From 84fedbdb60a09da6ec6ddf8e9dac9099c41a16a0 Mon Sep 17 00:00:00 2001 From: Guenter Obiltschnig Date: Mon, 23 Oct 2006 15:48:43 +0000 Subject: [PATCH] set eol-style to native --- Foundation/Foundation_vs71.sln | 96 +- Foundation/Foundation_vs71.vcproj | 4874 ++-- Foundation/Foundation_vs80.sln | 90 +- Foundation/Foundation_vs80.vcproj | 6382 +++--- Foundation/Makefile | 82 +- Foundation/foundation.vmsbuild | 252 +- Foundation/include/Poco/ASCIIEncoding.h | 136 +- Foundation/include/Poco/AbstractCache.h | 550 +- Foundation/include/Poco/AbstractDelegate.h | 192 +- Foundation/include/Poco/AbstractEvent.h | 608 +- Foundation/include/Poco/AbstractObserver.h | 142 +- .../include/Poco/AbstractPriorityDelegate.h | 218 +- Foundation/include/Poco/AbstractStrategy.h | 182 +- Foundation/include/Poco/ActiveDispatcher.h | 274 +- Foundation/include/Poco/ActiveMethod.h | 260 +- Foundation/include/Poco/ActiveResult.h | 578 +- Foundation/include/Poco/ActiveRunnable.h | 206 +- Foundation/include/Poco/ActiveStarter.h | 142 +- Foundation/include/Poco/Activity.h | 436 +- Foundation/include/Poco/Any.h | 572 +- Foundation/include/Poco/ArchiveStrategy.h | 258 +- Foundation/include/Poco/AsyncChannel.h | 220 +- Foundation/include/Poco/AutoPtr.h | 672 +- Foundation/include/Poco/AutoReleasePool.h | 216 +- Foundation/include/Poco/Base64Decoder.h | 204 +- Foundation/include/Poco/Base64Encoder.h | 224 +- Foundation/include/Poco/BasicEvent.h | 176 +- Foundation/include/Poco/BinaryReader.h | 374 +- Foundation/include/Poco/BinaryWriter.h | 398 +- Foundation/include/Poco/Buffer.h | 258 +- Foundation/include/Poco/BufferAllocator.h | 146 +- .../Poco/BufferedBidirectionalStreamBuf.h | 354 +- Foundation/include/Poco/BufferedStreamBuf.h | 348 +- Foundation/include/Poco/Bugcheck.h | 252 +- Foundation/include/Poco/ByteOrder.h | 454 +- Foundation/include/Poco/Channel.h | 192 +- Foundation/include/Poco/ClassLibrary.h | 208 +- Foundation/include/Poco/ClassLoader.h | 716 +- Foundation/include/Poco/CompareFunctions.h | 126 +- Foundation/include/Poco/Config.h | 110 +- Foundation/include/Poco/Configurable.h | 184 +- Foundation/include/Poco/ConsoleChannel.h | 178 +- Foundation/include/Poco/CountingStream.h | 482 +- Foundation/include/Poco/DateTime.h | 854 +- Foundation/include/Poco/DateTimeFormat.h | 246 +- Foundation/include/Poco/DateTimeFormatter.h | 274 +- Foundation/include/Poco/DateTimeParser.h | 238 +- Foundation/include/Poco/Debugger.h | 190 +- Foundation/include/Poco/DefaultStrategy.h | 308 +- Foundation/include/Poco/DeflatingStream.h | 282 +- Foundation/include/Poco/Delegate.h | 218 +- Foundation/include/Poco/DigestEngine.h | 250 +- Foundation/include/Poco/DigestStream.h | 244 +- Foundation/include/Poco/DirectoryIterator.h | 316 +- .../include/Poco/DirectoryIterator_UNIX.h | 188 +- .../include/Poco/DirectoryIterator_VMS.h | 194 +- .../include/Poco/DirectoryIterator_WIN32.h | 190 +- .../include/Poco/DirectoryIterator_WIN32U.h | 190 +- Foundation/include/Poco/DynamicFactory.h | 316 +- Foundation/include/Poco/Environment.h | 168 +- Foundation/include/Poco/Environment_UNIX.h | 146 +- Foundation/include/Poco/Environment_VMS.h | 148 +- Foundation/include/Poco/Environment_WIN32.h | 130 +- Foundation/include/Poco/Environment_WIN32U.h | 130 +- Foundation/include/Poco/ErrorHandler.h | 284 +- Foundation/include/Poco/Event.h | 286 +- Foundation/include/Poco/EventArgs.h | 132 +- Foundation/include/Poco/EventLogChannel.h | 254 +- Foundation/include/Poco/Event_POSIX.h | 198 +- Foundation/include/Poco/Event_WIN32.h | 180 +- Foundation/include/Poco/Exception.h | 504 +- Foundation/include/Poco/Expire.h | 264 +- Foundation/include/Poco/ExpireCache.h | 156 +- Foundation/include/Poco/ExpireLRUCache.h | 164 +- Foundation/include/Poco/ExpireStrategy.h | 300 +- Foundation/include/Poco/FIFOEvent.h | 180 +- Foundation/include/Poco/FIFOStrategy.h | 320 +- Foundation/include/Poco/FPEnvironment.h | 454 +- Foundation/include/Poco/FPEnvironment_C99.h | 294 +- Foundation/include/Poco/FPEnvironment_DEC.h | 222 +- Foundation/include/Poco/FPEnvironment_DUMMY.h | 294 +- Foundation/include/Poco/FPEnvironment_SUN.h | 192 +- Foundation/include/Poco/FPEnvironment_WIN32.h | 306 +- Foundation/include/Poco/File.h | 506 +- Foundation/include/Poco/FileChannel.h | 496 +- Foundation/include/Poco/FileStreamFactory.h | 166 +- Foundation/include/Poco/File_UNIX.h | 196 +- Foundation/include/Poco/File_VMS.h | 194 +- Foundation/include/Poco/File_WIN32.h | 200 +- Foundation/include/Poco/File_WIN32U.h | 202 +- Foundation/include/Poco/Format.h | 308 +- Foundation/include/Poco/Formatter.h | 192 +- Foundation/include/Poco/FormattingChannel.h | 236 +- Foundation/include/Poco/Foundation.h | 208 +- Foundation/include/Poco/Glob.h | 316 +- Foundation/include/Poco/HMACEngine.h | 332 +- Foundation/include/Poco/HashFunction.h | 164 +- Foundation/include/Poco/HashStatistic.h | 294 +- Foundation/include/Poco/HashTable.h | 724 +- Foundation/include/Poco/HexBinaryDecoder.h | 208 +- Foundation/include/Poco/HexBinaryEncoder.h | 234 +- Foundation/include/Poco/InflatingStream.h | 278 +- Foundation/include/Poco/Instantiator.h | 208 +- Foundation/include/Poco/KeyValueArgs.h | 190 +- Foundation/include/Poco/LRUCache.h | 146 +- Foundation/include/Poco/LRUStrategy.h | 322 +- Foundation/include/Poco/Latin1Encoding.h | 136 +- Foundation/include/Poco/Latin9Encoding.h | 142 +- Foundation/include/Poco/LineEndingConverter.h | 406 +- Foundation/include/Poco/LocalDateTime.h | 740 +- Foundation/include/Poco/LogFile.h | 230 +- Foundation/include/Poco/LogFile_STD.h | 148 +- Foundation/include/Poco/LogFile_VMS.h | 150 +- Foundation/include/Poco/LogFile_WIN32.h | 148 +- Foundation/include/Poco/LogFile_WIN32U.h | 148 +- Foundation/include/Poco/LogStream.h | 332 +- Foundation/include/Poco/Logger.h | 966 +- Foundation/include/Poco/LoggingFactory.h | 230 +- Foundation/include/Poco/LoggingRegistry.h | 242 +- Foundation/include/Poco/MD2Engine.h | 218 +- Foundation/include/Poco/MD4Engine.h | 228 +- Foundation/include/Poco/MD5Engine.h | 228 +- Foundation/include/Poco/Manifest.h | 404 +- Foundation/include/Poco/MemoryPool.h | 268 +- Foundation/include/Poco/Message.h | 416 +- Foundation/include/Poco/MetaObject.h | 446 +- Foundation/include/Poco/Mutex.h | 348 +- Foundation/include/Poco/Mutex_POSIX.h | 216 +- Foundation/include/Poco/Mutex_WIN32.h | 212 +- Foundation/include/Poco/NObserver.h | 270 +- Foundation/include/Poco/NamedEvent.h | 236 +- Foundation/include/Poco/NamedEvent_UNIX.h | 154 +- Foundation/include/Poco/NamedEvent_VMS.h | 132 +- Foundation/include/Poco/NamedEvent_WIN32.h | 134 +- Foundation/include/Poco/NamedEvent_WIN32U.h | 136 +- Foundation/include/Poco/NamedMutex.h | 264 +- Foundation/include/Poco/NamedMutex_UNIX.h | 160 +- Foundation/include/Poco/NamedMutex_VMS.h | 140 +- Foundation/include/Poco/NamedMutex_WIN32.h | 136 +- Foundation/include/Poco/NamedMutex_WIN32U.h | 138 +- .../include/Poco/NestedDiagnosticContext.h | 376 +- Foundation/include/Poco/Notification.h | 148 +- Foundation/include/Poco/NotificationCenter.h | 304 +- Foundation/include/Poco/NotificationQueue.h | 330 +- .../include/Poco/NotificationStrategy.h | 158 +- Foundation/include/Poco/NullChannel.h | 154 +- Foundation/include/Poco/NullStream.h | 224 +- Foundation/include/Poco/NumberFormatter.h | 430 +- Foundation/include/Poco/NumberParser.h | 248 +- Foundation/include/Poco/Observer.h | 264 +- Foundation/include/Poco/OpcomChannel.h | 204 +- Foundation/include/Poco/Path.h | 952 +- Foundation/include/Poco/Path_UNIX.h | 130 +- Foundation/include/Poco/Path_VMS.h | 130 +- Foundation/include/Poco/Path_WIN32.h | 130 +- Foundation/include/Poco/Path_WIN32U.h | 140 +- Foundation/include/Poco/PatternFormatter.h | 290 +- Foundation/include/Poco/Pipe.h | 328 +- Foundation/include/Poco/PipeImpl.h | 110 +- Foundation/include/Poco/PipeImpl_DUMMY.h | 142 +- Foundation/include/Poco/PipeImpl_POSIX.h | 150 +- Foundation/include/Poco/PipeImpl_WIN32.h | 152 +- Foundation/include/Poco/PipeStream.h | 284 +- Foundation/include/Poco/Platform.h | 362 +- Foundation/include/Poco/Platform_POSIX.h | 114 +- Foundation/include/Poco/Platform_VMS.h | 184 +- Foundation/include/Poco/Platform_WIN32.h | 172 +- Foundation/include/Poco/Poco.h | 92 +- Foundation/include/Poco/PriorityDelegate.h | 220 +- Foundation/include/Poco/PriorityEvent.h | 180 +- Foundation/include/Poco/PriorityExpire.h | 264 +- Foundation/include/Poco/Process.h | 372 +- Foundation/include/Poco/Process_UNIX.h | 172 +- Foundation/include/Poco/Process_VMS.h | 174 +- Foundation/include/Poco/Process_WIN32.h | 174 +- Foundation/include/Poco/Process_WIN32U.h | 174 +- Foundation/include/Poco/PurgeStrategy.h | 238 +- Foundation/include/Poco/RWLock.h | 336 +- Foundation/include/Poco/RWLock_POSIX.h | 242 +- Foundation/include/Poco/RWLock_WIN32.h | 154 +- Foundation/include/Poco/Random.h | 382 +- Foundation/include/Poco/RandomStream.h | 190 +- Foundation/include/Poco/RefCountedObject.h | 196 +- Foundation/include/Poco/RegularExpression.h | 464 +- Foundation/include/Poco/RotateStrategy.h | 360 +- Foundation/include/Poco/Runnable.h | 134 +- Foundation/include/Poco/RunnableAdapter.h | 192 +- Foundation/include/Poco/SHA1Engine.h | 200 +- Foundation/include/Poco/ScopedLock.h | 156 +- Foundation/include/Poco/Semaphore.h | 314 +- Foundation/include/Poco/Semaphore_POSIX.h | 194 +- Foundation/include/Poco/Semaphore_WIN32.h | 160 +- Foundation/include/Poco/SharedLibrary.h | 244 +- Foundation/include/Poco/SharedLibrary_HPUX.h | 146 +- Foundation/include/Poco/SharedLibrary_UNIX.h | 144 +- Foundation/include/Poco/SharedLibrary_VMS.h | 142 +- Foundation/include/Poco/SharedLibrary_WIN32.h | 144 +- .../include/Poco/SharedLibrary_WIN32U.h | 144 +- Foundation/include/Poco/SharedPtr.h | 740 +- Foundation/include/Poco/SignalHandler.h | 288 +- Foundation/include/Poco/SimpleFileChannel.h | 312 +- Foundation/include/Poco/SimpleHashTable.h | 814 +- Foundation/include/Poco/SingletonHolder.h | 178 +- Foundation/include/Poco/SplitterChannel.h | 198 +- Foundation/include/Poco/Stopwatch.h | 248 +- Foundation/include/Poco/StrategyCollection.h | 310 +- Foundation/include/Poco/StreamChannel.h | 162 +- Foundation/include/Poco/StreamConverter.h | 300 +- Foundation/include/Poco/StreamCopier.h | 152 +- Foundation/include/Poco/StreamTokenizer.h | 238 +- Foundation/include/Poco/StreamUtil.h | 202 +- Foundation/include/Poco/String.h | 1010 +- Foundation/include/Poco/StringTokenizer.h | 260 +- Foundation/include/Poco/SynchronizedObject.h | 306 +- Foundation/include/Poco/SyslogChannel.h | 262 +- Foundation/include/Poco/Task.h | 414 +- Foundation/include/Poco/TaskManager.h | 306 +- Foundation/include/Poco/TaskNotification.h | 384 +- Foundation/include/Poco/TeeStream.h | 308 +- Foundation/include/Poco/TemporaryFile.h | 204 +- Foundation/include/Poco/TextConverter.h | 188 +- Foundation/include/Poco/TextEncoding.h | 212 +- Foundation/include/Poco/TextIterator.h | 302 +- Foundation/include/Poco/Thread.h | 392 +- Foundation/include/Poco/ThreadLocal.h | 358 +- Foundation/include/Poco/ThreadPool.h | 340 +- Foundation/include/Poco/Thread_POSIX.h | 272 +- Foundation/include/Poco/Thread_WIN32.h | 232 +- Foundation/include/Poco/Timer.h | 430 +- Foundation/include/Poco/Timespan.h | 640 +- Foundation/include/Poco/Timestamp.h | 520 +- Foundation/include/Poco/Timezone.h | 178 +- Foundation/include/Poco/Token.h | 366 +- Foundation/include/Poco/Types.h | 428 +- Foundation/include/Poco/URI.h | 730 +- Foundation/include/Poco/URIStreamFactory.h | 170 +- Foundation/include/Poco/URIStreamOpener.h | 302 +- Foundation/include/Poco/UTF16Encoding.h | 204 +- Foundation/include/Poco/UTF8Encoding.h | 136 +- Foundation/include/Poco/UUID.h | 466 +- Foundation/include/Poco/UUIDGenerator.h | 236 +- Foundation/include/Poco/UnbufferedStreamBuf.h | 382 +- Foundation/include/Poco/UnicodeConverter.h | 162 +- Foundation/include/Poco/ValidArgs.h | 192 +- Foundation/include/Poco/Void.h | 180 +- Foundation/include/Poco/Windows1252Encoding.h | 136 +- Foundation/include/Poco/zconf.h | 664 +- Foundation/include/Poco/zlib.h | 2714 +-- .../ActiveMethod/ActiveMethod.vmsbuild | 16 +- .../ActiveMethod/ActiveMethod_vs71.vcproj | 298 +- .../ActiveMethod/ActiveMethod_vs80.vcproj | 426 +- Foundation/samples/ActiveMethod/Makefile | 34 +- .../samples/ActiveMethod/src/ActiveMethod.cpp | 156 +- Foundation/samples/Activity/Activity.vmsbuild | 16 +- .../samples/Activity/Activity_vs71.vcproj | 298 +- .../samples/Activity/Activity_vs80.vcproj | 426 +- Foundation/samples/Activity/Makefile | 34 +- Foundation/samples/Activity/src/Activity.cpp | 180 +- .../BinaryReaderWriter.vmsbuild | 16 +- .../BinaryReaderWriter_vs71.vcproj | 298 +- .../BinaryReaderWriter_vs80.vcproj | 426 +- .../samples/BinaryReaderWriter/Makefile | 34 +- .../src/BinaryReaderWriter.cpp | 152 +- Foundation/samples/DateTime/DateTime.vmsbuild | 16 +- .../samples/DateTime/DateTime_vs71.vcproj | 298 +- .../samples/DateTime/DateTime_vs80.vcproj | 426 +- Foundation/samples/DateTime/Makefile | 34 +- Foundation/samples/DateTime/src/DateTime.cpp | 122 +- Foundation/samples/Logger/Logger.vmsbuild | 16 +- Foundation/samples/Logger/Logger_vs71.vcproj | 298 +- Foundation/samples/Logger/Logger_vs80.vcproj | 426 +- Foundation/samples/Logger/Makefile | 34 +- Foundation/samples/Logger/src/Logger.cpp | 164 +- Foundation/samples/Makefile | 58 +- Foundation/samples/NotificationQueue/Makefile | 34 +- .../NotificationQueue.vmsbuild | 16 +- .../NotificationQueue_vs71.vcproj | 298 +- .../NotificationQueue_vs80.vcproj | 426 +- .../src/NotificationQueue.cpp | 298 +- Foundation/samples/StringTokenizer/Makefile | 34 +- .../StringTokenizer/StringTokenizer.vmsbuild | 16 +- .../StringTokenizer_vs71.vcproj | 298 +- .../StringTokenizer_vs80.vcproj | 426 +- .../StringTokenizer/src/StringTokenizer.cpp | 102 +- Foundation/samples/Timer/Makefile | 34 +- Foundation/samples/Timer/Timer.vmsbuild | 16 +- Foundation/samples/Timer/Timer_vs71.vcproj | 298 +- Foundation/samples/Timer/Timer_vs80.vcproj | 426 +- Foundation/samples/Timer/src/Timer.cpp | 154 +- Foundation/samples/URI/Makefile | 34 +- Foundation/samples/URI/URI.vmsbuild | 16 +- Foundation/samples/URI/URI_vs71.vcproj | 298 +- Foundation/samples/URI/URI_vs80.vcproj | 426 +- Foundation/samples/URI/src/URI.cpp | 120 +- Foundation/samples/base64decode/Makefile | 34 +- .../base64decode/base64decode.vmsbuild | 16 +- .../base64decode/base64decode_vs71.vcproj | 298 +- .../base64decode/base64decode_vs80.vcproj | 426 +- .../samples/base64decode/src/base64decode.cpp | 156 +- Foundation/samples/base64encode/Makefile | 34 +- .../base64encode/base64encode.vmsbuild | 16 +- .../base64encode/base64encode_vs71.vcproj | 298 +- .../base64encode/base64encode_vs80.vcproj | 426 +- .../samples/base64encode/src/base64encode.cpp | 156 +- Foundation/samples/deflate/Makefile | 34 +- Foundation/samples/deflate/deflate.vmsbuild | 16 +- .../samples/deflate/deflate_vs71.vcproj | 298 +- .../samples/deflate/deflate_vs80.vcproj | 426 +- Foundation/samples/deflate/src/deflate.cpp | 156 +- Foundation/samples/dir/Makefile | 34 +- Foundation/samples/dir/dir.vmsbuild | 16 +- Foundation/samples/dir/dir_vs71.vcproj | 298 +- Foundation/samples/dir/dir_vs80.vcproj | 426 +- Foundation/samples/dir/src/dir.cpp | 168 +- Foundation/samples/grep/Makefile | 34 +- Foundation/samples/grep/grep.vmsbuild | 16 +- Foundation/samples/grep/grep_vs71.vcproj | 298 +- Foundation/samples/grep/grep_vs80.vcproj | 426 +- Foundation/samples/grep/src/grep.cpp | 166 +- Foundation/samples/hmacmd5/Makefile | 34 +- Foundation/samples/hmacmd5/hmacmd5.vmsbuild | 16 +- .../samples/hmacmd5/hmacmd5_vs71.vcproj | 298 +- .../samples/hmacmd5/hmacmd5_vs80.vcproj | 426 +- Foundation/samples/hmacmd5/src/hmacmd5.cpp | 154 +- Foundation/samples/inflate/Makefile | 34 +- Foundation/samples/inflate/inflate.vmsbuild | 16 +- .../samples/inflate/inflate_vs71.vcproj | 298 +- .../samples/inflate/inflate_vs80.vcproj | 426 +- Foundation/samples/inflate/src/inflate.cpp | 156 +- Foundation/samples/md5/Makefile | 34 +- Foundation/samples/md5/md5.vmsbuild | 16 +- Foundation/samples/md5/md5_vs71.vcproj | 298 +- Foundation/samples/md5/md5_vs80.vcproj | 426 +- Foundation/samples/md5/src/md5.cpp | 148 +- Foundation/samples/samples_vs71.sln | 314 +- Foundation/samples/samples_vs80.sln | 242 +- Foundation/samples/uuidgen/Makefile | 34 +- Foundation/samples/uuidgen/src/uuidgen.cpp | 144 +- Foundation/samples/uuidgen/uuidgen.vmsbuild | 16 +- .../samples/uuidgen/uuidgen_vs71.vcproj | 298 +- .../samples/uuidgen/uuidgen_vs80.vcproj | 426 +- Foundation/src/ASCIIEncoding.cpp | 194 +- Foundation/src/AbstractObserver.cpp | 128 +- Foundation/src/ActiveDispatcher.cpp | 266 +- Foundation/src/ArchiveStrategy.cpp | 422 +- Foundation/src/AsyncChannel.cpp | 294 +- Foundation/src/Base64Decoder.cpp | 306 +- Foundation/src/Base64Encoder.cpp | 362 +- Foundation/src/BinaryReader.cpp | 558 +- Foundation/src/BinaryWriter.cpp | 656 +- Foundation/src/Bugcheck.cpp | 206 +- Foundation/src/ByteOrder.cpp | 74 +- Foundation/src/Channel.cpp | 150 +- Foundation/src/Configurable.cpp | 106 +- Foundation/src/ConsoleChannel.cpp | 142 +- Foundation/src/CountingStream.cpp | 370 +- Foundation/src/DateTime.cpp | 820 +- Foundation/src/DateTimeFormat.cpp | 164 +- Foundation/src/DateTimeFormatter.cpp | 376 +- Foundation/src/DateTimeParser.cpp | 738 +- Foundation/src/Debugger.cpp | 330 +- Foundation/src/DeflatingStream.cpp | 574 +- Foundation/src/DigestEngine.cpp | 136 +- Foundation/src/DigestStream.cpp | 344 +- Foundation/src/DirectoryIterator.cpp | 342 +- Foundation/src/DirectoryIterator_UNIX.cpp | 156 +- Foundation/src/DirectoryIterator_VMS.cpp | 174 +- Foundation/src/DirectoryIterator_WIN32.cpp | 170 +- Foundation/src/DirectoryIterator_WIN32U.cpp | 180 +- Foundation/src/Environment.cpp | 192 +- Foundation/src/Environment_UNIX.cpp | 240 +- Foundation/src/Environment_VMS.cpp | 342 +- Foundation/src/Environment_WIN32.cpp | 294 +- Foundation/src/Environment_WIN32U.cpp | 324 +- Foundation/src/ErrorHandler.cpp | 266 +- Foundation/src/Event.cpp | 120 +- Foundation/src/EventArgs.cpp | 110 +- Foundation/src/EventLogChannel.cpp | 630 +- Foundation/src/Event_POSIX.cpp | 234 +- Foundation/src/Event_WIN32.cpp | 166 +- Foundation/src/Exception.cpp | 368 +- Foundation/src/FPEnvironment.cpp | 214 +- Foundation/src/FPEnvironment_C99.cpp | 208 +- Foundation/src/FPEnvironment_DEC.cpp | 434 +- Foundation/src/FPEnvironment_DUMMY.cpp | 202 +- Foundation/src/FPEnvironment_SUN.cpp | 322 +- Foundation/src/FPEnvironment_WIN32.cpp | 196 +- Foundation/src/File.cpp | 602 +- Foundation/src/FileChannel.cpp | 716 +- Foundation/src/FileStreamFactory.cpp | 172 +- Foundation/src/File_UNIX.cpp | 776 +- Foundation/src/File_VMS.cpp | 762 +- Foundation/src/File_WIN32.cpp | 718 +- Foundation/src/File_WIN32U.cpp | 734 +- Foundation/src/Format.cpp | 668 +- Foundation/src/Formatter.cpp | 132 +- Foundation/src/FormattingChannel.cpp | 296 +- Foundation/src/Glob.cpp | 484 +- Foundation/src/HashStatistic.cpp | 172 +- Foundation/src/HexBinaryDecoder.cpp | 230 +- Foundation/src/HexBinaryEncoder.cpp | 280 +- Foundation/src/InflatingStream.cpp | 506 +- Foundation/src/Latin1Encoding.cpp | 194 +- Foundation/src/Latin9Encoding.cpp | 216 +- Foundation/src/LineEndingConverter.cpp | 408 +- Foundation/src/LocalDateTime.cpp | 506 +- Foundation/src/LogFile.cpp | 128 +- Foundation/src/LogFile_STD.cpp | 172 +- Foundation/src/LogFile_VMS.cpp | 182 +- Foundation/src/LogFile_WIN32.cpp | 218 +- Foundation/src/LogFile_WIN32U.cpp | 224 +- Foundation/src/LogStream.cpp | 362 +- Foundation/src/Logger.cpp | 916 +- Foundation/src/LoggingFactory.cpp | 250 +- Foundation/src/LoggingRegistry.cpp | 268 +- Foundation/src/MD2Engine.cpp | 432 +- Foundation/src/MD4Engine.cpp | 600 +- Foundation/src/MD5Engine.cpp | 662 +- Foundation/src/Manifest.cpp | 106 +- Foundation/src/MemoryPool.cpp | 206 +- Foundation/src/Message.cpp | 404 +- Foundation/src/Mutex.cpp | 140 +- Foundation/src/Mutex_POSIX.cpp | 190 +- Foundation/src/Mutex_WIN32.cpp | 112 +- Foundation/src/NamedEvent.cpp | 130 +- Foundation/src/NamedEvent_UNIX.cpp | 338 +- Foundation/src/NamedEvent_VMS.cpp | 170 +- Foundation/src/NamedEvent_WIN32.cpp | 156 +- Foundation/src/NamedEvent_WIN32U.cpp | 160 +- Foundation/src/NamedMutex.cpp | 130 +- Foundation/src/NamedMutex_UNIX.cpp | 366 +- Foundation/src/NamedMutex_VMS.cpp | 174 +- Foundation/src/NamedMutex_WIN32.cpp | 190 +- Foundation/src/NamedMutex_WIN32U.cpp | 194 +- Foundation/src/NestedDiagnosticContext.cpp | 292 +- Foundation/src/Notification.cpp | 120 +- Foundation/src/NotificationCenter.cpp | 252 +- Foundation/src/NotificationQueue.cpp | 454 +- Foundation/src/NullChannel.cpp | 126 +- Foundation/src/NullStream.cpp | 192 +- Foundation/src/NumberFormatter.cpp | 768 +- Foundation/src/NumberParser.cpp | 346 +- Foundation/src/OpcomChannel.cpp | 398 +- Foundation/src/Path.cpp | 1974 +- Foundation/src/Path_UNIX.cpp | 324 +- Foundation/src/Path_VMS.cpp | 278 +- Foundation/src/Path_WIN32.cpp | 240 +- Foundation/src/Path_WIN32U.cpp | 274 +- Foundation/src/PatternFormatter.cpp | 380 +- Foundation/src/Pipe.cpp | 184 +- Foundation/src/PipeImpl.cpp | 92 +- Foundation/src/PipeImpl_DUMMY.cpp | 174 +- Foundation/src/PipeImpl_POSIX.cpp | 264 +- Foundation/src/PipeImpl_WIN32.cpp | 238 +- Foundation/src/PipeStream.cpp | 298 +- Foundation/src/Process.cpp | 272 +- Foundation/src/Process_UNIX.cpp | 412 +- Foundation/src/Process_VMS.cpp | 308 +- Foundation/src/Process_WIN32.cpp | 430 +- Foundation/src/Process_WIN32U.cpp | 438 +- Foundation/src/PurgeStrategy.cpp | 306 +- Foundation/src/RWLock.cpp | 120 +- Foundation/src/RWLock_POSIX.cpp | 112 +- Foundation/src/RWLock_WIN32.cpp | 398 +- Foundation/src/Random.cpp | 764 +- Foundation/src/RandomStream.cpp | 298 +- Foundation/src/RefCountedObject.cpp | 140 +- Foundation/src/RegularExpression.cpp | 582 +- Foundation/src/RotateStrategy.cpp | 206 +- Foundation/src/Runnable.cpp | 106 +- Foundation/src/SHA1Engine.cpp | 610 +- Foundation/src/Semaphore.cpp | 130 +- Foundation/src/Semaphore_POSIX.cpp | 236 +- Foundation/src/Semaphore_WIN32.cpp | 174 +- Foundation/src/SharedLibrary.cpp | 238 +- Foundation/src/SharedLibrary_HPUX.cpp | 232 +- Foundation/src/SharedLibrary_UNIX.cpp | 294 +- Foundation/src/SharedLibrary_VMS.cpp | 278 +- Foundation/src/SharedLibrary_WIN32.cpp | 232 +- Foundation/src/SharedLibrary_WIN32U.cpp | 238 +- Foundation/src/SignalHandler.cpp | 254 +- Foundation/src/SimpleFileChannel.cpp | 456 +- Foundation/src/SplitterChannel.cpp | 256 +- Foundation/src/Stopwatch.cpp | 164 +- Foundation/src/StreamChannel.cpp | 124 +- Foundation/src/StreamConverter.cpp | 438 +- Foundation/src/StreamCopier.cpp | 210 +- Foundation/src/StreamTokenizer.cpp | 254 +- Foundation/src/String.cpp | 316 +- Foundation/src/StringTokenizer.cpp | 174 +- Foundation/src/SynchronizedObject.cpp | 106 +- Foundation/src/SyslogChannel.cpp | 556 +- Foundation/src/Task.cpp | 302 +- Foundation/src/TaskManager.cpp | 330 +- Foundation/src/TaskNotification.cpp | 228 +- Foundation/src/TeeStream.cpp | 310 +- Foundation/src/TemporaryFile.cpp | 288 +- Foundation/src/TextConverter.cpp | 254 +- Foundation/src/TextEncoding.cpp | 122 +- Foundation/src/TextIterator.cpp | 326 +- Foundation/src/Thread.cpp | 286 +- Foundation/src/ThreadLocal.cpp | 204 +- Foundation/src/ThreadPool.cpp | 986 +- Foundation/src/Thread_POSIX.cpp | 442 +- Foundation/src/Thread_WIN32.cpp | 320 +- Foundation/src/Timer.cpp | 420 +- Foundation/src/Timespan.cpp | 344 +- Foundation/src/Timestamp.cpp | 344 +- Foundation/src/Timezone.cpp | 114 +- Foundation/src/Timezone_UNIX.cpp | 236 +- Foundation/src/Timezone_WIN32.cpp | 204 +- Foundation/src/Token.cpp | 336 +- Foundation/src/URI.cpp | 1682 +- Foundation/src/URIStreamFactory.cpp | 106 +- Foundation/src/URIStreamOpener.cpp | 348 +- Foundation/src/UTF16Encoding.cpp | 322 +- Foundation/src/UTF8Encoding.cpp | 320 +- Foundation/src/UUID.cpp | 744 +- Foundation/src/UUIDGenerator.cpp | 722 +- Foundation/src/UnicodeConverter.cpp | 272 +- Foundation/src/Void.cpp | 158 +- Foundation/src/Windows1252Encoding.cpp | 196 +- Foundation/src/adler32.c | 298 +- Foundation/src/chartables.c | 366 +- Foundation/src/compress.c | 158 +- Foundation/src/crc32.c | 846 +- Foundation/src/crc32.h | 882 +- Foundation/src/deflate.c | 3472 +-- Foundation/src/deflate.h | 662 +- Foundation/src/get.c | 714 +- Foundation/src/gzio.c | 2052 +- Foundation/src/infback.c | 1246 +- Foundation/src/inffast.c | 636 +- Foundation/src/inffast.h | 22 +- Foundation/src/inffixed.h | 188 +- Foundation/src/inflate.c | 2736 +-- Foundation/src/inflate.h | 230 +- Foundation/src/inftrees.c | 658 +- Foundation/src/inftrees.h | 110 +- Foundation/src/maketables.c | 292 +- Foundation/src/pcre.c | 18390 ++++++++-------- Foundation/src/pcre.h | 478 +- Foundation/src/pcreconfig.h | 250 +- Foundation/src/pcreinternal.h | 1504 +- Foundation/src/pocomsg.h | 316 +- Foundation/src/pocomsg.mc | 178 +- Foundation/src/pocomsg.rc | 4 +- Foundation/src/study.c | 968 +- Foundation/src/trees.c | 2446 +- Foundation/src/trees.h | 256 +- Foundation/src/zconf.h | 664 +- Foundation/src/zlib.h | 2714 +-- Foundation/src/zutil.c | 636 +- Foundation/src/zutil.h | 538 +- Foundation/testsuite/Makefile | 28 +- Foundation/testsuite/Makefile-Driver | 84 +- Foundation/testsuite/Makefile-TestApp | 34 +- Foundation/testsuite/Makefile-TestLibrary | 34 +- Foundation/testsuite/TestApp_vs71.vcproj | 286 +- Foundation/testsuite/TestApp_vs80.vcproj | 416 +- Foundation/testsuite/TestLibrary_vs71.vcproj | 316 +- Foundation/testsuite/TestLibrary_vs80.vcproj | 452 +- Foundation/testsuite/TestSuite_vs71.vcproj | 1978 +- Foundation/testsuite/TestSuite_vs80.vcproj | 2530 +-- .../testsuite/src/ActiveDispatcherTest.cpp | 380 +- .../testsuite/src/ActiveDispatcherTest.h | 152 +- Foundation/testsuite/src/ActiveMethodTest.cpp | 348 +- Foundation/testsuite/src/ActiveMethodTest.h | 126 +- Foundation/testsuite/src/ActivityTest.cpp | 248 +- Foundation/testsuite/src/ActivityTest.h | 120 +- Foundation/testsuite/src/AnyTest.cpp | 284 +- Foundation/testsuite/src/AnyTest.h | 116 +- Foundation/testsuite/src/AutoPtrTest.cpp | 408 +- Foundation/testsuite/src/AutoPtrTest.h | 122 +- .../testsuite/src/AutoReleasePoolTest.cpp | 252 +- .../testsuite/src/AutoReleasePoolTest.h | 120 +- Foundation/testsuite/src/Base64Test.cpp | 398 +- Foundation/testsuite/src/Base64Test.h | 124 +- Foundation/testsuite/src/BasicEventTest.cpp | 716 +- Foundation/testsuite/src/BasicEventTest.h | 178 +- .../testsuite/src/BinaryReaderWriterTest.cpp | 508 +- .../testsuite/src/BinaryReaderWriterTest.h | 132 +- Foundation/testsuite/src/ByteOrderTest.cpp | 1266 +- Foundation/testsuite/src/ByteOrderTest.h | 126 +- Foundation/testsuite/src/CacheTestSuite.cpp | 94 +- Foundation/testsuite/src/CacheTestSuite.h | 98 +- Foundation/testsuite/src/ChannelTest.cpp | 320 +- Foundation/testsuite/src/ChannelTest.h | 128 +- Foundation/testsuite/src/ClassLoaderTest.cpp | 468 +- Foundation/testsuite/src/ClassLoaderTest.h | 124 +- Foundation/testsuite/src/CoreTest.cpp | 330 +- Foundation/testsuite/src/CoreTest.h | 128 +- Foundation/testsuite/src/CoreTestSuite.cpp | 152 +- Foundation/testsuite/src/CoreTestSuite.h | 98 +- .../testsuite/src/CountingStreamTest.cpp | 248 +- Foundation/testsuite/src/CountingStreamTest.h | 122 +- Foundation/testsuite/src/CryptTestSuite.cpp | 116 +- Foundation/testsuite/src/CryptTestSuite.h | 98 +- .../testsuite/src/DateTimeFormatterTest.cpp | 458 +- .../testsuite/src/DateTimeFormatterTest.h | 138 +- .../testsuite/src/DateTimeParserTest.cpp | 1102 +- Foundation/testsuite/src/DateTimeParserTest.h | 142 +- Foundation/testsuite/src/DateTimeTest.cpp | 1736 +- Foundation/testsuite/src/DateTimeTest.h | 148 +- .../testsuite/src/DateTimeTestSuite.cpp | 112 +- Foundation/testsuite/src/DateTimeTestSuite.h | 98 +- Foundation/testsuite/src/DigestStreamTest.cpp | 230 +- Foundation/testsuite/src/DigestStreamTest.h | 124 +- Foundation/testsuite/src/Driver.cpp | 78 +- Foundation/testsuite/src/DummyDelegate.cpp | 110 +- Foundation/testsuite/src/DummyDelegate.h | 100 +- .../testsuite/src/DynamicFactoryTest.cpp | 276 +- Foundation/testsuite/src/DynamicFactoryTest.h | 120 +- Foundation/testsuite/src/EventTestSuite.cpp | 94 +- Foundation/testsuite/src/EventTestSuite.h | 98 +- Foundation/testsuite/src/ExpireCacheTest.cpp | 352 +- Foundation/testsuite/src/ExpireCacheTest.h | 120 +- .../testsuite/src/ExpireLRUCacheTest.cpp | 622 +- Foundation/testsuite/src/ExpireLRUCacheTest.h | 126 +- Foundation/testsuite/src/FIFOEventTest.cpp | 888 +- Foundation/testsuite/src/FIFOEventTest.h | 182 +- Foundation/testsuite/src/FPETest.cpp | 336 +- Foundation/testsuite/src/FPETest.h | 124 +- Foundation/testsuite/src/FileChannelTest.cpp | 1082 +- Foundation/testsuite/src/FileChannelTest.h | 162 +- Foundation/testsuite/src/FileTest.cpp | 868 +- Foundation/testsuite/src/FileTest.h | 138 +- .../testsuite/src/FilesystemTestSuite.cpp | 96 +- .../testsuite/src/FilesystemTestSuite.h | 98 +- Foundation/testsuite/src/FormatTest.cpp | 620 +- Foundation/testsuite/src/FormatTest.h | 156 +- .../testsuite/src/FoundationTestSuite.cpp | 146 +- .../testsuite/src/FoundationTestSuite.h | 98 +- Foundation/testsuite/src/GlobTest.cpp | 890 +- Foundation/testsuite/src/GlobTest.h | 136 +- Foundation/testsuite/src/HMACEngineTest.cpp | 198 +- Foundation/testsuite/src/HMACEngineTest.h | 120 +- Foundation/testsuite/src/HashTest.cpp | 452 +- Foundation/testsuite/src/HashTest.h | 130 +- Foundation/testsuite/src/HexBinaryTest.cpp | 454 +- Foundation/testsuite/src/HexBinaryTest.h | 124 +- Foundation/testsuite/src/LRUCacheTest.cpp | 480 +- Foundation/testsuite/src/LRUCacheTest.h | 122 +- .../testsuite/src/LineEndingConverterTest.cpp | 330 +- .../testsuite/src/LineEndingConverterTest.h | 134 +- .../testsuite/src/LocalDateTimeTest.cpp | 782 +- Foundation/testsuite/src/LocalDateTimeTest.h | 138 +- Foundation/testsuite/src/LogStreamTest.cpp | 218 +- Foundation/testsuite/src/LogStreamTest.h | 146 +- Foundation/testsuite/src/LoggerTest.cpp | 502 +- Foundation/testsuite/src/LoggerTest.h | 124 +- .../testsuite/src/LoggingFactoryTest.cpp | 320 +- Foundation/testsuite/src/LoggingFactoryTest.h | 122 +- .../testsuite/src/LoggingRegistryTest.cpp | 376 +- .../testsuite/src/LoggingRegistryTest.h | 124 +- Foundation/testsuite/src/LoggingTestSuite.cpp | 116 +- Foundation/testsuite/src/LoggingTestSuite.h | 98 +- Foundation/testsuite/src/MD2EngineTest.cpp | 200 +- Foundation/testsuite/src/MD2EngineTest.h | 120 +- Foundation/testsuite/src/MD4EngineTest.cpp | 200 +- Foundation/testsuite/src/MD4EngineTest.h | 120 +- Foundation/testsuite/src/MD5EngineTest.cpp | 200 +- Foundation/testsuite/src/MD5EngineTest.h | 120 +- Foundation/testsuite/src/ManifestTest.cpp | 272 +- Foundation/testsuite/src/ManifestTest.h | 120 +- Foundation/testsuite/src/MemoryPoolTest.cpp | 220 +- Foundation/testsuite/src/MemoryPoolTest.h | 120 +- Foundation/testsuite/src/NDCTest.cpp | 214 +- Foundation/testsuite/src/NDCTest.h | 122 +- Foundation/testsuite/src/NamedEventTest.cpp | 244 +- Foundation/testsuite/src/NamedEventTest.h | 120 +- Foundation/testsuite/src/NamedMutexTest.cpp | 320 +- Foundation/testsuite/src/NamedMutexTest.h | 122 +- .../testsuite/src/NotificationCenterTest.cpp | 440 +- .../testsuite/src/NotificationCenterTest.h | 160 +- .../testsuite/src/NotificationQueueTest.cpp | 490 +- .../testsuite/src/NotificationQueueTest.h | 146 +- .../testsuite/src/NotificationsTestSuite.cpp | 92 +- .../testsuite/src/NotificationsTestSuite.h | 98 +- Foundation/testsuite/src/NullStreamTest.cpp | 182 +- Foundation/testsuite/src/NullStreamTest.h | 122 +- .../testsuite/src/NumberFormatterTest.cpp | 332 +- .../testsuite/src/NumberFormatterTest.h | 124 +- Foundation/testsuite/src/NumberParserTest.cpp | 338 +- Foundation/testsuite/src/NumberParserTest.h | 122 +- Foundation/testsuite/src/PathTest.cpp | 3304 +-- Foundation/testsuite/src/PathTest.h | 170 +- .../testsuite/src/PatternFormatterTest.cpp | 222 +- .../testsuite/src/PatternFormatterTest.h | 120 +- .../testsuite/src/PriorityEventTest.cpp | 938 +- Foundation/testsuite/src/PriorityEventTest.h | 182 +- Foundation/testsuite/src/ProcessTest.cpp | 316 +- Foundation/testsuite/src/ProcessTest.h | 124 +- .../testsuite/src/ProcessesTestSuite.cpp | 96 +- Foundation/testsuite/src/ProcessesTestSuite.h | 98 +- Foundation/testsuite/src/RWLockTest.cpp | 448 +- Foundation/testsuite/src/RWLockTest.h | 122 +- Foundation/testsuite/src/RandomStreamTest.cpp | 194 +- Foundation/testsuite/src/RandomStreamTest.h | 120 +- Foundation/testsuite/src/RandomTest.cpp | 344 +- Foundation/testsuite/src/RandomTest.h | 128 +- .../testsuite/src/RegularExpressionTest.cpp | 618 +- .../testsuite/src/RegularExpressionTest.h | 146 +- Foundation/testsuite/src/SHA1EngineTest.cpp | 176 +- Foundation/testsuite/src/SHA1EngineTest.h | 120 +- Foundation/testsuite/src/SemaphoreTest.cpp | 334 +- Foundation/testsuite/src/SemaphoreTest.h | 122 +- .../testsuite/src/SharedLibraryTest.cpp | 342 +- Foundation/testsuite/src/SharedLibraryTest.h | 124 +- .../testsuite/src/SharedLibraryTestSuite.cpp | 96 +- .../testsuite/src/SharedLibraryTestSuite.h | 98 +- Foundation/testsuite/src/SharedPtrTest.cpp | 468 +- Foundation/testsuite/src/SharedPtrTest.h | 126 +- .../testsuite/src/SimpleFileChannelTest.cpp | 294 +- .../testsuite/src/SimpleFileChannelTest.h | 124 +- Foundation/testsuite/src/StopwatchTest.cpp | 196 +- Foundation/testsuite/src/StopwatchTest.h | 120 +- .../testsuite/src/StreamConverterTest.cpp | 646 +- .../testsuite/src/StreamConverterTest.h | 138 +- Foundation/testsuite/src/StreamCopierTest.cpp | 260 +- Foundation/testsuite/src/StreamCopierTest.h | 124 +- .../testsuite/src/StreamTokenizerTest.cpp | 620 +- .../testsuite/src/StreamTokenizerTest.h | 132 +- Foundation/testsuite/src/StreamsTestSuite.cpp | 124 +- Foundation/testsuite/src/StreamsTestSuite.h | 98 +- Foundation/testsuite/src/StringTest.cpp | 652 +- Foundation/testsuite/src/StringTest.h | 142 +- .../testsuite/src/StringTokenizerTest.cpp | 614 +- .../testsuite/src/StringTokenizerTest.h | 120 +- Foundation/testsuite/src/TaskManagerTest.cpp | 968 +- Foundation/testsuite/src/TaskManagerTest.h | 140 +- Foundation/testsuite/src/TaskTest.cpp | 322 +- Foundation/testsuite/src/TaskTest.h | 124 +- Foundation/testsuite/src/TaskTestSuite.cpp | 92 +- Foundation/testsuite/src/TaskTestSuite.h | 98 +- Foundation/testsuite/src/TeeStreamTest.cpp | 192 +- Foundation/testsuite/src/TeeStreamTest.h | 122 +- Foundation/testsuite/src/TestApp.cpp | 110 +- Foundation/testsuite/src/TestChannel.cpp | 122 +- Foundation/testsuite/src/TestChannel.h | 122 +- Foundation/testsuite/src/TestLibrary.cpp | 234 +- Foundation/testsuite/src/TestPlugin.cpp | 86 +- Foundation/testsuite/src/TestPlugin.h | 102 +- .../testsuite/src/TextConverterTest.cpp | 480 +- Foundation/testsuite/src/TextConverterTest.h | 128 +- Foundation/testsuite/src/TextIteratorTest.cpp | 516 +- Foundation/testsuite/src/TextIteratorTest.h | 132 +- Foundation/testsuite/src/TextTestSuite.cpp | 96 +- Foundation/testsuite/src/TextTestSuite.h | 98 +- Foundation/testsuite/src/ThreadLocalTest.cpp | 288 +- Foundation/testsuite/src/ThreadLocalTest.h | 122 +- Foundation/testsuite/src/ThreadPoolTest.cpp | 366 +- Foundation/testsuite/src/ThreadPoolTest.h | 136 +- Foundation/testsuite/src/ThreadTest.cpp | 406 +- Foundation/testsuite/src/ThreadTest.h | 126 +- .../testsuite/src/ThreadingTestSuite.cpp | 120 +- Foundation/testsuite/src/ThreadingTestSuite.h | 98 +- Foundation/testsuite/src/TimerTest.cpp | 208 +- Foundation/testsuite/src/TimerTest.h | 132 +- Foundation/testsuite/src/TimespanTest.cpp | 360 +- Foundation/testsuite/src/TimespanTest.h | 126 +- Foundation/testsuite/src/TimestampTest.cpp | 244 +- Foundation/testsuite/src/TimestampTest.h | 120 +- Foundation/testsuite/src/TimezoneTest.cpp | 166 +- Foundation/testsuite/src/TimezoneTest.h | 120 +- .../testsuite/src/URIStreamOpenerTest.cpp | 492 +- .../testsuite/src/URIStreamOpenerTest.h | 132 +- Foundation/testsuite/src/URITest.cpp | 1524 +- Foundation/testsuite/src/URITest.h | 132 +- Foundation/testsuite/src/URITestSuite.cpp | 92 +- Foundation/testsuite/src/URITestSuite.h | 98 +- .../testsuite/src/UUIDGeneratorTest.cpp | 258 +- Foundation/testsuite/src/UUIDGeneratorTest.h | 124 +- Foundation/testsuite/src/UUIDTest.cpp | 378 +- Foundation/testsuite/src/UUIDTest.h | 130 +- Foundation/testsuite/src/UUIDTestSuite.cpp | 92 +- Foundation/testsuite/src/UUIDTestSuite.h | 98 +- Foundation/testsuite/src/WinDriver.cpp | 100 +- Foundation/testsuite/src/ZLibTest.cpp | 348 +- Foundation/testsuite/src/ZLibTest.h | 128 +- Foundation/testsuite/testapp.vmsbuild | 14 +- Foundation/testsuite/testlibrary.opt | 2 +- Foundation/testsuite/testlibrary.vmsbuild | 16 +- Foundation/testsuite/testsuite.vmsbuild | 208 +- 784 files changed, 133464 insertions(+), 133464 deletions(-) diff --git a/Foundation/Foundation_vs71.sln b/Foundation/Foundation_vs71.sln index 21ffd4531..136033bc1 100644 --- a/Foundation/Foundation_vs71.sln +++ b/Foundation/Foundation_vs71.sln @@ -1,48 +1,48 @@ -Microsoft Visual Studio Solution File, Format Version 8.00 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Foundation", "Foundation_vs71.vcproj", "{8164D41D-B053-405B-826C-CF37AC0EF176}" - ProjectSection(ProjectDependencies) = postProject - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TestSuite", "testsuite\TestSuite_vs71.vcproj", "{F1EE93DF-347F-4CB3-B191-C4E63F38E972}" - ProjectSection(ProjectDependencies) = postProject - {0955EB03-544B-4BD4-9C10-89CF38078F5F} = {0955EB03-544B-4BD4-9C10-89CF38078F5F} - {8164D41D-B053-405B-826C-CF37AC0EF176} = {8164D41D-B053-405B-826C-CF37AC0EF176} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TestLibrary", "testsuite\TestLibrary_vs71.vcproj", "{0955EB03-544B-4BD4-9C10-89CF38078F5F}" - ProjectSection(ProjectDependencies) = postProject - {8164D41D-B053-405B-826C-CF37AC0EF176} = {8164D41D-B053-405B-826C-CF37AC0EF176} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TestApp", "testsuite\TestApp_vs71.vcproj", "{6C41E55D-C0FC-4E01-AA8D-B7DA40E31D3A}" - ProjectSection(ProjectDependencies) = postProject - EndProjectSection -EndProject -Global - GlobalSection(SolutionConfiguration) = preSolution - debug_shared = debug_shared - release_shared = release_shared - EndGlobalSection - GlobalSection(ProjectConfiguration) = postSolution - {8164D41D-B053-405B-826C-CF37AC0EF176}.debug_shared.ActiveCfg = debug_shared|Win32 - {8164D41D-B053-405B-826C-CF37AC0EF176}.debug_shared.Build.0 = debug_shared|Win32 - {8164D41D-B053-405B-826C-CF37AC0EF176}.release_shared.ActiveCfg = release_shared|Win32 - {8164D41D-B053-405B-826C-CF37AC0EF176}.release_shared.Build.0 = release_shared|Win32 - {F1EE93DF-347F-4CB3-B191-C4E63F38E972}.debug_shared.ActiveCfg = debug_shared|Win32 - {F1EE93DF-347F-4CB3-B191-C4E63F38E972}.debug_shared.Build.0 = debug_shared|Win32 - {F1EE93DF-347F-4CB3-B191-C4E63F38E972}.release_shared.ActiveCfg = release_shared|Win32 - {F1EE93DF-347F-4CB3-B191-C4E63F38E972}.release_shared.Build.0 = release_shared|Win32 - {0955EB03-544B-4BD4-9C10-89CF38078F5F}.debug_shared.ActiveCfg = debug_shared|Win32 - {0955EB03-544B-4BD4-9C10-89CF38078F5F}.debug_shared.Build.0 = debug_shared|Win32 - {0955EB03-544B-4BD4-9C10-89CF38078F5F}.release_shared.ActiveCfg = release_shared|Win32 - {0955EB03-544B-4BD4-9C10-89CF38078F5F}.release_shared.Build.0 = release_shared|Win32 - {6C41E55D-C0FC-4E01-AA8D-B7DA40E31D3A}.debug_shared.ActiveCfg = debug_shared|Win32 - {6C41E55D-C0FC-4E01-AA8D-B7DA40E31D3A}.debug_shared.Build.0 = debug_shared|Win32 - {6C41E55D-C0FC-4E01-AA8D-B7DA40E31D3A}.release_shared.ActiveCfg = release_shared|Win32 - {6C41E55D-C0FC-4E01-AA8D-B7DA40E31D3A}.release_shared.Build.0 = release_shared|Win32 - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - EndGlobalSection - GlobalSection(ExtensibilityAddIns) = postSolution - EndGlobalSection -EndGlobal +Microsoft Visual Studio Solution File, Format Version 8.00 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Foundation", "Foundation_vs71.vcproj", "{8164D41D-B053-405B-826C-CF37AC0EF176}" + ProjectSection(ProjectDependencies) = postProject + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TestSuite", "testsuite\TestSuite_vs71.vcproj", "{F1EE93DF-347F-4CB3-B191-C4E63F38E972}" + ProjectSection(ProjectDependencies) = postProject + {0955EB03-544B-4BD4-9C10-89CF38078F5F} = {0955EB03-544B-4BD4-9C10-89CF38078F5F} + {8164D41D-B053-405B-826C-CF37AC0EF176} = {8164D41D-B053-405B-826C-CF37AC0EF176} + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TestLibrary", "testsuite\TestLibrary_vs71.vcproj", "{0955EB03-544B-4BD4-9C10-89CF38078F5F}" + ProjectSection(ProjectDependencies) = postProject + {8164D41D-B053-405B-826C-CF37AC0EF176} = {8164D41D-B053-405B-826C-CF37AC0EF176} + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TestApp", "testsuite\TestApp_vs71.vcproj", "{6C41E55D-C0FC-4E01-AA8D-B7DA40E31D3A}" + ProjectSection(ProjectDependencies) = postProject + EndProjectSection +EndProject +Global + GlobalSection(SolutionConfiguration) = preSolution + debug_shared = debug_shared + release_shared = release_shared + EndGlobalSection + GlobalSection(ProjectConfiguration) = postSolution + {8164D41D-B053-405B-826C-CF37AC0EF176}.debug_shared.ActiveCfg = debug_shared|Win32 + {8164D41D-B053-405B-826C-CF37AC0EF176}.debug_shared.Build.0 = debug_shared|Win32 + {8164D41D-B053-405B-826C-CF37AC0EF176}.release_shared.ActiveCfg = release_shared|Win32 + {8164D41D-B053-405B-826C-CF37AC0EF176}.release_shared.Build.0 = release_shared|Win32 + {F1EE93DF-347F-4CB3-B191-C4E63F38E972}.debug_shared.ActiveCfg = debug_shared|Win32 + {F1EE93DF-347F-4CB3-B191-C4E63F38E972}.debug_shared.Build.0 = debug_shared|Win32 + {F1EE93DF-347F-4CB3-B191-C4E63F38E972}.release_shared.ActiveCfg = release_shared|Win32 + {F1EE93DF-347F-4CB3-B191-C4E63F38E972}.release_shared.Build.0 = release_shared|Win32 + {0955EB03-544B-4BD4-9C10-89CF38078F5F}.debug_shared.ActiveCfg = debug_shared|Win32 + {0955EB03-544B-4BD4-9C10-89CF38078F5F}.debug_shared.Build.0 = debug_shared|Win32 + {0955EB03-544B-4BD4-9C10-89CF38078F5F}.release_shared.ActiveCfg = release_shared|Win32 + {0955EB03-544B-4BD4-9C10-89CF38078F5F}.release_shared.Build.0 = release_shared|Win32 + {6C41E55D-C0FC-4E01-AA8D-B7DA40E31D3A}.debug_shared.ActiveCfg = debug_shared|Win32 + {6C41E55D-C0FC-4E01-AA8D-B7DA40E31D3A}.debug_shared.Build.0 = debug_shared|Win32 + {6C41E55D-C0FC-4E01-AA8D-B7DA40E31D3A}.release_shared.ActiveCfg = release_shared|Win32 + {6C41E55D-C0FC-4E01-AA8D-B7DA40E31D3A}.release_shared.Build.0 = release_shared|Win32 + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + EndGlobalSection + GlobalSection(ExtensibilityAddIns) = postSolution + EndGlobalSection +EndGlobal diff --git a/Foundation/Foundation_vs71.vcproj b/Foundation/Foundation_vs71.vcproj index 75bcef9e9..895cb2c09 100644 --- a/Foundation/Foundation_vs71.vcproj +++ b/Foundation/Foundation_vs71.vcproj @@ -1,2437 +1,2437 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Foundation/Foundation_vs80.sln b/Foundation/Foundation_vs80.sln index 34abaf235..29aba5f91 100644 --- a/Foundation/Foundation_vs80.sln +++ b/Foundation/Foundation_vs80.sln @@ -1,45 +1,45 @@ -Microsoft Visual Studio Solution File, Format Version 9.00 -# Visual Studio 2005 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Foundation", "Foundation_vs80.vcproj", "{8164D41D-B053-405B-826C-CF37AC0EF176}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TestSuite", "testsuite\TestSuite_vs80.vcproj", "{F1EE93DF-347F-4CB3-B191-C4E63F38E972}" - ProjectSection(ProjectDependencies) = postProject - {0955EB03-544B-4BD4-9C10-89CF38078F5F} = {0955EB03-544B-4BD4-9C10-89CF38078F5F} - {6C41E55D-C0FC-4E01-AA8D-B7DA40E31D3A} = {6C41E55D-C0FC-4E01-AA8D-B7DA40E31D3A} - {8164D41D-B053-405B-826C-CF37AC0EF176} = {8164D41D-B053-405B-826C-CF37AC0EF176} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TestLibrary", "testsuite\TestLibrary_vs80.vcproj", "{0955EB03-544B-4BD4-9C10-89CF38078F5F}" - ProjectSection(ProjectDependencies) = postProject - {8164D41D-B053-405B-826C-CF37AC0EF176} = {8164D41D-B053-405B-826C-CF37AC0EF176} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TestApp", "testsuite\TestApp_vs80.vcproj", "{6C41E55D-C0FC-4E01-AA8D-B7DA40E31D3A}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - debug_shared|Win32 = debug_shared|Win32 - release_shared|Win32 = release_shared|Win32 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {8164D41D-B053-405B-826C-CF37AC0EF176}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 - {8164D41D-B053-405B-826C-CF37AC0EF176}.debug_shared|Win32.Build.0 = debug_shared|Win32 - {8164D41D-B053-405B-826C-CF37AC0EF176}.release_shared|Win32.ActiveCfg = release_shared|Win32 - {8164D41D-B053-405B-826C-CF37AC0EF176}.release_shared|Win32.Build.0 = release_shared|Win32 - {F1EE93DF-347F-4CB3-B191-C4E63F38E972}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 - {F1EE93DF-347F-4CB3-B191-C4E63F38E972}.debug_shared|Win32.Build.0 = debug_shared|Win32 - {F1EE93DF-347F-4CB3-B191-C4E63F38E972}.release_shared|Win32.ActiveCfg = release_shared|Win32 - {F1EE93DF-347F-4CB3-B191-C4E63F38E972}.release_shared|Win32.Build.0 = release_shared|Win32 - {0955EB03-544B-4BD4-9C10-89CF38078F5F}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 - {0955EB03-544B-4BD4-9C10-89CF38078F5F}.debug_shared|Win32.Build.0 = debug_shared|Win32 - {0955EB03-544B-4BD4-9C10-89CF38078F5F}.release_shared|Win32.ActiveCfg = release_shared|Win32 - {0955EB03-544B-4BD4-9C10-89CF38078F5F}.release_shared|Win32.Build.0 = release_shared|Win32 - {6C41E55D-C0FC-4E01-AA8D-B7DA40E31D3A}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 - {6C41E55D-C0FC-4E01-AA8D-B7DA40E31D3A}.debug_shared|Win32.Build.0 = debug_shared|Win32 - {6C41E55D-C0FC-4E01-AA8D-B7DA40E31D3A}.release_shared|Win32.ActiveCfg = release_shared|Win32 - {6C41E55D-C0FC-4E01-AA8D-B7DA40E31D3A}.release_shared|Win32.Build.0 = release_shared|Win32 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal +Microsoft Visual Studio Solution File, Format Version 9.00 +# Visual Studio 2005 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Foundation", "Foundation_vs80.vcproj", "{8164D41D-B053-405B-826C-CF37AC0EF176}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TestSuite", "testsuite\TestSuite_vs80.vcproj", "{F1EE93DF-347F-4CB3-B191-C4E63F38E972}" + ProjectSection(ProjectDependencies) = postProject + {0955EB03-544B-4BD4-9C10-89CF38078F5F} = {0955EB03-544B-4BD4-9C10-89CF38078F5F} + {6C41E55D-C0FC-4E01-AA8D-B7DA40E31D3A} = {6C41E55D-C0FC-4E01-AA8D-B7DA40E31D3A} + {8164D41D-B053-405B-826C-CF37AC0EF176} = {8164D41D-B053-405B-826C-CF37AC0EF176} + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TestLibrary", "testsuite\TestLibrary_vs80.vcproj", "{0955EB03-544B-4BD4-9C10-89CF38078F5F}" + ProjectSection(ProjectDependencies) = postProject + {8164D41D-B053-405B-826C-CF37AC0EF176} = {8164D41D-B053-405B-826C-CF37AC0EF176} + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TestApp", "testsuite\TestApp_vs80.vcproj", "{6C41E55D-C0FC-4E01-AA8D-B7DA40E31D3A}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + debug_shared|Win32 = debug_shared|Win32 + release_shared|Win32 = release_shared|Win32 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {8164D41D-B053-405B-826C-CF37AC0EF176}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 + {8164D41D-B053-405B-826C-CF37AC0EF176}.debug_shared|Win32.Build.0 = debug_shared|Win32 + {8164D41D-B053-405B-826C-CF37AC0EF176}.release_shared|Win32.ActiveCfg = release_shared|Win32 + {8164D41D-B053-405B-826C-CF37AC0EF176}.release_shared|Win32.Build.0 = release_shared|Win32 + {F1EE93DF-347F-4CB3-B191-C4E63F38E972}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 + {F1EE93DF-347F-4CB3-B191-C4E63F38E972}.debug_shared|Win32.Build.0 = debug_shared|Win32 + {F1EE93DF-347F-4CB3-B191-C4E63F38E972}.release_shared|Win32.ActiveCfg = release_shared|Win32 + {F1EE93DF-347F-4CB3-B191-C4E63F38E972}.release_shared|Win32.Build.0 = release_shared|Win32 + {0955EB03-544B-4BD4-9C10-89CF38078F5F}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 + {0955EB03-544B-4BD4-9C10-89CF38078F5F}.debug_shared|Win32.Build.0 = debug_shared|Win32 + {0955EB03-544B-4BD4-9C10-89CF38078F5F}.release_shared|Win32.ActiveCfg = release_shared|Win32 + {0955EB03-544B-4BD4-9C10-89CF38078F5F}.release_shared|Win32.Build.0 = release_shared|Win32 + {6C41E55D-C0FC-4E01-AA8D-B7DA40E31D3A}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 + {6C41E55D-C0FC-4E01-AA8D-B7DA40E31D3A}.debug_shared|Win32.Build.0 = debug_shared|Win32 + {6C41E55D-C0FC-4E01-AA8D-B7DA40E31D3A}.release_shared|Win32.ActiveCfg = release_shared|Win32 + {6C41E55D-C0FC-4E01-AA8D-B7DA40E31D3A}.release_shared|Win32.Build.0 = release_shared|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Foundation/Foundation_vs80.vcproj b/Foundation/Foundation_vs80.vcproj index 3b5d23eb3..c1582d20e 100644 --- a/Foundation/Foundation_vs80.vcproj +++ b/Foundation/Foundation_vs80.vcproj @@ -1,3191 +1,3191 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Foundation/Makefile b/Foundation/Makefile index 127b0b29d..6f5caed71 100644 --- a/Foundation/Makefile +++ b/Foundation/Makefile @@ -1,41 +1,41 @@ -# -# Makefile -# -# $Id: //poco/1.2/Foundation/Makefile#2 $ -# -# Makefile for Poco Foundation -# - -include $(POCO_BASE)/build/rules/global - -objects = ArchiveStrategy ASCIIEncoding AsyncChannel Base64Decoder Base64Encoder \ - BinaryReader BinaryWriter Bugcheck ByteOrder Channel Configurable ConsoleChannel \ - CountingStream DateTime LocalDateTime DateTimeFormat DateTimeFormatter DateTimeParser \ - Debugger DeflatingStream DigestEngine DigestStream DirectoryIterator \ - Environment Event EventArgs ErrorHandler Exception FPEnvironment File Glob \ - FileChannel Formatter FormattingChannel HexBinaryDecoder LineEndingConverter \ - HexBinaryEncoder InflatingStream Latin1Encoding Latin9Encoding LogFile Logger \ - LoggingFactory LoggingRegistry LogStream NamedEvent NamedMutex NullChannel \ - MemoryPool MD2Engine MD4Engine MD5Engine Manifest Message Mutex \ - NestedDiagnosticContext Notification NotificationCenter \ - NotificationQueue NullStream NumberFormatter NumberParser AbstractObserver \ - Path PatternFormatter Process PurgeStrategy RWLock Random RandomStream \ - RegularExpression RefCountedObject Runnable RotateStrategy \ - SHA1Engine Semaphore SharedLibrary SimpleFileChannel \ - SignalHandler SplitterChannel Stopwatch StreamChannel StreamConverter StreamCopier \ - StreamTokenizer String StringTokenizer SynchronizedObject SyslogChannel \ - Task TaskManager TaskNotification TeeStream HashStatistic\ - TemporaryFile TextConverter TextEncoding TextIterator Thread ThreadLocal \ - ThreadPool ActiveDispatcher Timer Timespan Timestamp Timezone Token URI \ - FileStreamFactory URIStreamFactory URIStreamOpener UTF16Encoding Windows1252Encoding \ - UTF8Encoding UnicodeConverter UUID UUIDGenerator Void Format \ - Pipe PipeImpl PipeStream \ - adler32 chartables compress crc32 \ - deflate get gzio infback inffast inflate inftrees maketables pcre study \ - trees zutil - -target = PocoFoundation -target_version = $(LIBVERSION) -target_libs = - -include $(POCO_BASE)/build/rules/lib +# +# Makefile +# +# $Id: //poco/1.2/Foundation/Makefile#2 $ +# +# Makefile for Poco Foundation +# + +include $(POCO_BASE)/build/rules/global + +objects = ArchiveStrategy ASCIIEncoding AsyncChannel Base64Decoder Base64Encoder \ + BinaryReader BinaryWriter Bugcheck ByteOrder Channel Configurable ConsoleChannel \ + CountingStream DateTime LocalDateTime DateTimeFormat DateTimeFormatter DateTimeParser \ + Debugger DeflatingStream DigestEngine DigestStream DirectoryIterator \ + Environment Event EventArgs ErrorHandler Exception FPEnvironment File Glob \ + FileChannel Formatter FormattingChannel HexBinaryDecoder LineEndingConverter \ + HexBinaryEncoder InflatingStream Latin1Encoding Latin9Encoding LogFile Logger \ + LoggingFactory LoggingRegistry LogStream NamedEvent NamedMutex NullChannel \ + MemoryPool MD2Engine MD4Engine MD5Engine Manifest Message Mutex \ + NestedDiagnosticContext Notification NotificationCenter \ + NotificationQueue NullStream NumberFormatter NumberParser AbstractObserver \ + Path PatternFormatter Process PurgeStrategy RWLock Random RandomStream \ + RegularExpression RefCountedObject Runnable RotateStrategy \ + SHA1Engine Semaphore SharedLibrary SimpleFileChannel \ + SignalHandler SplitterChannel Stopwatch StreamChannel StreamConverter StreamCopier \ + StreamTokenizer String StringTokenizer SynchronizedObject SyslogChannel \ + Task TaskManager TaskNotification TeeStream HashStatistic\ + TemporaryFile TextConverter TextEncoding TextIterator Thread ThreadLocal \ + ThreadPool ActiveDispatcher Timer Timespan Timestamp Timezone Token URI \ + FileStreamFactory URIStreamFactory URIStreamOpener UTF16Encoding Windows1252Encoding \ + UTF8Encoding UnicodeConverter UUID UUIDGenerator Void Format \ + Pipe PipeImpl PipeStream \ + adler32 chartables compress crc32 \ + deflate get gzio infback inffast inflate inftrees maketables pcre study \ + trees zutil + +target = PocoFoundation +target_version = $(LIBVERSION) +target_libs = + +include $(POCO_BASE)/build/rules/lib diff --git a/Foundation/foundation.vmsbuild b/Foundation/foundation.vmsbuild index 8be41b0d9..09b4d9a4b 100644 --- a/Foundation/foundation.vmsbuild +++ b/Foundation/foundation.vmsbuild @@ -1,126 +1,126 @@ -# -# Foundation.vmsbuild -# -# $Id: //poco/Foundation/foundation.vmsbuild#8 $ -# -LIB=PocoFoundation -ASCIIEncoding -AsyncChannel -Base64Decoder -Base64Encoder -BinaryReader -BinaryWriter -Bugcheck -ByteOrder -Channel -Configurable -ConsoleChannel -CountingStream -DateTime -LocalDateTime -DateTimeFormat -DateTimeFormatter -DateTimeParser -Debugger -DeflatingStream -DigestEngine -DigestStream -DirectoryIterator -Environment -Event -EventArgs -Exception -FPEnvironment -File -Glob -FileChannel -Formatter -FormattingChannel -HashStatistic -HexBinaryDecoder -HexBinaryEncoder -InflatingStream -Latin1Encoding -Latin9Encoding -Logger -LoggingFactory -LoggingRegistry -NamedEvent -NamedMutex -NullChannel -MD2Engine -MD4Engine -MD5Engine -Manifest -Message -Mutex -NestedDiagnosticContext -Notification -NotificationCenter -NotificationQueue -NullStream -NumberFormatter -NumberParser -Observer -Path -PatternFormatter -Process -RWLock -Random -RandomStream -RegularExpression -RefCountedObject -Runnable -SHA1Engine -Semaphore -SharedLibrary -SignalHandler -SplitterChannel -Stopwatch -StreamChannel -StreamConverter -StreamCopier -StreamTokenizer -String -StringTokenizer -SynchronizedObject -SyslogChannel -Task -TaskManager -TaskNotification -TemporaryFile -TextConverter -TextEncoding -TextIterator -Thread -ThreadLocal -ThreadPool -Timer -Timespan -Timestamp -Timezone -Token -URI -URIFileStreamFactory -URIStreamFactory -URIStreamOpener -UTF16Encoding -UTF8Encoding -UUID -UUIDGenerator -adler32 -chartables -compress -crc32 -deflate -get -gzio -infback -inffast -inflate -inftrees -maketables -pcre -study -trees -zutil +# +# Foundation.vmsbuild +# +# $Id: //poco/Foundation/foundation.vmsbuild#8 $ +# +LIB=PocoFoundation +ASCIIEncoding +AsyncChannel +Base64Decoder +Base64Encoder +BinaryReader +BinaryWriter +Bugcheck +ByteOrder +Channel +Configurable +ConsoleChannel +CountingStream +DateTime +LocalDateTime +DateTimeFormat +DateTimeFormatter +DateTimeParser +Debugger +DeflatingStream +DigestEngine +DigestStream +DirectoryIterator +Environment +Event +EventArgs +Exception +FPEnvironment +File +Glob +FileChannel +Formatter +FormattingChannel +HashStatistic +HexBinaryDecoder +HexBinaryEncoder +InflatingStream +Latin1Encoding +Latin9Encoding +Logger +LoggingFactory +LoggingRegistry +NamedEvent +NamedMutex +NullChannel +MD2Engine +MD4Engine +MD5Engine +Manifest +Message +Mutex +NestedDiagnosticContext +Notification +NotificationCenter +NotificationQueue +NullStream +NumberFormatter +NumberParser +Observer +Path +PatternFormatter +Process +RWLock +Random +RandomStream +RegularExpression +RefCountedObject +Runnable +SHA1Engine +Semaphore +SharedLibrary +SignalHandler +SplitterChannel +Stopwatch +StreamChannel +StreamConverter +StreamCopier +StreamTokenizer +String +StringTokenizer +SynchronizedObject +SyslogChannel +Task +TaskManager +TaskNotification +TemporaryFile +TextConverter +TextEncoding +TextIterator +Thread +ThreadLocal +ThreadPool +Timer +Timespan +Timestamp +Timezone +Token +URI +URIFileStreamFactory +URIStreamFactory +URIStreamOpener +UTF16Encoding +UTF8Encoding +UUID +UUIDGenerator +adler32 +chartables +compress +crc32 +deflate +get +gzio +infback +inffast +inflate +inftrees +maketables +pcre +study +trees +zutil diff --git a/Foundation/include/Poco/ASCIIEncoding.h b/Foundation/include/Poco/ASCIIEncoding.h index b1151504e..6307866a6 100644 --- a/Foundation/include/Poco/ASCIIEncoding.h +++ b/Foundation/include/Poco/ASCIIEncoding.h @@ -1,68 +1,68 @@ -// -// ASCIIEncoding.h -// -// $Id: //poco/1.2/Foundation/include/Poco/ASCIIEncoding.h#1 $ -// -// Library: Foundation -// Package: Text -// Module: ASCIIEncoding -// -// Definition of the ASCIIEncoding class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_ASCIIEncoding_INCLUDED -#define Foundation_ASCIIEncoding_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/TextEncoding.h" - - -namespace Poco { - - -class Foundation_API ASCIIEncoding: public TextEncoding - /// 7-bit ASCII text encoding. -{ -public: - ASCIIEncoding(); - ~ASCIIEncoding(); - const CharacterMap& characterMap() const; - int convert(const unsigned char* bytes) const; - int convert(int ch, unsigned char* bytes, int length) const; - -private: - static const CharacterMap _charMap; -}; - - -} // namespace Poco - - -#endif // Foundation_ASCIIEncoding_INCLUDED +// +// ASCIIEncoding.h +// +// $Id: //poco/1.2/Foundation/include/Poco/ASCIIEncoding.h#1 $ +// +// Library: Foundation +// Package: Text +// Module: ASCIIEncoding +// +// Definition of the ASCIIEncoding class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_ASCIIEncoding_INCLUDED +#define Foundation_ASCIIEncoding_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/TextEncoding.h" + + +namespace Poco { + + +class Foundation_API ASCIIEncoding: public TextEncoding + /// 7-bit ASCII text encoding. +{ +public: + ASCIIEncoding(); + ~ASCIIEncoding(); + const CharacterMap& characterMap() const; + int convert(const unsigned char* bytes) const; + int convert(int ch, unsigned char* bytes, int length) const; + +private: + static const CharacterMap _charMap; +}; + + +} // namespace Poco + + +#endif // Foundation_ASCIIEncoding_INCLUDED diff --git a/Foundation/include/Poco/AbstractCache.h b/Foundation/include/Poco/AbstractCache.h index 279966e80..98c1ff175 100644 --- a/Foundation/include/Poco/AbstractCache.h +++ b/Foundation/include/Poco/AbstractCache.h @@ -1,275 +1,275 @@ -// -// AbstractCache.h -// -// $Id: //poco/1.2/Foundation/include/Poco/AbstractCache.h#4 $ -// -// Library: Foundation -// Package: Cache -// Module: AbstractCache -// -// Definition of the AbstractCache class. -// -// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_AbstractCache_INCLUDED -#define Foundation_AbstractCache_INCLUDED - - -#include "Poco/KeyValueArgs.h" -#include "Poco/ValidArgs.h" -#include "Poco/Mutex.h" -#include "Poco/Exception.h" -#include "Poco/BasicEvent.h" -#include "Poco/EventArgs.h" -#include "Poco/Delegate.h" -#include "Poco/SharedPtr.h" -#include -#include - - -namespace Poco { - - -template -class AbstractCache - /// An AbstractCache is the interface of all caches. -{ -public: - BasicEvent > Add; - BasicEvent Remove; - BasicEvent Get; - BasicEvent Clear; - - typedef std::map > DataHolder; - typedef typename DataHolder::iterator Iterator; - typedef typename DataHolder::const_iterator ConstIterator; - typedef std::set KeySet; - - AbstractCache() - { - initialize(); - } - - AbstractCache(const TStrategy& strat): _strategy(strat) - { - initialize(); - } - - virtual ~AbstractCache() - { - uninitialize(); - } - - void add(const TKey& key, const TValue& val) - /// Adds the key value pair to the cache. - /// If for the key already an entry exists, it will be overwritten. - { - FastMutex::ScopedLock lock(_mutex); - doAdd(key, val); - } - - void remove(const TKey& key) - /// Removes an entry from the cache. If the entry is not found, - /// the remove is ignored. - { - FastMutex::ScopedLock lock(_mutex); - doRemove(key); - } - - bool has(const TKey& key) const - /// Returns true if the cache contains a value for the key. - { - FastMutex::ScopedLock lock(_mutex); - return doHas(key); - } - - SharedPtr get(const TKey& key) - /// Returns a SharedPtr of the value. The SharedPointer will remain valid - /// even when cache replacement removes the element. - /// If for the key no value exists, an empty SharedPtr is returned. - { - FastMutex::ScopedLock lock(_mutex); - return doGet (key); - } - - void clear() - /// Removes all elements from the cache. - { - FastMutex::ScopedLock lock(_mutex); - doClear(); - } - - std::size_t size() const - /// Returns the number of cached elements - { - FastMutex::ScopedLock lock(_mutex); - return _data.size(); - } - - void forceReplace() - /// Forces cache replacement. Note that Poco's cache strategy use for efficiency reason no background thread - /// which periodically triggers cache replacement. Cache Replacement is only started when the cache is modified - /// from outside, i.e. add is called, or when a user tries to access an cache element via get. - /// In some cases, i.e. expire based caching where for a long time no access to the cache happens, - /// it might be desirable to be able to trigger cache replacement manually. - { - FastMutex::ScopedLock lock(_mutex); - doReplace(); - } - - -protected: - mutable BasicEvent > IsValid; - mutable BasicEvent Replace; - - void initialize() - /// Sets up event registration. - { - Add += Delegate >(&_strategy, &TStrategy::onAdd); - Remove += Delegate(&_strategy, &TStrategy::onRemove); - Get += Delegate(&_strategy, &TStrategy::onGet); - Clear += Delegate(&_strategy, &TStrategy::onClear); - IsValid += Delegate >(&_strategy, &TStrategy::onIsValid); - Replace += Delegate(&_strategy, &TStrategy::onReplace); - } - - void uninitialize() - /// Reverts event registration. - { - Add -= Delegate >(&_strategy, &TStrategy::onAdd ); - Remove -= Delegate(&_strategy, &TStrategy::onRemove); - Get -= Delegate(&_strategy, &TStrategy::onGet); - Clear -= Delegate(&_strategy, &TStrategy::onClear); - IsValid -= Delegate >(&_strategy, &TStrategy::onIsValid); - Replace -= Delegate(&_strategy, &TStrategy::onReplace); - } - - void doAdd(const TKey& key, const TValue& val) - /// Adds the key value pair to the cache. - /// If for the key already an entry exists, it will be overwritten. - { - if (doHas(key)) - { - doRemove(key); - } - - KeyValueArgs args(key, val); - Add.notify(this, args); - _data.insert(std::make_pair(key, SharedPtr(new TValue(val)))); - - doReplace(); - } - - void doRemove(const TKey& key) - /// Removes an entry from the cache. If the entry is not found - /// the remove is ignored. - { - Remove.notify(this, key); - _data.erase(key); - } - - bool doHas(const TKey& key) const - /// Returns true if the cache contains a value for the key - { - // ask the strategy if the key is valid - ConstIterator it = _data.find(key); - bool result = false; - - if (it != _data.end()) - { - ValidArgs args(key); - IsValid.notify(this, args); - result = args.isValid(); - } - - return result; - } - - SharedPtr doGet(const TKey& key) - /// Returns a SharedPtr of the cache entry, returns 0 if for - /// the key no value was found - { - Iterator it = _data.find(key); - SharedPtr result; - - if (it != _data.end()) - { - // inform all strategies that a read-access to an element happens - Get.notify(this, key); - // ask all strategies if the key is valid - ValidArgs args(key); - IsValid.notify(this, args); - - if (!args.isValid()) - { - doRemove(key); - } - else - { - result = it->second; - } - } - - return result; - } - - void doClear() - { - static EventArgs _emptyArgs; - Clear.notify(this, _emptyArgs); - _data.clear(); - } - - void doReplace() - { - std::set delMe; - Replace.notify(this, delMe); - // delMe contains the to be removed elements - typename std::set::const_iterator it = delMe.begin(); - typename std::set::const_iterator endIt = delMe.end(); - - for (; it != endIt; ++it) - { - doRemove(*it); - } - } - - TStrategy _strategy; - mutable DataHolder _data; - mutable FastMutex _mutex; - -private: - AbstractCache(const AbstractCache& aCache); - AbstractCache& operator = (const AbstractCache& aCache); -}; - - -} // namespace Poco - - -#endif +// +// AbstractCache.h +// +// $Id: //poco/1.2/Foundation/include/Poco/AbstractCache.h#4 $ +// +// Library: Foundation +// Package: Cache +// Module: AbstractCache +// +// Definition of the AbstractCache class. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_AbstractCache_INCLUDED +#define Foundation_AbstractCache_INCLUDED + + +#include "Poco/KeyValueArgs.h" +#include "Poco/ValidArgs.h" +#include "Poco/Mutex.h" +#include "Poco/Exception.h" +#include "Poco/BasicEvent.h" +#include "Poco/EventArgs.h" +#include "Poco/Delegate.h" +#include "Poco/SharedPtr.h" +#include +#include + + +namespace Poco { + + +template +class AbstractCache + /// An AbstractCache is the interface of all caches. +{ +public: + BasicEvent > Add; + BasicEvent Remove; + BasicEvent Get; + BasicEvent Clear; + + typedef std::map > DataHolder; + typedef typename DataHolder::iterator Iterator; + typedef typename DataHolder::const_iterator ConstIterator; + typedef std::set KeySet; + + AbstractCache() + { + initialize(); + } + + AbstractCache(const TStrategy& strat): _strategy(strat) + { + initialize(); + } + + virtual ~AbstractCache() + { + uninitialize(); + } + + void add(const TKey& key, const TValue& val) + /// Adds the key value pair to the cache. + /// If for the key already an entry exists, it will be overwritten. + { + FastMutex::ScopedLock lock(_mutex); + doAdd(key, val); + } + + void remove(const TKey& key) + /// Removes an entry from the cache. If the entry is not found, + /// the remove is ignored. + { + FastMutex::ScopedLock lock(_mutex); + doRemove(key); + } + + bool has(const TKey& key) const + /// Returns true if the cache contains a value for the key. + { + FastMutex::ScopedLock lock(_mutex); + return doHas(key); + } + + SharedPtr get(const TKey& key) + /// Returns a SharedPtr of the value. The SharedPointer will remain valid + /// even when cache replacement removes the element. + /// If for the key no value exists, an empty SharedPtr is returned. + { + FastMutex::ScopedLock lock(_mutex); + return doGet (key); + } + + void clear() + /// Removes all elements from the cache. + { + FastMutex::ScopedLock lock(_mutex); + doClear(); + } + + std::size_t size() const + /// Returns the number of cached elements + { + FastMutex::ScopedLock lock(_mutex); + return _data.size(); + } + + void forceReplace() + /// Forces cache replacement. Note that Poco's cache strategy use for efficiency reason no background thread + /// which periodically triggers cache replacement. Cache Replacement is only started when the cache is modified + /// from outside, i.e. add is called, or when a user tries to access an cache element via get. + /// In some cases, i.e. expire based caching where for a long time no access to the cache happens, + /// it might be desirable to be able to trigger cache replacement manually. + { + FastMutex::ScopedLock lock(_mutex); + doReplace(); + } + + +protected: + mutable BasicEvent > IsValid; + mutable BasicEvent Replace; + + void initialize() + /// Sets up event registration. + { + Add += Delegate >(&_strategy, &TStrategy::onAdd); + Remove += Delegate(&_strategy, &TStrategy::onRemove); + Get += Delegate(&_strategy, &TStrategy::onGet); + Clear += Delegate(&_strategy, &TStrategy::onClear); + IsValid += Delegate >(&_strategy, &TStrategy::onIsValid); + Replace += Delegate(&_strategy, &TStrategy::onReplace); + } + + void uninitialize() + /// Reverts event registration. + { + Add -= Delegate >(&_strategy, &TStrategy::onAdd ); + Remove -= Delegate(&_strategy, &TStrategy::onRemove); + Get -= Delegate(&_strategy, &TStrategy::onGet); + Clear -= Delegate(&_strategy, &TStrategy::onClear); + IsValid -= Delegate >(&_strategy, &TStrategy::onIsValid); + Replace -= Delegate(&_strategy, &TStrategy::onReplace); + } + + void doAdd(const TKey& key, const TValue& val) + /// Adds the key value pair to the cache. + /// If for the key already an entry exists, it will be overwritten. + { + if (doHas(key)) + { + doRemove(key); + } + + KeyValueArgs args(key, val); + Add.notify(this, args); + _data.insert(std::make_pair(key, SharedPtr(new TValue(val)))); + + doReplace(); + } + + void doRemove(const TKey& key) + /// Removes an entry from the cache. If the entry is not found + /// the remove is ignored. + { + Remove.notify(this, key); + _data.erase(key); + } + + bool doHas(const TKey& key) const + /// Returns true if the cache contains a value for the key + { + // ask the strategy if the key is valid + ConstIterator it = _data.find(key); + bool result = false; + + if (it != _data.end()) + { + ValidArgs args(key); + IsValid.notify(this, args); + result = args.isValid(); + } + + return result; + } + + SharedPtr doGet(const TKey& key) + /// Returns a SharedPtr of the cache entry, returns 0 if for + /// the key no value was found + { + Iterator it = _data.find(key); + SharedPtr result; + + if (it != _data.end()) + { + // inform all strategies that a read-access to an element happens + Get.notify(this, key); + // ask all strategies if the key is valid + ValidArgs args(key); + IsValid.notify(this, args); + + if (!args.isValid()) + { + doRemove(key); + } + else + { + result = it->second; + } + } + + return result; + } + + void doClear() + { + static EventArgs _emptyArgs; + Clear.notify(this, _emptyArgs); + _data.clear(); + } + + void doReplace() + { + std::set delMe; + Replace.notify(this, delMe); + // delMe contains the to be removed elements + typename std::set::const_iterator it = delMe.begin(); + typename std::set::const_iterator endIt = delMe.end(); + + for (; it != endIt; ++it) + { + doRemove(*it); + } + } + + TStrategy _strategy; + mutable DataHolder _data; + mutable FastMutex _mutex; + +private: + AbstractCache(const AbstractCache& aCache); + AbstractCache& operator = (const AbstractCache& aCache); +}; + + +} // namespace Poco + + +#endif diff --git a/Foundation/include/Poco/AbstractDelegate.h b/Foundation/include/Poco/AbstractDelegate.h index d0e6d9b83..312216f36 100644 --- a/Foundation/include/Poco/AbstractDelegate.h +++ b/Foundation/include/Poco/AbstractDelegate.h @@ -1,96 +1,96 @@ -// -// AbstractDelegate.h -// -// $Id: //poco/1.2/Foundation/include/Poco/AbstractDelegate.h#2 $ -// -// Library: Foundation -// Package: Events -// Module: AbstractDelegate -// -// Implementation of the AbstractDelegate template. -// -// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_AbstractDelegate_INCLUDED -#define Foundation_AbstractDelegate_INCLUDED - - -#include "Poco/Foundation.h" - - -namespace Poco { - - -template -class AbstractDelegate - /// Interface for Delegate and Expire - /// Very similar to AbstractPriorityDelegate but having two separate files (no inheritance) - /// allows one to have compile-time checks when registering an observer - /// instead of run-time checks. -{ -public: - AbstractDelegate(void* pTarget): _pTarget(pTarget) - { - poco_assert_dbg (_pTarget != 0); - } - - AbstractDelegate(const AbstractDelegate& del):_pTarget(del._pTarget) - { - poco_assert_dbg (_pTarget != 0); - } - - virtual ~AbstractDelegate() - { - } - - virtual bool notify(const void* sender, TArgs& arguments) = 0; - /// Returns false, if the Delegate is no longer valid, thus indicating an expire - - virtual AbstractDelegate* clone() const = 0; - /// Returns a deep-copy of the AbstractDelegate - - bool operator < (const AbstractDelegate& other) const - /// For comparing AbstractDelegates in a collection. - { - return _pTarget < other._pTarget; - } - - void* target() const - { - return _pTarget; - } - -protected: - void* _pTarget; -}; - - -} // namespace Poco - - -#endif +// +// AbstractDelegate.h +// +// $Id: //poco/1.2/Foundation/include/Poco/AbstractDelegate.h#2 $ +// +// Library: Foundation +// Package: Events +// Module: AbstractDelegate +// +// Implementation of the AbstractDelegate template. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_AbstractDelegate_INCLUDED +#define Foundation_AbstractDelegate_INCLUDED + + +#include "Poco/Foundation.h" + + +namespace Poco { + + +template +class AbstractDelegate + /// Interface for Delegate and Expire + /// Very similar to AbstractPriorityDelegate but having two separate files (no inheritance) + /// allows one to have compile-time checks when registering an observer + /// instead of run-time checks. +{ +public: + AbstractDelegate(void* pTarget): _pTarget(pTarget) + { + poco_assert_dbg (_pTarget != 0); + } + + AbstractDelegate(const AbstractDelegate& del):_pTarget(del._pTarget) + { + poco_assert_dbg (_pTarget != 0); + } + + virtual ~AbstractDelegate() + { + } + + virtual bool notify(const void* sender, TArgs& arguments) = 0; + /// Returns false, if the Delegate is no longer valid, thus indicating an expire + + virtual AbstractDelegate* clone() const = 0; + /// Returns a deep-copy of the AbstractDelegate + + bool operator < (const AbstractDelegate& other) const + /// For comparing AbstractDelegates in a collection. + { + return _pTarget < other._pTarget; + } + + void* target() const + { + return _pTarget; + } + +protected: + void* _pTarget; +}; + + +} // namespace Poco + + +#endif diff --git a/Foundation/include/Poco/AbstractEvent.h b/Foundation/include/Poco/AbstractEvent.h index 3be0a5805..7f93c6407 100644 --- a/Foundation/include/Poco/AbstractEvent.h +++ b/Foundation/include/Poco/AbstractEvent.h @@ -1,304 +1,304 @@ -// -// AbstractEvent.h -// -// $Id: //poco/1.2/Foundation/include/Poco/AbstractEvent.h#3 $ -// -// Library: Foundation -// Package: Events -// Module: AbstractEvent -// -// Definition of the AbstractEvent class. -// -// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_AbstractFoundation_INCLUDED -#define Foundation_AbstractFoundation_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/SingletonHolder.h" -#include "Poco/SharedPtr.h" -#include "Poco/ActiveResult.h" -#include "Poco/ActiveMethod.h" -#include "Poco/Mutex.h" - - -namespace Poco { - - -template -class AbstractEvent - /// An abstractEvent is the super-class of all events. - /// It works similar to the way C# handles notifications (aka events in C#). - /// Events can be used to send information to a set of observers - /// which are registered at the event. The type of the data is specified with - /// the template parameter TArgs. The TStrategy parameter must be a subclass - /// of NotificationStrategy. The parameter TDelegate can either be a subclass of AbstractDelegate - /// or of PriorityAbstractDelegate. - /// - /// Note that AbstractEvent should never be used directly. One ought to use - /// one of its subclasses which set the TStrategy and TDelegate template parameters - /// to fixed values. For most use-cases the BasicEvent template will be sufficient. - /// - /// Use events by adding them as public members to the object which is throwing notifications: - /// - /// class MyData - /// { - /// public: - /// Poco::BasicEvent AgeChanged; - /// - /// MyData(); - /// ... - /// }; - /// - /// Throwing the event can be done either by the events notify or notifyAsync method: - /// - /// void MyData::setAge(int i) - /// { - /// this->_age = i; - /// AgeChanged.notify(this, this->_age); - /// } - /// - /// Note that notify and notifyAsync do not catch exceptions, i.e. in case a delegate - /// throws an exception, the notify is immediately aborted and the exception is thrown - /// back to the caller. - /// - /// Delegates can register methods at the event. In the case of a BasicEvent or FIFOEvent - /// the Delegate template is used, in case of an PriorityEvent a PriorityDelegate is used. - /// Mixing of observers, e.g. using a PriorityDelegate with a BasicEvent is not possible and - /// checked for during compile time. - /// Events require the observers to follow the following method signature: - /// - /// void onEvent(const void* pSender, TArgs& args); - /// - /// For performance reasons arguments are always sent by reference. This also allows observers - /// to modify the sent argument. To prevent that, use as template - /// parameter. A non-conformant method signature leads to compile errors. - /// - /// Assuming that the observer meets the method signature requirement, it can register - /// this method with the += operator: - /// - /// class MyController - /// { - /// protected: - /// MyData _data; - /// - /// void onDataChanged(void* pSender, int& data); - /// ... - /// }; - /// - /// MyController::MyController() - /// { - /// _data.AgeChanged += Delegate(this, &MyController::onDataChanged); - /// } - /// - /// In some cases it might be desirable to work with automatically expiring registrations: - /// - /// _data.DataChanged += Expire(Delegate(this, &MyController::onDataChanged), 1000); - /// - /// This will add a delegate to the event which will automatically be removed in 1000 millisecs. - /// - /// Unregistering happens via the -= operator. Forgetting to unregister a method will lead to - /// segmentation faults later, when one tries to send a notify to a no longer existing object. - /// - /// MyController::~MyController() - /// { - /// _data.DataChanged -= Delegate(this, &MyController::onDataChanged); - /// } - /// - /// For further examples refer to the event testsuites. -{ -public: - AbstractEvent(): - _executeAsync(this, &AbstractEvent::executeAsyncImpl), - _enabled(true) - { - } - - AbstractEvent(const TStrategy& strat): - _executeAsync(this, &AbstractEvent::executeAsyncImpl), - _strategy(strat), - _enabled(true) - { - } - - virtual ~AbstractEvent() - { - } - - void operator += (const TDelegate& aDelegate) - /// Adds a delegate to the event. If the observer is equal to an - /// already existing one (determined by the < operator), - /// it will simply replace the existing observer. - /// This behavior is determined by the TStrategy. Current implementations - /// (DefaultStrategy, FIFOStrategy) follow that guideline but future ones - /// can deviate. - { - FastMutex::ScopedLock lock(_mutex); - _strategy.add(aDelegate); - } - - void operator -= (const TDelegate& aDelegate) - /// Removes a delegate from the event. If the delegate is equal to an - /// already existing one is determined by the < operator. - /// If the observer is not found, the unregister will be ignored - { - FastMutex::ScopedLock lock(_mutex); - _strategy.remove(aDelegate); - } - - void notify(const void* pSender, TArgs& args) - /// Sends a notification to all registered delegates. The order is - /// determined by the TStrategy. This method is blocking. While executing, - /// other objects can change the list of delegates. These changes don't - /// influence the current active notifications but are activated with - /// the next notify. If one of the delegates throws an exception, the notify - /// method is immediately aborted and the exception is reported to the caller. - { - SharedPtr ptrStrat; - bool enabled = false; - - { - FastMutex::ScopedLock lock(_mutex); - enabled = _enabled; - if (_enabled) - { - // thread-safeness: - // copy should be faster and safer than blocking until - // execution ends - ptrStrat = new TStrategy(_strategy); - } - } - - if (enabled) - { - ptrStrat->notify(pSender, args); - } - } - - ActiveResult notifyAsync(const void* pSender, const TArgs& args) - /// Sends a notification to all registered delegates. The order is - /// determined by the TStrategy. This method is not blocking and will - /// immediately return. The delegates are invoked in a seperate thread. - /// Call activeResult.wait() to wait until the notification has ended. - /// While executing, other objects can change the delegate list. These changes don't - /// influence the current active notifications but are activated with - /// the next notify. If one of the delegates throws an exception, the execution - /// is aborted and the exception is reported to the caller. - { - NotifyAsyncParams params(pSender, args); - - { - FastMutex::ScopedLock lock(_mutex); - - // thread-safeness: - // copy should be faster and safer than blocking until - // execution ends - // make a copy of the strategy here to guarantee that - // between notifyAsync and the execution of the method no changes can occur - - params.ptrStrat = SharedPtr(new TStrategy(_strategy)); - params.enabled = _enabled; - } - - ActiveResult result = _executeAsync(params); - return result; - } - - void enable() - /// Enables the event - { - FastMutex::ScopedLock lock(_mutex); - _enabled = true; - } - - void disable() - /// Disables the event. notify and notifyAsnyc will be ignored, - /// but adding/removing delegates is still allowed. - { - FastMutex::ScopedLock lock(_mutex); - _enabled = false; - } - - bool isEnabled() const - { - FastMutex::ScopedLock lock(_mutex); - return _enabled; - } - - void clear() - /// Removes all delegates. - { - FastMutex::ScopedLock lock(_mutex); - _strategy.clear(); - } - -protected: - struct NotifyAsyncParams - { - SharedPtr ptrStrat; - const void* pSender; - TArgs args; - bool enabled; - - NotifyAsyncParams(const void* pSend, const TArgs& a):ptrStrat(), pSender(pSend), args(a), enabled(true) - /// default constructor reduces the need for TArgs to have an empty constructor, only copy constructor is needed. - { - } - }; - - ActiveMethod _executeAsync; - - TArgs executeAsyncImpl(const NotifyAsyncParams& par) - { - if (!par.enabled) - { - return par.args; - } - - NotifyAsyncParams params = par; - TArgs retArgs(params.args); - params.ptrStrat->notify(params.pSender, retArgs); - return retArgs; - } - - TStrategy _strategy; /// The strategy used to notify observers. - bool _enabled; /// Stores if an event is enabled. Notfies on disabled events have no effect - /// but it is possible to change the observers. - mutable FastMutex _mutex; - -private: - AbstractEvent(const AbstractEvent& other); - AbstractEvent& operator = (const AbstractEvent& other); -}; - - -} // namespace Poco - - -#endif +// +// AbstractEvent.h +// +// $Id: //poco/1.2/Foundation/include/Poco/AbstractEvent.h#3 $ +// +// Library: Foundation +// Package: Events +// Module: AbstractEvent +// +// Definition of the AbstractEvent class. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_AbstractFoundation_INCLUDED +#define Foundation_AbstractFoundation_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/SingletonHolder.h" +#include "Poco/SharedPtr.h" +#include "Poco/ActiveResult.h" +#include "Poco/ActiveMethod.h" +#include "Poco/Mutex.h" + + +namespace Poco { + + +template +class AbstractEvent + /// An abstractEvent is the super-class of all events. + /// It works similar to the way C# handles notifications (aka events in C#). + /// Events can be used to send information to a set of observers + /// which are registered at the event. The type of the data is specified with + /// the template parameter TArgs. The TStrategy parameter must be a subclass + /// of NotificationStrategy. The parameter TDelegate can either be a subclass of AbstractDelegate + /// or of PriorityAbstractDelegate. + /// + /// Note that AbstractEvent should never be used directly. One ought to use + /// one of its subclasses which set the TStrategy and TDelegate template parameters + /// to fixed values. For most use-cases the BasicEvent template will be sufficient. + /// + /// Use events by adding them as public members to the object which is throwing notifications: + /// + /// class MyData + /// { + /// public: + /// Poco::BasicEvent AgeChanged; + /// + /// MyData(); + /// ... + /// }; + /// + /// Throwing the event can be done either by the events notify or notifyAsync method: + /// + /// void MyData::setAge(int i) + /// { + /// this->_age = i; + /// AgeChanged.notify(this, this->_age); + /// } + /// + /// Note that notify and notifyAsync do not catch exceptions, i.e. in case a delegate + /// throws an exception, the notify is immediately aborted and the exception is thrown + /// back to the caller. + /// + /// Delegates can register methods at the event. In the case of a BasicEvent or FIFOEvent + /// the Delegate template is used, in case of an PriorityEvent a PriorityDelegate is used. + /// Mixing of observers, e.g. using a PriorityDelegate with a BasicEvent is not possible and + /// checked for during compile time. + /// Events require the observers to follow the following method signature: + /// + /// void onEvent(const void* pSender, TArgs& args); + /// + /// For performance reasons arguments are always sent by reference. This also allows observers + /// to modify the sent argument. To prevent that, use as template + /// parameter. A non-conformant method signature leads to compile errors. + /// + /// Assuming that the observer meets the method signature requirement, it can register + /// this method with the += operator: + /// + /// class MyController + /// { + /// protected: + /// MyData _data; + /// + /// void onDataChanged(void* pSender, int& data); + /// ... + /// }; + /// + /// MyController::MyController() + /// { + /// _data.AgeChanged += Delegate(this, &MyController::onDataChanged); + /// } + /// + /// In some cases it might be desirable to work with automatically expiring registrations: + /// + /// _data.DataChanged += Expire(Delegate(this, &MyController::onDataChanged), 1000); + /// + /// This will add a delegate to the event which will automatically be removed in 1000 millisecs. + /// + /// Unregistering happens via the -= operator. Forgetting to unregister a method will lead to + /// segmentation faults later, when one tries to send a notify to a no longer existing object. + /// + /// MyController::~MyController() + /// { + /// _data.DataChanged -= Delegate(this, &MyController::onDataChanged); + /// } + /// + /// For further examples refer to the event testsuites. +{ +public: + AbstractEvent(): + _executeAsync(this, &AbstractEvent::executeAsyncImpl), + _enabled(true) + { + } + + AbstractEvent(const TStrategy& strat): + _executeAsync(this, &AbstractEvent::executeAsyncImpl), + _strategy(strat), + _enabled(true) + { + } + + virtual ~AbstractEvent() + { + } + + void operator += (const TDelegate& aDelegate) + /// Adds a delegate to the event. If the observer is equal to an + /// already existing one (determined by the < operator), + /// it will simply replace the existing observer. + /// This behavior is determined by the TStrategy. Current implementations + /// (DefaultStrategy, FIFOStrategy) follow that guideline but future ones + /// can deviate. + { + FastMutex::ScopedLock lock(_mutex); + _strategy.add(aDelegate); + } + + void operator -= (const TDelegate& aDelegate) + /// Removes a delegate from the event. If the delegate is equal to an + /// already existing one is determined by the < operator. + /// If the observer is not found, the unregister will be ignored + { + FastMutex::ScopedLock lock(_mutex); + _strategy.remove(aDelegate); + } + + void notify(const void* pSender, TArgs& args) + /// Sends a notification to all registered delegates. The order is + /// determined by the TStrategy. This method is blocking. While executing, + /// other objects can change the list of delegates. These changes don't + /// influence the current active notifications but are activated with + /// the next notify. If one of the delegates throws an exception, the notify + /// method is immediately aborted and the exception is reported to the caller. + { + SharedPtr ptrStrat; + bool enabled = false; + + { + FastMutex::ScopedLock lock(_mutex); + enabled = _enabled; + if (_enabled) + { + // thread-safeness: + // copy should be faster and safer than blocking until + // execution ends + ptrStrat = new TStrategy(_strategy); + } + } + + if (enabled) + { + ptrStrat->notify(pSender, args); + } + } + + ActiveResult notifyAsync(const void* pSender, const TArgs& args) + /// Sends a notification to all registered delegates. The order is + /// determined by the TStrategy. This method is not blocking and will + /// immediately return. The delegates are invoked in a seperate thread. + /// Call activeResult.wait() to wait until the notification has ended. + /// While executing, other objects can change the delegate list. These changes don't + /// influence the current active notifications but are activated with + /// the next notify. If one of the delegates throws an exception, the execution + /// is aborted and the exception is reported to the caller. + { + NotifyAsyncParams params(pSender, args); + + { + FastMutex::ScopedLock lock(_mutex); + + // thread-safeness: + // copy should be faster and safer than blocking until + // execution ends + // make a copy of the strategy here to guarantee that + // between notifyAsync and the execution of the method no changes can occur + + params.ptrStrat = SharedPtr(new TStrategy(_strategy)); + params.enabled = _enabled; + } + + ActiveResult result = _executeAsync(params); + return result; + } + + void enable() + /// Enables the event + { + FastMutex::ScopedLock lock(_mutex); + _enabled = true; + } + + void disable() + /// Disables the event. notify and notifyAsnyc will be ignored, + /// but adding/removing delegates is still allowed. + { + FastMutex::ScopedLock lock(_mutex); + _enabled = false; + } + + bool isEnabled() const + { + FastMutex::ScopedLock lock(_mutex); + return _enabled; + } + + void clear() + /// Removes all delegates. + { + FastMutex::ScopedLock lock(_mutex); + _strategy.clear(); + } + +protected: + struct NotifyAsyncParams + { + SharedPtr ptrStrat; + const void* pSender; + TArgs args; + bool enabled; + + NotifyAsyncParams(const void* pSend, const TArgs& a):ptrStrat(), pSender(pSend), args(a), enabled(true) + /// default constructor reduces the need for TArgs to have an empty constructor, only copy constructor is needed. + { + } + }; + + ActiveMethod _executeAsync; + + TArgs executeAsyncImpl(const NotifyAsyncParams& par) + { + if (!par.enabled) + { + return par.args; + } + + NotifyAsyncParams params = par; + TArgs retArgs(params.args); + params.ptrStrat->notify(params.pSender, retArgs); + return retArgs; + } + + TStrategy _strategy; /// The strategy used to notify observers. + bool _enabled; /// Stores if an event is enabled. Notfies on disabled events have no effect + /// but it is possible to change the observers. + mutable FastMutex _mutex; + +private: + AbstractEvent(const AbstractEvent& other); + AbstractEvent& operator = (const AbstractEvent& other); +}; + + +} // namespace Poco + + +#endif diff --git a/Foundation/include/Poco/AbstractObserver.h b/Foundation/include/Poco/AbstractObserver.h index 7faafd955..a87a2444e 100644 --- a/Foundation/include/Poco/AbstractObserver.h +++ b/Foundation/include/Poco/AbstractObserver.h @@ -1,71 +1,71 @@ -// -// AbstractObserver.h -// -// $Id: //poco/1.2/Foundation/include/Poco/AbstractObserver.h#1 $ -// -// Library: Foundation -// Package: Notifications -// Module: NotificationCenter -// -// Definition of the AbstractObserver class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_AbstractObserver_INCLUDED -#define Foundation_AbstractObserver_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/Notification.h" - - -namespace Poco { - - -class Foundation_API AbstractObserver - /// The base class for all instantiations of - /// the Observer and NObserver template classes. -{ -public: - AbstractObserver(); - AbstractObserver(const AbstractObserver& observer); - virtual ~AbstractObserver(); - - AbstractObserver& operator = (const AbstractObserver& observer); - - virtual void notify(Notification* pNf) const = 0; - virtual bool equals(const AbstractObserver& observer) const = 0; - virtual bool accepts(Notification* pNf) const = 0; - virtual AbstractObserver* clone() const = 0; -}; - - -} // namespace Poco - - -#endif // Foundation_AbstractObserver_INCLUDED +// +// AbstractObserver.h +// +// $Id: //poco/1.2/Foundation/include/Poco/AbstractObserver.h#1 $ +// +// Library: Foundation +// Package: Notifications +// Module: NotificationCenter +// +// Definition of the AbstractObserver class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_AbstractObserver_INCLUDED +#define Foundation_AbstractObserver_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Notification.h" + + +namespace Poco { + + +class Foundation_API AbstractObserver + /// The base class for all instantiations of + /// the Observer and NObserver template classes. +{ +public: + AbstractObserver(); + AbstractObserver(const AbstractObserver& observer); + virtual ~AbstractObserver(); + + AbstractObserver& operator = (const AbstractObserver& observer); + + virtual void notify(Notification* pNf) const = 0; + virtual bool equals(const AbstractObserver& observer) const = 0; + virtual bool accepts(Notification* pNf) const = 0; + virtual AbstractObserver* clone() const = 0; +}; + + +} // namespace Poco + + +#endif // Foundation_AbstractObserver_INCLUDED diff --git a/Foundation/include/Poco/AbstractPriorityDelegate.h b/Foundation/include/Poco/AbstractPriorityDelegate.h index 6d0eec585..899bf192e 100644 --- a/Foundation/include/Poco/AbstractPriorityDelegate.h +++ b/Foundation/include/Poco/AbstractPriorityDelegate.h @@ -1,109 +1,109 @@ -// -// AbstractPriorityDelegate.h -// -// $Id: //poco/1.2/Foundation/include/Poco/AbstractPriorityDelegate.h#2 $ -// -// Library: Foundation -// Package: Events -// Module: AbstractPriorityDelegate -// -// Implementation of the AbstractPriorityDelegate template. -// -// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_AbstractPriorityDelegate_INCLUDED -#define Foundation_AbstractPriorityDelegate_INCLUDED - - -#include "Poco/Foundation.h" - - -namespace Poco { - - -template -class AbstractPriorityDelegate - /// Interface for PriorityDelegate and PriorityExpire. - /// Very similar to AbstractDelegate but having two separate files (no inheritance) - /// allows to have compile-time checks when registering an observer - /// instead of run-time checks. -{ -public: - AbstractPriorityDelegate(void* pTarget, int prio): - _pTarget(pTarget), - _priority(prio) - { - } - - AbstractPriorityDelegate(const AbstractPriorityDelegate& del): - _pTarget(del._pTarget), - _priority(del._priority) - { - } - - virtual ~AbstractPriorityDelegate() - { - } - - virtual bool notify(const void* sender, TArgs & arguments) = 0; - /// Returns false, if the Delegate is no longer valid, thus indicating an expire - - virtual AbstractPriorityDelegate* clone() const = 0; - // Returns a deep-copy of the object. - - bool operator < (const AbstractPriorityDelegate& other) const - /// Operator used for comparing AbstractPriorityDelegates in a collection. - { - if (_priority == other._priority) - { - return _pTarget < other._pTarget; - } - - return (_priority < other._priority); - } - - void* target() const - { - return _pTarget; - } - - int priority() const - { - return _priority; - } - -protected: - void* _pTarget; - int _priority; -}; - - -} // namespace Poco - - -#endif +// +// AbstractPriorityDelegate.h +// +// $Id: //poco/1.2/Foundation/include/Poco/AbstractPriorityDelegate.h#2 $ +// +// Library: Foundation +// Package: Events +// Module: AbstractPriorityDelegate +// +// Implementation of the AbstractPriorityDelegate template. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_AbstractPriorityDelegate_INCLUDED +#define Foundation_AbstractPriorityDelegate_INCLUDED + + +#include "Poco/Foundation.h" + + +namespace Poco { + + +template +class AbstractPriorityDelegate + /// Interface for PriorityDelegate and PriorityExpire. + /// Very similar to AbstractDelegate but having two separate files (no inheritance) + /// allows to have compile-time checks when registering an observer + /// instead of run-time checks. +{ +public: + AbstractPriorityDelegate(void* pTarget, int prio): + _pTarget(pTarget), + _priority(prio) + { + } + + AbstractPriorityDelegate(const AbstractPriorityDelegate& del): + _pTarget(del._pTarget), + _priority(del._priority) + { + } + + virtual ~AbstractPriorityDelegate() + { + } + + virtual bool notify(const void* sender, TArgs & arguments) = 0; + /// Returns false, if the Delegate is no longer valid, thus indicating an expire + + virtual AbstractPriorityDelegate* clone() const = 0; + // Returns a deep-copy of the object. + + bool operator < (const AbstractPriorityDelegate& other) const + /// Operator used for comparing AbstractPriorityDelegates in a collection. + { + if (_priority == other._priority) + { + return _pTarget < other._pTarget; + } + + return (_priority < other._priority); + } + + void* target() const + { + return _pTarget; + } + + int priority() const + { + return _priority; + } + +protected: + void* _pTarget; + int _priority; +}; + + +} // namespace Poco + + +#endif diff --git a/Foundation/include/Poco/AbstractStrategy.h b/Foundation/include/Poco/AbstractStrategy.h index 19a0cbd8b..fdf8be002 100644 --- a/Foundation/include/Poco/AbstractStrategy.h +++ b/Foundation/include/Poco/AbstractStrategy.h @@ -1,91 +1,91 @@ -// -// AbstractStrategy.h -// -// $Id: //poco/1.2/Foundation/include/Poco/AbstractStrategy.h#2 $ -// -// Library: Foundation -// Package: Cache -// Module: AbstractCache -// -// Definition of the AbstractStrategy class. -// -// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_AbstractStrategy_INCLUDED -#define Foundation_AbstractStrategy_INCLUDED - - -#include "Poco/KeyValueArgs.h" -#include "Poco/ValidArgs.h" -#include "Poco/EventArgs.h" - - -namespace Poco { - - -template -class AbstractStrategy - /// An AbstractStrategy is the interface for all strategies. -{ -public: - AbstractStrategy() - { - } - - virtual ~AbstractStrategy() - { - } - - virtual void onAdd(const void* pSender, const KeyValueArgs & key) = 0; - /// Adds the key to the strategy. - /// If for the key already an entry exists, an excpetion will be thrown. - - virtual void onRemove(const void* pSender, const TKey& key) = 0; - /// Removes an entry from the strategy. If the entry is not found - /// the remove is ignored. - - virtual void onGet(const void* pSender, const TKey& key) = 0; - /// Informs the strategy that a read-access happens to an element. - - virtual void onClear(const void* pSender, const EventArgs& args) = 0; - /// Removes all elements from the cache. - - virtual void onIsValid(const void* pSender, ValidArgs& key) = 0; - /// Used to query if a key is still valid (i.e. cached). - - virtual void onReplace(const void* pSender, std::set& elemsToRemove) = 0; - /// Used by the Strategy to indicate which elements should be removed from - /// the cache. Note that onReplace does not change the current list of keys. - /// The cache object is reponsible to remove the elements. -}; - - -} // namespace Poco - - -#endif +// +// AbstractStrategy.h +// +// $Id: //poco/1.2/Foundation/include/Poco/AbstractStrategy.h#2 $ +// +// Library: Foundation +// Package: Cache +// Module: AbstractCache +// +// Definition of the AbstractStrategy class. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_AbstractStrategy_INCLUDED +#define Foundation_AbstractStrategy_INCLUDED + + +#include "Poco/KeyValueArgs.h" +#include "Poco/ValidArgs.h" +#include "Poco/EventArgs.h" + + +namespace Poco { + + +template +class AbstractStrategy + /// An AbstractStrategy is the interface for all strategies. +{ +public: + AbstractStrategy() + { + } + + virtual ~AbstractStrategy() + { + } + + virtual void onAdd(const void* pSender, const KeyValueArgs & key) = 0; + /// Adds the key to the strategy. + /// If for the key already an entry exists, an excpetion will be thrown. + + virtual void onRemove(const void* pSender, const TKey& key) = 0; + /// Removes an entry from the strategy. If the entry is not found + /// the remove is ignored. + + virtual void onGet(const void* pSender, const TKey& key) = 0; + /// Informs the strategy that a read-access happens to an element. + + virtual void onClear(const void* pSender, const EventArgs& args) = 0; + /// Removes all elements from the cache. + + virtual void onIsValid(const void* pSender, ValidArgs& key) = 0; + /// Used to query if a key is still valid (i.e. cached). + + virtual void onReplace(const void* pSender, std::set& elemsToRemove) = 0; + /// Used by the Strategy to indicate which elements should be removed from + /// the cache. Note that onReplace does not change the current list of keys. + /// The cache object is reponsible to remove the elements. +}; + + +} // namespace Poco + + +#endif diff --git a/Foundation/include/Poco/ActiveDispatcher.h b/Foundation/include/Poco/ActiveDispatcher.h index ae3d7fdb3..c335bc2b3 100644 --- a/Foundation/include/Poco/ActiveDispatcher.h +++ b/Foundation/include/Poco/ActiveDispatcher.h @@ -1,137 +1,137 @@ -// -// ActiveDispatcher.h -// -// $Id: //poco/1.2/Foundation/include/Poco/ActiveDispatcher.h#1 $ -// -// Library: Foundation -// Package: Threading -// Module: ActiveObjects -// -// Definition of the ActiveDispatcher class. -// -// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_ActiveDispatcher_INCLUDED -#define Foundation_ActiveDispatcher_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/Runnable.h" -#include "Poco/Thread.h" -#include "Poco/ActiveStarter.h" -#include "Poco/NotificationQueue.h" - - -namespace Poco { - - -class Foundation_API ActiveDispatcher: protected Runnable - /// This class is used to implement an active object - /// with strictly serialized method execution. - /// - /// An active object, with is an ordinary object - /// containing ActiveMethod members, executes all - /// active methods in their own thread. - /// This behavior does not fit the "classic" - /// definition of an active object, which serializes - /// the execution of active methods (in other words, - /// only one active method can be running at any given - /// time). - /// - /// Using this class as a base class, the serializing - /// behavior for active objects can be implemented. - /// - /// The following example shows how this is done: - /// - /// class ActiveObject: public ActiveDispatcher - /// { - /// public: - /// ActiveObject(): - /// exampleActiveMethod(this, &ActiveObject::exampleActiveMethodImpl) - /// { - /// } - /// - /// ActiveMethod > exampleActiveMethod; - /// - /// protected: - /// std::string exampleActiveMethodImpl(const std::string& arg) - /// { - /// ... - /// } - /// }; - /// - /// The only things different from the example in - /// ActiveMethod is that the ActiveObject in this case - /// inherits from ActiveDispatcher, and that the ActiveMethod - /// template for exampleActiveMethod has an additional parameter, - /// specifying the specialized ActiveStarter for ActiveDispatcher. -{ -public: - ActiveDispatcher(); - /// Creates the ActiveDispatcher. - - ActiveDispatcher(Thread::Priority prio); - /// Creates the ActiveDispatcher and sets - /// the priority of its thread. - - virtual ~ActiveDispatcher(); - /// Destroys the ActiveDispatcher. - - void start(Runnable* pRunnable); - /// Adds the Runnable to the dispatch queue. - - void cancel(); - /// Cancels all queued methods. - -protected: - void run(); - void stop(); - -private: - Thread _thread; - NotificationQueue _queue; -}; - - -template <> -class ActiveStarter - /// A specialization of ActiveStarter - /// for ActiveDispatcher. -{ -public: - static void start(ActiveDispatcher* pOwner, Runnable* pRunnable) - { - pOwner->start(pRunnable); - } -}; - - -} // namespace Poco - - -#endif // Foundation_ActiveDispatcher_INCLUDED +// +// ActiveDispatcher.h +// +// $Id: //poco/1.2/Foundation/include/Poco/ActiveDispatcher.h#1 $ +// +// Library: Foundation +// Package: Threading +// Module: ActiveObjects +// +// Definition of the ActiveDispatcher class. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_ActiveDispatcher_INCLUDED +#define Foundation_ActiveDispatcher_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Runnable.h" +#include "Poco/Thread.h" +#include "Poco/ActiveStarter.h" +#include "Poco/NotificationQueue.h" + + +namespace Poco { + + +class Foundation_API ActiveDispatcher: protected Runnable + /// This class is used to implement an active object + /// with strictly serialized method execution. + /// + /// An active object, with is an ordinary object + /// containing ActiveMethod members, executes all + /// active methods in their own thread. + /// This behavior does not fit the "classic" + /// definition of an active object, which serializes + /// the execution of active methods (in other words, + /// only one active method can be running at any given + /// time). + /// + /// Using this class as a base class, the serializing + /// behavior for active objects can be implemented. + /// + /// The following example shows how this is done: + /// + /// class ActiveObject: public ActiveDispatcher + /// { + /// public: + /// ActiveObject(): + /// exampleActiveMethod(this, &ActiveObject::exampleActiveMethodImpl) + /// { + /// } + /// + /// ActiveMethod > exampleActiveMethod; + /// + /// protected: + /// std::string exampleActiveMethodImpl(const std::string& arg) + /// { + /// ... + /// } + /// }; + /// + /// The only things different from the example in + /// ActiveMethod is that the ActiveObject in this case + /// inherits from ActiveDispatcher, and that the ActiveMethod + /// template for exampleActiveMethod has an additional parameter, + /// specifying the specialized ActiveStarter for ActiveDispatcher. +{ +public: + ActiveDispatcher(); + /// Creates the ActiveDispatcher. + + ActiveDispatcher(Thread::Priority prio); + /// Creates the ActiveDispatcher and sets + /// the priority of its thread. + + virtual ~ActiveDispatcher(); + /// Destroys the ActiveDispatcher. + + void start(Runnable* pRunnable); + /// Adds the Runnable to the dispatch queue. + + void cancel(); + /// Cancels all queued methods. + +protected: + void run(); + void stop(); + +private: + Thread _thread; + NotificationQueue _queue; +}; + + +template <> +class ActiveStarter + /// A specialization of ActiveStarter + /// for ActiveDispatcher. +{ +public: + static void start(ActiveDispatcher* pOwner, Runnable* pRunnable) + { + pOwner->start(pRunnable); + } +}; + + +} // namespace Poco + + +#endif // Foundation_ActiveDispatcher_INCLUDED diff --git a/Foundation/include/Poco/ActiveMethod.h b/Foundation/include/Poco/ActiveMethod.h index 2ac11e0a7..63e5bb430 100644 --- a/Foundation/include/Poco/ActiveMethod.h +++ b/Foundation/include/Poco/ActiveMethod.h @@ -1,130 +1,130 @@ -// -// ActiveMethod.h -// -// $Id: //poco/1.2/Foundation/include/Poco/ActiveMethod.h#1 $ -// -// Library: Foundation -// Package: Threading -// Module: ActiveObjects -// -// Definition of the ActiveMethod class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_ActiveMethod_INCLUDED -#define Foundation_ActiveMethod_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/ActiveResult.h" -#include "Poco/ActiveRunnable.h" -#include "Poco/ActiveStarter.h" - - -namespace Poco { - - -template > -class ActiveMethod - /// An active method is a method that, when called, executes - /// in its own thread. ActiveMethod's take exactly one - /// argument and can return a value. To pass more than one - /// argument to the method, use a struct. - /// The following example shows how to add an ActiveMethod - /// to a class: - /// - /// class ActiveObject - /// { - /// public: - /// ActiveObject(): - /// exampleActiveMethod(this, &ActiveObject::exampleActiveMethodImpl) - /// { - /// } - /// - /// ActiveMethod exampleActiveMethod; - /// - /// protected: - /// std::string exampleActiveMethodImpl(const std::string& arg) - /// { - /// ... - /// } - /// }; - /// - /// And following is an example that shows how to invoke an ActiveMethod. - /// - /// ActiveObject myActiveObject; - /// ActiveResult result = myActiveObject.exampleActiveMethod("foo"); - /// ... - /// result.wait(); - /// std::cout << result.data() << std::endl; - /// - /// The way an ActiveMethod is started can be changed by passing a StarterType - /// template argument with a corresponding class. The default ActiveStarter - /// starts the method in its own thread, obtained from a thread pool. - /// - /// For an alternative implementation of StarterType, see ActiveDispatcher. - /// - /// For methods that do not require an argument or a return value, the Void - /// class can be used. -{ -public: - typedef ResultType (OwnerType::*Callback)(const ArgType&); - typedef ActiveResult ActiveResultType; - typedef ActiveRunnable ActiveRunnableType; - - ActiveMethod(OwnerType* pOwner, Callback method): - _pOwner(pOwner), - _method(method) - /// Creates an ActiveMethod object. - { - poco_check_ptr (pOwner); - } - - ActiveResultType operator () (const ArgType& arg) - /// Invokes the ActiveMethod. - { - ActiveResultType result(new ActiveResultHolder()); - ActiveRunnableType* pRunnable = new ActiveRunnableType(_pOwner, _method, arg, result); - StarterType::start(_pOwner, pRunnable); - return result; - } - -private: - ActiveMethod(); - ActiveMethod(const ActiveMethod&); - ActiveMethod& operator = (const ActiveMethod&); - - OwnerType* _pOwner; - Callback _method; -}; - - -} // namespace Poco - - -#endif // Foundation_ActiveMethod_INCLUDED +// +// ActiveMethod.h +// +// $Id: //poco/1.2/Foundation/include/Poco/ActiveMethod.h#1 $ +// +// Library: Foundation +// Package: Threading +// Module: ActiveObjects +// +// Definition of the ActiveMethod class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_ActiveMethod_INCLUDED +#define Foundation_ActiveMethod_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/ActiveResult.h" +#include "Poco/ActiveRunnable.h" +#include "Poco/ActiveStarter.h" + + +namespace Poco { + + +template > +class ActiveMethod + /// An active method is a method that, when called, executes + /// in its own thread. ActiveMethod's take exactly one + /// argument and can return a value. To pass more than one + /// argument to the method, use a struct. + /// The following example shows how to add an ActiveMethod + /// to a class: + /// + /// class ActiveObject + /// { + /// public: + /// ActiveObject(): + /// exampleActiveMethod(this, &ActiveObject::exampleActiveMethodImpl) + /// { + /// } + /// + /// ActiveMethod exampleActiveMethod; + /// + /// protected: + /// std::string exampleActiveMethodImpl(const std::string& arg) + /// { + /// ... + /// } + /// }; + /// + /// And following is an example that shows how to invoke an ActiveMethod. + /// + /// ActiveObject myActiveObject; + /// ActiveResult result = myActiveObject.exampleActiveMethod("foo"); + /// ... + /// result.wait(); + /// std::cout << result.data() << std::endl; + /// + /// The way an ActiveMethod is started can be changed by passing a StarterType + /// template argument with a corresponding class. The default ActiveStarter + /// starts the method in its own thread, obtained from a thread pool. + /// + /// For an alternative implementation of StarterType, see ActiveDispatcher. + /// + /// For methods that do not require an argument or a return value, the Void + /// class can be used. +{ +public: + typedef ResultType (OwnerType::*Callback)(const ArgType&); + typedef ActiveResult ActiveResultType; + typedef ActiveRunnable ActiveRunnableType; + + ActiveMethod(OwnerType* pOwner, Callback method): + _pOwner(pOwner), + _method(method) + /// Creates an ActiveMethod object. + { + poco_check_ptr (pOwner); + } + + ActiveResultType operator () (const ArgType& arg) + /// Invokes the ActiveMethod. + { + ActiveResultType result(new ActiveResultHolder()); + ActiveRunnableType* pRunnable = new ActiveRunnableType(_pOwner, _method, arg, result); + StarterType::start(_pOwner, pRunnable); + return result; + } + +private: + ActiveMethod(); + ActiveMethod(const ActiveMethod&); + ActiveMethod& operator = (const ActiveMethod&); + + OwnerType* _pOwner; + Callback _method; +}; + + +} // namespace Poco + + +#endif // Foundation_ActiveMethod_INCLUDED diff --git a/Foundation/include/Poco/ActiveResult.h b/Foundation/include/Poco/ActiveResult.h index 905dd967c..4016c4a22 100644 --- a/Foundation/include/Poco/ActiveResult.h +++ b/Foundation/include/Poco/ActiveResult.h @@ -1,289 +1,289 @@ -// -// ActiveResult.h -// -// $Id: //poco/1.2/Foundation/include/Poco/ActiveResult.h#1 $ -// -// Library: Foundation -// Package: Threading -// Module: ActiveObjects -// -// Definition of the ActiveResult class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_ActiveResult_INCLUDED -#define Foundation_ActiveResult_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/Mutex.h" -#include "Poco/Event.h" -#include "Poco/RefCountedObject.h" -#include "Poco/Exception.h" - - -namespace Poco { - - -template -class ActiveResultHolder: public RefCountedObject - /// This class holds the result of an asynchronous method - /// invocation. It is used to pass the result from the - /// execution thread back to the invocation thread. - /// The class uses reference counting for memory management. - /// Do not use this class directly, use ActiveResult instead. -{ -public: - ActiveResultHolder(): - _pExc(0), - _event(false) - /// Creates an ActiveResultHolder. - { - } - - ResultType& data() - /// Returns a reference to the actual result. - { - return _data; - } - - void wait() - /// Pauses the caller until the result becomes available. - { - _event.wait(); - } - - bool tryWait(long milliseconds) - /// Waits up to the specified interval for the result to - /// become available. Returns true if the result became - /// available, false otherwise. - { - return _event.tryWait(milliseconds); - } - - void wait(long milliseconds) - /// Waits up to the specified interval for the result to - /// become available. Throws a TimeoutException if the - /// result did not became available. - { - _event.wait(milliseconds); - } - - void notify() - /// Notifies the invoking thread that the result became available. - { - _event.set(); - } - - bool failed() const - /// Returns true if the active method failed (and threw an exception). - /// Information about the exception can be obtained by calling error(). - { - return _pExc != 0; - } - - std::string error() const - /// If the active method threw an exception, a textual representation - /// of the exception is returned. An empty string is returned if the - /// active method completed successfully. - { - if (_pExc) - return _pExc->message(); - else - return std::string(); - } - - Exception* exception() const - /// If the active method threw an exception, a clone of the exception - /// object is returned, otherwise null. - { - return _pExc; - } - - void error(const Exception& exc) - /// Sets the exception. - { - delete _pExc; - _pExc = exc.clone(); - } - - void error(const std::string& msg) - /// Sets the exception. - { - delete _pExc; - _pExc = new UnhandledException(msg); - } - -protected: - ~ActiveResultHolder() - { - delete _pExc; - } - -private: - ResultType _data; - Exception* _pExc; - Event _event; -}; - - -template -class ActiveResult - /// This class holds the result of an asynchronous method - /// invocation (see class ActiveMethod). It is used to pass the - /// result from the execution thread back to the invocation thread. -{ -public: - typedef RT ResultType; - typedef ActiveResultHolder ActiveResultHolderType; - - ActiveResult(ActiveResultHolderType* pHolder): - _pHolder(pHolder) - /// Creates the active result. For internal use only. - { - poco_check_ptr (pHolder); - } - - ActiveResult(const ActiveResult& result) - /// Copy constructor. - { - _pHolder = result._pHolder; - _pHolder->duplicate(); - } - - ~ActiveResult() - /// Destroys the result. - { - _pHolder->release(); - } - - ActiveResult& operator = (const ActiveResult& result) - /// Assignment operator. - { - if (&result != this) - { - _pHolder->release(); - _pHolder = result._pHolder; - _pHolder->duplicate(); - } - return *this; - } - - const ResultType& data() const - /// Returns a reference to the result data. - { - return _pHolder->data(); - } - - void wait() - /// Pauses the caller until the result becomes available. - { - _pHolder->wait(); - } - - bool tryWait(long milliseconds) - /// Waits up to the specified interval for the result to - /// become available. Returns true if the result became - /// available, false otherwise. - { - return _pHolder->tryWait(milliseconds); - } - - void wait(long milliseconds) - /// Waits up to the specified interval for the result to - /// become available. Throws a TimeoutException if the - /// result did not became available. - { - _pHolder->wait(milliseconds); - } - - bool available() const - /// Returns true if a result is available. - { - return _pHolder->tryWait(0); - } - - bool failed() const - /// Returns true if the active method failed (and threw an exception). - /// Information about the exception can be obtained by calling error(). - { - return _pHolder->failed(); - } - - std::string error() const - /// If the active method threw an exception, a textual representation - /// of the exception is returned. An empty string is returned if the - /// active method completed successfully. - { - return _pHolder->error(); - } - - Exception* exception() const - /// If the active method threw an exception, a clone of the exception - /// object is returned, otherwise null. - { - return _pHolder->exception(); - } - - void notify() - /// Notifies the invoking thread that the result became available. - /// For internal use only. - { - _pHolder->notify(); - } - - ResultType& data() - /// Returns a non-const reference to the result data. For internal - /// use only. - { - return _pHolder->data(); - } - - void error(const std::string& msg) - /// Sets the failed flag and the exception message. - { - _pHolder->error(msg); - } - - void error(const Exception& exc) - /// Sets the failed flag and the exception message. - { - _pHolder->error(exc); - } - -private: - ActiveResult(); - - ActiveResultHolderType* _pHolder; -}; - - -} // namespace Poco - - -#endif // Foundation_ActiveResult_INCLUDED +// +// ActiveResult.h +// +// $Id: //poco/1.2/Foundation/include/Poco/ActiveResult.h#1 $ +// +// Library: Foundation +// Package: Threading +// Module: ActiveObjects +// +// Definition of the ActiveResult class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_ActiveResult_INCLUDED +#define Foundation_ActiveResult_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Mutex.h" +#include "Poco/Event.h" +#include "Poco/RefCountedObject.h" +#include "Poco/Exception.h" + + +namespace Poco { + + +template +class ActiveResultHolder: public RefCountedObject + /// This class holds the result of an asynchronous method + /// invocation. It is used to pass the result from the + /// execution thread back to the invocation thread. + /// The class uses reference counting for memory management. + /// Do not use this class directly, use ActiveResult instead. +{ +public: + ActiveResultHolder(): + _pExc(0), + _event(false) + /// Creates an ActiveResultHolder. + { + } + + ResultType& data() + /// Returns a reference to the actual result. + { + return _data; + } + + void wait() + /// Pauses the caller until the result becomes available. + { + _event.wait(); + } + + bool tryWait(long milliseconds) + /// Waits up to the specified interval for the result to + /// become available. Returns true if the result became + /// available, false otherwise. + { + return _event.tryWait(milliseconds); + } + + void wait(long milliseconds) + /// Waits up to the specified interval for the result to + /// become available. Throws a TimeoutException if the + /// result did not became available. + { + _event.wait(milliseconds); + } + + void notify() + /// Notifies the invoking thread that the result became available. + { + _event.set(); + } + + bool failed() const + /// Returns true if the active method failed (and threw an exception). + /// Information about the exception can be obtained by calling error(). + { + return _pExc != 0; + } + + std::string error() const + /// If the active method threw an exception, a textual representation + /// of the exception is returned. An empty string is returned if the + /// active method completed successfully. + { + if (_pExc) + return _pExc->message(); + else + return std::string(); + } + + Exception* exception() const + /// If the active method threw an exception, a clone of the exception + /// object is returned, otherwise null. + { + return _pExc; + } + + void error(const Exception& exc) + /// Sets the exception. + { + delete _pExc; + _pExc = exc.clone(); + } + + void error(const std::string& msg) + /// Sets the exception. + { + delete _pExc; + _pExc = new UnhandledException(msg); + } + +protected: + ~ActiveResultHolder() + { + delete _pExc; + } + +private: + ResultType _data; + Exception* _pExc; + Event _event; +}; + + +template +class ActiveResult + /// This class holds the result of an asynchronous method + /// invocation (see class ActiveMethod). It is used to pass the + /// result from the execution thread back to the invocation thread. +{ +public: + typedef RT ResultType; + typedef ActiveResultHolder ActiveResultHolderType; + + ActiveResult(ActiveResultHolderType* pHolder): + _pHolder(pHolder) + /// Creates the active result. For internal use only. + { + poco_check_ptr (pHolder); + } + + ActiveResult(const ActiveResult& result) + /// Copy constructor. + { + _pHolder = result._pHolder; + _pHolder->duplicate(); + } + + ~ActiveResult() + /// Destroys the result. + { + _pHolder->release(); + } + + ActiveResult& operator = (const ActiveResult& result) + /// Assignment operator. + { + if (&result != this) + { + _pHolder->release(); + _pHolder = result._pHolder; + _pHolder->duplicate(); + } + return *this; + } + + const ResultType& data() const + /// Returns a reference to the result data. + { + return _pHolder->data(); + } + + void wait() + /// Pauses the caller until the result becomes available. + { + _pHolder->wait(); + } + + bool tryWait(long milliseconds) + /// Waits up to the specified interval for the result to + /// become available. Returns true if the result became + /// available, false otherwise. + { + return _pHolder->tryWait(milliseconds); + } + + void wait(long milliseconds) + /// Waits up to the specified interval for the result to + /// become available. Throws a TimeoutException if the + /// result did not became available. + { + _pHolder->wait(milliseconds); + } + + bool available() const + /// Returns true if a result is available. + { + return _pHolder->tryWait(0); + } + + bool failed() const + /// Returns true if the active method failed (and threw an exception). + /// Information about the exception can be obtained by calling error(). + { + return _pHolder->failed(); + } + + std::string error() const + /// If the active method threw an exception, a textual representation + /// of the exception is returned. An empty string is returned if the + /// active method completed successfully. + { + return _pHolder->error(); + } + + Exception* exception() const + /// If the active method threw an exception, a clone of the exception + /// object is returned, otherwise null. + { + return _pHolder->exception(); + } + + void notify() + /// Notifies the invoking thread that the result became available. + /// For internal use only. + { + _pHolder->notify(); + } + + ResultType& data() + /// Returns a non-const reference to the result data. For internal + /// use only. + { + return _pHolder->data(); + } + + void error(const std::string& msg) + /// Sets the failed flag and the exception message. + { + _pHolder->error(msg); + } + + void error(const Exception& exc) + /// Sets the failed flag and the exception message. + { + _pHolder->error(exc); + } + +private: + ActiveResult(); + + ActiveResultHolderType* _pHolder; +}; + + +} // namespace Poco + + +#endif // Foundation_ActiveResult_INCLUDED diff --git a/Foundation/include/Poco/ActiveRunnable.h b/Foundation/include/Poco/ActiveRunnable.h index a743e7aca..22dadba5c 100644 --- a/Foundation/include/Poco/ActiveRunnable.h +++ b/Foundation/include/Poco/ActiveRunnable.h @@ -1,103 +1,103 @@ -// -// ActiveRunnable.h -// -// $Id: //poco/1.2/Foundation/include/Poco/ActiveRunnable.h#1 $ -// -// Library: Foundation -// Package: Threading -// Module: ActiveObjects -// -// Definition of the ActiveRunnable class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_ActiveRunnable_INCLUDED -#define Foundation_ActiveRunnable_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/ActiveResult.h" -#include "Poco/Runnable.h" -#include "Poco/Exception.h" - - -namespace Poco { - - -template -class ActiveRunnable: public Runnable - /// This class is used by ActiveMethod. - /// See the ActiveMethod class for more information. -{ -public: - typedef ResultType (OwnerType::*Callback)(const ArgType&); - typedef ActiveResult ActiveResultType; - - ActiveRunnable(OwnerType* pOwner, Callback method, const ArgType& arg, const ActiveResultType& result): - _pOwner(pOwner), - _method(method), - _arg(arg), - _result(result) - { - poco_check_ptr (pOwner); - } - - void run() - { - try - { - _result.data() = (_pOwner->*_method)(_arg); - } - catch (Exception& e) - { - _result.error(e); - } - catch (std::exception& e) - { - _result.error(e.what()); - } - catch (...) - { - _result.error("unknown exception"); - } - _result.notify(); - delete this; - } - -private: - OwnerType* _pOwner; - Callback _method; - ArgType _arg; - ActiveResultType _result; -}; - - -} // namespace Poco - - -#endif // Foundation_ActiveRunnable_INCLUDED +// +// ActiveRunnable.h +// +// $Id: //poco/1.2/Foundation/include/Poco/ActiveRunnable.h#1 $ +// +// Library: Foundation +// Package: Threading +// Module: ActiveObjects +// +// Definition of the ActiveRunnable class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_ActiveRunnable_INCLUDED +#define Foundation_ActiveRunnable_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/ActiveResult.h" +#include "Poco/Runnable.h" +#include "Poco/Exception.h" + + +namespace Poco { + + +template +class ActiveRunnable: public Runnable + /// This class is used by ActiveMethod. + /// See the ActiveMethod class for more information. +{ +public: + typedef ResultType (OwnerType::*Callback)(const ArgType&); + typedef ActiveResult ActiveResultType; + + ActiveRunnable(OwnerType* pOwner, Callback method, const ArgType& arg, const ActiveResultType& result): + _pOwner(pOwner), + _method(method), + _arg(arg), + _result(result) + { + poco_check_ptr (pOwner); + } + + void run() + { + try + { + _result.data() = (_pOwner->*_method)(_arg); + } + catch (Exception& e) + { + _result.error(e); + } + catch (std::exception& e) + { + _result.error(e.what()); + } + catch (...) + { + _result.error("unknown exception"); + } + _result.notify(); + delete this; + } + +private: + OwnerType* _pOwner; + Callback _method; + ArgType _arg; + ActiveResultType _result; +}; + + +} // namespace Poco + + +#endif // Foundation_ActiveRunnable_INCLUDED diff --git a/Foundation/include/Poco/ActiveStarter.h b/Foundation/include/Poco/ActiveStarter.h index 19305f594..9fdf34d0a 100644 --- a/Foundation/include/Poco/ActiveStarter.h +++ b/Foundation/include/Poco/ActiveStarter.h @@ -1,71 +1,71 @@ -// -// ActiveStarter.h -// -// $Id: //poco/1.2/Foundation/include/Poco/ActiveStarter.h#1 $ -// -// Library: Foundation -// Package: Threading -// Module: ActiveObjects -// -// Definition of the ActiveStarter class. -// -// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_ActiveStarter_INCLUDED -#define Foundation_ActiveStarter_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/ThreadPool.h" - - -namespace Poco { - - -class Runnable; - - -template -class ActiveStarter - /// The default implementation of the StarterType - /// policy for ActiveMethod. It starts the method - /// in its own thread, obtained from the default - /// thread pool. -{ -public: - static void start(OwnerType* pOwner, Runnable* pRunnable) - { - ThreadPool::defaultPool().start(*pRunnable); - } -}; - - -} // namespace Poco - - -#endif // Foundation_ActiveStarter_INCLUDED +// +// ActiveStarter.h +// +// $Id: //poco/1.2/Foundation/include/Poco/ActiveStarter.h#1 $ +// +// Library: Foundation +// Package: Threading +// Module: ActiveObjects +// +// Definition of the ActiveStarter class. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_ActiveStarter_INCLUDED +#define Foundation_ActiveStarter_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/ThreadPool.h" + + +namespace Poco { + + +class Runnable; + + +template +class ActiveStarter + /// The default implementation of the StarterType + /// policy for ActiveMethod. It starts the method + /// in its own thread, obtained from the default + /// thread pool. +{ +public: + static void start(OwnerType* pOwner, Runnable* pRunnable) + { + ThreadPool::defaultPool().start(*pRunnable); + } +}; + + +} // namespace Poco + + +#endif // Foundation_ActiveStarter_INCLUDED diff --git a/Foundation/include/Poco/Activity.h b/Foundation/include/Poco/Activity.h index 2a6439033..de63d3220 100644 --- a/Foundation/include/Poco/Activity.h +++ b/Foundation/include/Poco/Activity.h @@ -1,218 +1,218 @@ -// -// Activity.h -// -// $Id: //poco/1.2/Foundation/include/Poco/Activity.h#1 $ -// -// Library: Foundation -// Package: Threading -// Module: ActiveObjects -// -// Definition of the Activity template class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_Activity_INCLUDED -#define Foundation_Activity_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/RunnableAdapter.h" -#include "Poco/ThreadPool.h" -#include "Poco/Event.h" -#include "Poco/Mutex.h" - - -namespace Poco { - - -template -class Activity: public Runnable - /// This template class helps to implement active objects. - /// An active object uses threads to decouple method - /// execution from method invocation, or to perform tasks - /// autonomously, without intervention of a caller. - /// - /// An activity is a (typically longer running) method - /// that executes within its own task. Activities can - /// be started automatically (upon object construction) - /// or manually at a later time. Activities can also - /// be stopped at any time. However, to make stopping - /// an activity work, the method implementing the - /// activity has to check periodically whether it - /// has been requested to stop, and if so, return. - /// Activities are stopped before the object they belong to is - /// destroyed. Methods implementing activities cannot have arguments - /// or return values. - /// - /// Activity objects are used as follows: - /// - /// class ActiveObject - /// { - /// public: - /// ActiveObject(): - /// _activity(this, &ActiveObject::runActivity) - /// { - /// ... - /// } - /// - /// ... - /// - /// protected: - /// void runActivity() - /// { - /// while (!_activity.isStopped()) - /// { - /// ... - /// } - /// } - /// - /// private: - /// Activity _activity; - /// }; -{ -public: - typedef RunnableAdapter RunnableAdapterType; - typedef typename RunnableAdapterType::Callback Callback; - - Activity(C* pOwner, Callback method): - _pOwner(pOwner), - _runnable(*pOwner, method), - _stopped(true), - _running(false), - _done(false) - /// Creates the activity. Call start() to - /// start it. - { - poco_check_ptr (pOwner); - } - - ~Activity() - /// Stops and destroys the activity. - { - stop(); - wait(); - } - - void start() - /// Starts the activity by acquiring a - /// thread for it from the default thread pool. - { - FastMutex::ScopedLock lock(_mutex); - - if (_stopped) - { - _done.reset(); - _stopped = false; - _running = true; - try - { - ThreadPool::defaultPool().start(*this); - } - catch (...) - { - _running = false; - throw; - } - } - } - - void stop() - /// Requests to stop the activity. - { - FastMutex::ScopedLock lock(_mutex); - - _stopped = true; - } - - void wait() - /// Waits for the activity to complete. - { - if (_running) - { - _done.wait(); - } - } - - void wait(long milliseconds) - /// Waits the given interval for the activity to complete. - /// An TimeoutException is thrown if the activity does not - /// complete within the given interval. - { - if (_running) - { - _done.wait(milliseconds); - } - } - - bool isStopped() const - /// Returns true if the activity has been requested to stop. - { - return _stopped; - } - - bool isRunning() const - /// Returns true if the activity is running. - { - return _running; - } - -protected: - void run() - { - try - { - _runnable.run(); - } - catch (...) - { - _running = false; - _done.set(); - throw; - } - _running = false; - _done.set(); - } - -private: - Activity(); - Activity(const Activity&); - Activity& operator = (const Activity&); - - C* _pOwner; - RunnableAdapterType _runnable; - volatile bool _stopped; - volatile bool _running; - Event _done; - FastMutex _mutex; -}; - - -} // namespace Poco - - -#endif // Foundation_Activity_INCLUDED +// +// Activity.h +// +// $Id: //poco/1.2/Foundation/include/Poco/Activity.h#1 $ +// +// Library: Foundation +// Package: Threading +// Module: ActiveObjects +// +// Definition of the Activity template class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_Activity_INCLUDED +#define Foundation_Activity_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/RunnableAdapter.h" +#include "Poco/ThreadPool.h" +#include "Poco/Event.h" +#include "Poco/Mutex.h" + + +namespace Poco { + + +template +class Activity: public Runnable + /// This template class helps to implement active objects. + /// An active object uses threads to decouple method + /// execution from method invocation, or to perform tasks + /// autonomously, without intervention of a caller. + /// + /// An activity is a (typically longer running) method + /// that executes within its own task. Activities can + /// be started automatically (upon object construction) + /// or manually at a later time. Activities can also + /// be stopped at any time. However, to make stopping + /// an activity work, the method implementing the + /// activity has to check periodically whether it + /// has been requested to stop, and if so, return. + /// Activities are stopped before the object they belong to is + /// destroyed. Methods implementing activities cannot have arguments + /// or return values. + /// + /// Activity objects are used as follows: + /// + /// class ActiveObject + /// { + /// public: + /// ActiveObject(): + /// _activity(this, &ActiveObject::runActivity) + /// { + /// ... + /// } + /// + /// ... + /// + /// protected: + /// void runActivity() + /// { + /// while (!_activity.isStopped()) + /// { + /// ... + /// } + /// } + /// + /// private: + /// Activity _activity; + /// }; +{ +public: + typedef RunnableAdapter RunnableAdapterType; + typedef typename RunnableAdapterType::Callback Callback; + + Activity(C* pOwner, Callback method): + _pOwner(pOwner), + _runnable(*pOwner, method), + _stopped(true), + _running(false), + _done(false) + /// Creates the activity. Call start() to + /// start it. + { + poco_check_ptr (pOwner); + } + + ~Activity() + /// Stops and destroys the activity. + { + stop(); + wait(); + } + + void start() + /// Starts the activity by acquiring a + /// thread for it from the default thread pool. + { + FastMutex::ScopedLock lock(_mutex); + + if (_stopped) + { + _done.reset(); + _stopped = false; + _running = true; + try + { + ThreadPool::defaultPool().start(*this); + } + catch (...) + { + _running = false; + throw; + } + } + } + + void stop() + /// Requests to stop the activity. + { + FastMutex::ScopedLock lock(_mutex); + + _stopped = true; + } + + void wait() + /// Waits for the activity to complete. + { + if (_running) + { + _done.wait(); + } + } + + void wait(long milliseconds) + /// Waits the given interval for the activity to complete. + /// An TimeoutException is thrown if the activity does not + /// complete within the given interval. + { + if (_running) + { + _done.wait(milliseconds); + } + } + + bool isStopped() const + /// Returns true if the activity has been requested to stop. + { + return _stopped; + } + + bool isRunning() const + /// Returns true if the activity is running. + { + return _running; + } + +protected: + void run() + { + try + { + _runnable.run(); + } + catch (...) + { + _running = false; + _done.set(); + throw; + } + _running = false; + _done.set(); + } + +private: + Activity(); + Activity(const Activity&); + Activity& operator = (const Activity&); + + C* _pOwner; + RunnableAdapterType _runnable; + volatile bool _stopped; + volatile bool _running; + Event _done; + FastMutex _mutex; +}; + + +} // namespace Poco + + +#endif // Foundation_Activity_INCLUDED diff --git a/Foundation/include/Poco/Any.h b/Foundation/include/Poco/Any.h index 8cadf656c..04c01efc1 100644 --- a/Foundation/include/Poco/Any.h +++ b/Foundation/include/Poco/Any.h @@ -1,286 +1,286 @@ -// -// Any.h -// -// $Id: //poco/1.2/Foundation/include/Poco/Any.h#1 $ -// -// Library: Foundation -// Package: Core -// Module: Any -// -// Copyright Kevlin Henney, 2000, 2001, 2002. All rights reserved. -// Extracted from Boost 1.33.1 lib and adapted for poco: Peter Schojer/AppliedInformatics 2006-02-02 -// -// 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 Foundation_Any_INCLUDED -#define Foundation_Any_INCLUDED - - -#include "Poco/Exception.h" -#include -#include - - -namespace Poco { - - -class Any - /// An Any class represents a general type and is capable of storing any type, supporting type-safe extraction - /// of the internally stored data. - /// - /// Code taken from the Boost 1.33.1 library. Original copyright by Kevlin Henney. Modified for Poco - /// by Applied Informatics. -{ -public: - Any(): - _content(0) - /// Creates an empty any type. - { - } - - template - Any(const ValueType& value): - _content(new Holder(value)) - /// Creates an any which stores the init parameter inside. - /// - /// Example: - /// Any a(13); - /// Any a(string("12345")); - { - } - - Any(const Any& other): - _content(other._content ? other._content->clone() : 0) - /// Copy constructor, works with empty Anys and initialized Any values. - { - } - - ~Any() - { - delete _content; - } - - Any& swap(Any& rhs) - /// Swaps the content of the two Anys. - { - std::swap(_content, rhs._content); - return *this; - } - - template - Any& operator = (const ValueType& rhs) - /// Assignment operator for all types != Any. - /// - /// Example: - /// Any a = 13; - /// Any a = string("12345"); - { - Any(rhs).swap(*this); - return *this; - } - - Any& operator = (const Any& rhs) - /// Assignment operator for Any. - { - Any(rhs).swap(*this); - return *this; - } - - bool empty() const - /// returns true if the Any is empty - { - return !_content; - } - - const std::type_info& type() const - /// Returns the type information of the stored content. - /// If the Any is empty typeid(void) is returned. - /// It is suggested to always query an Any for its type info before trying to extract - /// data via an AnyCast/RefAnyCast. - { - return _content ? _content->type() : typeid(void); - } - -private: - class Placeholder - { - public: - virtual ~Placeholder() - { - } - - virtual const std::type_info& type() const = 0; - virtual Placeholder* clone() const = 0; - }; - - template - class Holder: public Placeholder - { - public: - Holder(const ValueType& value): - _held(value) - { - } - - virtual const std::type_info& type() const - { - return typeid(ValueType); - } - - virtual Placeholder* clone() const - { - return new Holder(_held); - } - - ValueType _held; - }; - -private: - template - friend ValueType* AnyCast(Any*); - - template - friend ValueType* UnsafeAnyCast(Any*); - - Placeholder* _content; -}; - - -template -ValueType* AnyCast(Any* operand) - /// AnyCast operator used to extract the ValueType from an Any*. Will return a pointer - /// to the stored value. - /// - /// Example Usage: - /// MyType* pTmp = AnyCast(pAny). - /// Will return NULL if the cast fails, i.e. types don't match. -{ - return operand && operand->type() == typeid(ValueType) - ? &static_cast*>(operand->_content)->_held - : 0; -} - - -template -const ValueType* AnyCast(const Any* operand) - /// AnyCast operator used to extract a const ValueType pointer from an const Any*. Will return a const pointer - /// to the stored value. - /// - /// Example Usage: - /// const MyType* pTmp = AnyCast(pAny). - /// Will return NULL if the cast fails, i.e. types don't match. -{ - return AnyCast(const_cast(operand)); -} - - -template -ValueType AnyCast(const Any& operand) - /// AnyCast operator used to extract a copy of the ValueType from an const Any&. - /// - /// Example Usage: - /// MyType tmp = AnyCast(anAny). - /// Will throw a BadCastException if the cast fails. - /// Dont use an AnyCast in combination with references, i.e. MyType& tmp = ... or const MyType& = ... - /// Some compilers will accept this code although a copy is returned. Use the RefAnyCast in - /// these cases. -{ - ValueType* result = AnyCast(const_cast(&operand)); - if (!result) throw BadCastException("Failed to convert between const Any types"); - return *result; -} - - -template -ValueType AnyCast(Any& operand) - /// AnyCast operator used to extract a copy of the ValueType from an Any&. - /// - /// Example Usage: - /// MyType tmp = AnyCast(anAny). - /// Will throw a BadCastException if the cast fails. - /// Dont use an AnyCast in combination with references, i.e. MyType& tmp = ... or const MyType& tmp = ... - /// Some compilers will accept this code although a copy is returned. Use the RefAnyCast in - /// these cases. -{ - ValueType* result = AnyCast(&operand); - if (!result) throw BadCastException("Failed to convert between Any types"); - return *result; -} - - -template -const ValueType& RefAnyCast(const Any & operand) - /// AnyCast operator used to return a const reference to the internal data. - /// - /// Example Usage: - /// const MyType& tmp = RefAnyCast(anAny); -{ - ValueType* result = AnyCast(const_cast(&operand)); - if (!result) throw BadCastException("RefAnyCast: Failed to convert between const Any types"); - return *result; -} - - -template -ValueType& RefAnyCast(Any& operand) - /// AnyCast operator used to return a reference to the internal data. - /// - /// Example Usage: - /// MyType& tmp = RefAnyCast(anAny); -{ - ValueType* result = AnyCast(&operand); - if (!result) throw BadCastException("RefAnyCast: Failed to convert between Any types"); - return *result; -} - - -template -ValueType* UnsafeAnyCast(Any* operand) - /// The "unsafe" versions of AnyCast are not part of the - /// public interface and may be removed at any time. They are - /// required where we know what type is stored in the any and can't - /// use typeid() comparison, e.g., when our types may travel across - /// different shared libraries. -{ - return &static_cast*>(operand->_content)->_held; -} - - -template -const ValueType* UnsafeAnyCast(const Any* operand) - /// The "unsafe" versions of AnyCast are not part of the - /// public interface and may be removed at any time. They are - /// required where we know what type is stored in the any and can't - /// use typeid() comparison, e.g., when our types may travel across - /// different shared libraries. -{ - return AnyCast(const_cast(operand)); -} - - -} // namespace Poco - - -#endif +// +// Any.h +// +// $Id: //poco/1.2/Foundation/include/Poco/Any.h#1 $ +// +// Library: Foundation +// Package: Core +// Module: Any +// +// Copyright Kevlin Henney, 2000, 2001, 2002. All rights reserved. +// Extracted from Boost 1.33.1 lib and adapted for poco: Peter Schojer/AppliedInformatics 2006-02-02 +// +// 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 Foundation_Any_INCLUDED +#define Foundation_Any_INCLUDED + + +#include "Poco/Exception.h" +#include +#include + + +namespace Poco { + + +class Any + /// An Any class represents a general type and is capable of storing any type, supporting type-safe extraction + /// of the internally stored data. + /// + /// Code taken from the Boost 1.33.1 library. Original copyright by Kevlin Henney. Modified for Poco + /// by Applied Informatics. +{ +public: + Any(): + _content(0) + /// Creates an empty any type. + { + } + + template + Any(const ValueType& value): + _content(new Holder(value)) + /// Creates an any which stores the init parameter inside. + /// + /// Example: + /// Any a(13); + /// Any a(string("12345")); + { + } + + Any(const Any& other): + _content(other._content ? other._content->clone() : 0) + /// Copy constructor, works with empty Anys and initialized Any values. + { + } + + ~Any() + { + delete _content; + } + + Any& swap(Any& rhs) + /// Swaps the content of the two Anys. + { + std::swap(_content, rhs._content); + return *this; + } + + template + Any& operator = (const ValueType& rhs) + /// Assignment operator for all types != Any. + /// + /// Example: + /// Any a = 13; + /// Any a = string("12345"); + { + Any(rhs).swap(*this); + return *this; + } + + Any& operator = (const Any& rhs) + /// Assignment operator for Any. + { + Any(rhs).swap(*this); + return *this; + } + + bool empty() const + /// returns true if the Any is empty + { + return !_content; + } + + const std::type_info& type() const + /// Returns the type information of the stored content. + /// If the Any is empty typeid(void) is returned. + /// It is suggested to always query an Any for its type info before trying to extract + /// data via an AnyCast/RefAnyCast. + { + return _content ? _content->type() : typeid(void); + } + +private: + class Placeholder + { + public: + virtual ~Placeholder() + { + } + + virtual const std::type_info& type() const = 0; + virtual Placeholder* clone() const = 0; + }; + + template + class Holder: public Placeholder + { + public: + Holder(const ValueType& value): + _held(value) + { + } + + virtual const std::type_info& type() const + { + return typeid(ValueType); + } + + virtual Placeholder* clone() const + { + return new Holder(_held); + } + + ValueType _held; + }; + +private: + template + friend ValueType* AnyCast(Any*); + + template + friend ValueType* UnsafeAnyCast(Any*); + + Placeholder* _content; +}; + + +template +ValueType* AnyCast(Any* operand) + /// AnyCast operator used to extract the ValueType from an Any*. Will return a pointer + /// to the stored value. + /// + /// Example Usage: + /// MyType* pTmp = AnyCast(pAny). + /// Will return NULL if the cast fails, i.e. types don't match. +{ + return operand && operand->type() == typeid(ValueType) + ? &static_cast*>(operand->_content)->_held + : 0; +} + + +template +const ValueType* AnyCast(const Any* operand) + /// AnyCast operator used to extract a const ValueType pointer from an const Any*. Will return a const pointer + /// to the stored value. + /// + /// Example Usage: + /// const MyType* pTmp = AnyCast(pAny). + /// Will return NULL if the cast fails, i.e. types don't match. +{ + return AnyCast(const_cast(operand)); +} + + +template +ValueType AnyCast(const Any& operand) + /// AnyCast operator used to extract a copy of the ValueType from an const Any&. + /// + /// Example Usage: + /// MyType tmp = AnyCast(anAny). + /// Will throw a BadCastException if the cast fails. + /// Dont use an AnyCast in combination with references, i.e. MyType& tmp = ... or const MyType& = ... + /// Some compilers will accept this code although a copy is returned. Use the RefAnyCast in + /// these cases. +{ + ValueType* result = AnyCast(const_cast(&operand)); + if (!result) throw BadCastException("Failed to convert between const Any types"); + return *result; +} + + +template +ValueType AnyCast(Any& operand) + /// AnyCast operator used to extract a copy of the ValueType from an Any&. + /// + /// Example Usage: + /// MyType tmp = AnyCast(anAny). + /// Will throw a BadCastException if the cast fails. + /// Dont use an AnyCast in combination with references, i.e. MyType& tmp = ... or const MyType& tmp = ... + /// Some compilers will accept this code although a copy is returned. Use the RefAnyCast in + /// these cases. +{ + ValueType* result = AnyCast(&operand); + if (!result) throw BadCastException("Failed to convert between Any types"); + return *result; +} + + +template +const ValueType& RefAnyCast(const Any & operand) + /// AnyCast operator used to return a const reference to the internal data. + /// + /// Example Usage: + /// const MyType& tmp = RefAnyCast(anAny); +{ + ValueType* result = AnyCast(const_cast(&operand)); + if (!result) throw BadCastException("RefAnyCast: Failed to convert between const Any types"); + return *result; +} + + +template +ValueType& RefAnyCast(Any& operand) + /// AnyCast operator used to return a reference to the internal data. + /// + /// Example Usage: + /// MyType& tmp = RefAnyCast(anAny); +{ + ValueType* result = AnyCast(&operand); + if (!result) throw BadCastException("RefAnyCast: Failed to convert between Any types"); + return *result; +} + + +template +ValueType* UnsafeAnyCast(Any* operand) + /// The "unsafe" versions of AnyCast are not part of the + /// public interface and may be removed at any time. They are + /// required where we know what type is stored in the any and can't + /// use typeid() comparison, e.g., when our types may travel across + /// different shared libraries. +{ + return &static_cast*>(operand->_content)->_held; +} + + +template +const ValueType* UnsafeAnyCast(const Any* operand) + /// The "unsafe" versions of AnyCast are not part of the + /// public interface and may be removed at any time. They are + /// required where we know what type is stored in the any and can't + /// use typeid() comparison, e.g., when our types may travel across + /// different shared libraries. +{ + return AnyCast(const_cast(operand)); +} + + +} // namespace Poco + + +#endif diff --git a/Foundation/include/Poco/ArchiveStrategy.h b/Foundation/include/Poco/ArchiveStrategy.h index 9c9702221..08a7edf07 100644 --- a/Foundation/include/Poco/ArchiveStrategy.h +++ b/Foundation/include/Poco/ArchiveStrategy.h @@ -1,129 +1,129 @@ -// -// ArchiveStrategy.h -// -// $Id: //poco/1.2/Foundation/include/Poco/ArchiveStrategy.h#1 $ -// -// Library: Foundation -// Package: Logging -// Module: FileChannel -// -// Definition of the ArchiveStrategy class and subclasses. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_ArchiveStrategy_INCLUDED -#define Foundation_ArchiveStrategy_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/LogFile.h" -#include "Poco/File.h" -#include "Poco/DateTimeFormatter.h" - - -namespace Poco { - - -class ArchiveCompressor; - - -class Foundation_API ArchiveStrategy - /// The ArchiveStrategy is used by FileChannel - /// to rename a rotated log file for archiving. - /// - /// Archived files can be automatically compressed, - /// using the gzip file format. -{ -public: - ArchiveStrategy(); - virtual ~ArchiveStrategy(); - - virtual LogFile* archive(LogFile* pFile) = 0; - /// Renames the given log file for archiving - /// and creates and returns a new log file. - /// The given LogFile object is deleted. - - void compress(bool flag = true); - /// Enables or disables compression of archived files. - -protected: - void moveFile(const std::string& oldName, const std::string& newName); - bool exists(const std::string& name); - -private: - ArchiveStrategy(const ArchiveStrategy&); - ArchiveStrategy& operator = (const ArchiveStrategy&); - - bool _compress; - ArchiveCompressor* _pCompressor; -}; - - -class Foundation_API ArchiveByNumberStrategy: public ArchiveStrategy - /// A monotonic increasing number is appended to the - /// log file name. The most recent archived file - /// always has the number zero. -{ -public: - ArchiveByNumberStrategy(); - ~ArchiveByNumberStrategy(); - LogFile* archive(LogFile* pFile); -}; - - -template -class ArchiveByTimestampStrategy: public ArchiveStrategy - /// A timestamp (YYYYMMDDhhmmss) is appended to archived - /// log files. -{ -public: - ArchiveByTimestampStrategy() - { - } - - ~ArchiveByTimestampStrategy() - { - } - - LogFile* archive(LogFile* pFile) - { - std::string path = pFile->path(); - delete pFile; - std::string archPath = path; - archPath.append("."); - archPath.append(DateTimeFormatter::format(DT().timestamp(), "%Y%m%d%H%M%S")); - moveFile(path, archPath); - return new LogFile(path); - } -}; - - -} // namespace Poco - - -#endif // Foundation_ArchiveStrategy_INCLUDED +// +// ArchiveStrategy.h +// +// $Id: //poco/1.2/Foundation/include/Poco/ArchiveStrategy.h#1 $ +// +// Library: Foundation +// Package: Logging +// Module: FileChannel +// +// Definition of the ArchiveStrategy class and subclasses. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_ArchiveStrategy_INCLUDED +#define Foundation_ArchiveStrategy_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/LogFile.h" +#include "Poco/File.h" +#include "Poco/DateTimeFormatter.h" + + +namespace Poco { + + +class ArchiveCompressor; + + +class Foundation_API ArchiveStrategy + /// The ArchiveStrategy is used by FileChannel + /// to rename a rotated log file for archiving. + /// + /// Archived files can be automatically compressed, + /// using the gzip file format. +{ +public: + ArchiveStrategy(); + virtual ~ArchiveStrategy(); + + virtual LogFile* archive(LogFile* pFile) = 0; + /// Renames the given log file for archiving + /// and creates and returns a new log file. + /// The given LogFile object is deleted. + + void compress(bool flag = true); + /// Enables or disables compression of archived files. + +protected: + void moveFile(const std::string& oldName, const std::string& newName); + bool exists(const std::string& name); + +private: + ArchiveStrategy(const ArchiveStrategy&); + ArchiveStrategy& operator = (const ArchiveStrategy&); + + bool _compress; + ArchiveCompressor* _pCompressor; +}; + + +class Foundation_API ArchiveByNumberStrategy: public ArchiveStrategy + /// A monotonic increasing number is appended to the + /// log file name. The most recent archived file + /// always has the number zero. +{ +public: + ArchiveByNumberStrategy(); + ~ArchiveByNumberStrategy(); + LogFile* archive(LogFile* pFile); +}; + + +template +class ArchiveByTimestampStrategy: public ArchiveStrategy + /// A timestamp (YYYYMMDDhhmmss) is appended to archived + /// log files. +{ +public: + ArchiveByTimestampStrategy() + { + } + + ~ArchiveByTimestampStrategy() + { + } + + LogFile* archive(LogFile* pFile) + { + std::string path = pFile->path(); + delete pFile; + std::string archPath = path; + archPath.append("."); + archPath.append(DateTimeFormatter::format(DT().timestamp(), "%Y%m%d%H%M%S")); + moveFile(path, archPath); + return new LogFile(path); + } +}; + + +} // namespace Poco + + +#endif // Foundation_ArchiveStrategy_INCLUDED diff --git a/Foundation/include/Poco/AsyncChannel.h b/Foundation/include/Poco/AsyncChannel.h index 240e092f2..1abb59afc 100644 --- a/Foundation/include/Poco/AsyncChannel.h +++ b/Foundation/include/Poco/AsyncChannel.h @@ -1,110 +1,110 @@ -// -// AsyncChannel.h -// -// $Id: //poco/1.2/Foundation/include/Poco/AsyncChannel.h#1 $ -// -// Library: Foundation -// Package: Logging -// Module: AsyncChannel -// -// Definition of the AsyncChannel class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_AsyncChannel_INCLUDED -#define Foundation_AsyncChannel_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/Channel.h" -#include "Poco/Thread.h" -#include "Poco/Mutex.h" -#include "Poco/Runnable.h" -#include "Poco/NotificationQueue.h" - - -namespace Poco { - - -class Foundation_API AsyncChannel: public Channel, public Runnable - /// A channel uses a separate thread for logging. - /// - /// Using this channel can help to improve the performance of - /// applications that produce huge amounts of log messages or - /// that write log messages to multiple channels simultaneously. - /// - /// All log messages are put into a queue and this queue is - /// then processed by a separate thread. -{ -public: - AsyncChannel(Channel* pChannel = 0); - /// Creates the AsyncChannel and connects it to - /// the given channel. - - void setChannel(Channel* pChannel); - /// Connects the AsyncChannel to the given target channel. - /// All messages will be forwarded to this channel. - - Channel* getChannel() const; - /// Returns the target channel. - - void open(); - /// Opens the channel and creates the - /// background ;ogging thread. - - void close(); - /// Closes the channel and stops the background - /// logging thread. - - void log(const Message& msg); - /// Queues the message for processing by the - /// background thread. - - void setProperty(const std::string& name, const std::string& value); - /// Sets or changes a configuration property. - /// - /// Only the "channel" property is supported, which allows - /// setting the target channel via the LoggingRegistry. - /// The "channel" property is set-only. - -protected: - ~AsyncChannel(); - void run(); - -private: - Channel* _pChannel; - Thread _thread; - FastMutex _mutex; - NotificationQueue _queue; -}; - - -} // namespace Poco - - -#endif // Foundation_AsyncChannel_INCLUDED +// +// AsyncChannel.h +// +// $Id: //poco/1.2/Foundation/include/Poco/AsyncChannel.h#1 $ +// +// Library: Foundation +// Package: Logging +// Module: AsyncChannel +// +// Definition of the AsyncChannel class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_AsyncChannel_INCLUDED +#define Foundation_AsyncChannel_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Channel.h" +#include "Poco/Thread.h" +#include "Poco/Mutex.h" +#include "Poco/Runnable.h" +#include "Poco/NotificationQueue.h" + + +namespace Poco { + + +class Foundation_API AsyncChannel: public Channel, public Runnable + /// A channel uses a separate thread for logging. + /// + /// Using this channel can help to improve the performance of + /// applications that produce huge amounts of log messages or + /// that write log messages to multiple channels simultaneously. + /// + /// All log messages are put into a queue and this queue is + /// then processed by a separate thread. +{ +public: + AsyncChannel(Channel* pChannel = 0); + /// Creates the AsyncChannel and connects it to + /// the given channel. + + void setChannel(Channel* pChannel); + /// Connects the AsyncChannel to the given target channel. + /// All messages will be forwarded to this channel. + + Channel* getChannel() const; + /// Returns the target channel. + + void open(); + /// Opens the channel and creates the + /// background ;ogging thread. + + void close(); + /// Closes the channel and stops the background + /// logging thread. + + void log(const Message& msg); + /// Queues the message for processing by the + /// background thread. + + void setProperty(const std::string& name, const std::string& value); + /// Sets or changes a configuration property. + /// + /// Only the "channel" property is supported, which allows + /// setting the target channel via the LoggingRegistry. + /// The "channel" property is set-only. + +protected: + ~AsyncChannel(); + void run(); + +private: + Channel* _pChannel; + Thread _thread; + FastMutex _mutex; + NotificationQueue _queue; +}; + + +} // namespace Poco + + +#endif // Foundation_AsyncChannel_INCLUDED diff --git a/Foundation/include/Poco/AutoPtr.h b/Foundation/include/Poco/AutoPtr.h index 797958cce..2c2e43296 100644 --- a/Foundation/include/Poco/AutoPtr.h +++ b/Foundation/include/Poco/AutoPtr.h @@ -1,336 +1,336 @@ -// -// AutoPtr.h -// -// $Id: //poco/1.2/Foundation/include/Poco/AutoPtr.h#2 $ -// -// Library: Foundation -// Package: Core -// Module: AutoPtr -// -// Definition of the AutoPtr template class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_AutoPtr_INCLUDED -#define Foundation_AutoPtr_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/Exception.h" -#include - - -namespace Poco { - - -template -class AutoPtr - /// AutoPtr is a "smart" pointer for classes implementing - /// reference counting based garbage collection. - /// To be usable with the AutoPtr template, a class must - /// implement the following behaviour: - /// A class must maintain a reference count. - /// The constructors of the object initialize the reference - /// count to one. - /// The class must implement a public duplicate() method: - /// void duplicate(); - /// that increments the reference count by one. - /// The class must implement a public release() method: - /// void release() - /// that decrements the reference count by one, and, - /// if the reference count reaches zero, deletes the - /// object. - /// - /// AutoPtr works in the following way: - /// If an AutoPtr is assigned an ordinary pointer to - /// an object (via the constructor or the assignment operator), - /// it takes ownership of the object and the object's reference - /// count remains unchanged. - /// If the AutoPtr is assigned another AutoPtr, the - /// object's reference count is incremented by one by - /// calling duplicate() on its object. - /// The destructor of AutoPtr calls release() on its - /// object. - /// AutoPtr supports dereferencing with both the -> - /// and the * operator. An attempt to dereference a null - /// AutoPtr results in a NullPointerException being thrown. - /// AutoPtr also implements all relational operators. - /// Note that AutoPtr allows casting of its encapsulated data types. -{ -public: - AutoPtr(): _ptr(0) - { - } - - AutoPtr(C* ptr): _ptr(ptr) - { - } - - AutoPtr(C* ptr, bool shared): _ptr(ptr) - { - if (shared && _ptr) _ptr->duplicate(); - } - - AutoPtr(const AutoPtr& ptr): _ptr(ptr._ptr) - { - if (_ptr) _ptr->duplicate(); - } - - template - AutoPtr(const AutoPtr& ptr): _ptr(const_cast(ptr.get())) - { - if (_ptr) _ptr->duplicate(); - } - - ~AutoPtr() - { - if (_ptr) _ptr->release(); - } - - AutoPtr& operator = (C* ptr) - { - if (_ptr != ptr) - { - if (_ptr) _ptr->release(); - _ptr = ptr; - } - return *this; - } - - AutoPtr& operator = (const AutoPtr& ptr) - { - if (&ptr != this) - { - if (_ptr) _ptr->release(); - _ptr = ptr._ptr; - if (_ptr) _ptr->duplicate(); - } - return *this; - } - - void swap(AutoPtr& ptr) - { - std::swap(_ptr, ptr._ptr); - } - - template - AutoPtr& operator = (const AutoPtr& ptr) - { - if (ptr.get() != _ptr) - { - if (_ptr) _ptr->release(); - _ptr = const_cast(ptr.get()); - if (_ptr) _ptr->duplicate(); - } - return *this; - } - - template - AutoPtr cast() - /// Casts the AutoPtr via a dynamic cast to the given type. - /// Returns an AutoPtr containing NULL if the cast fails. - /// Example: (assume class Sub: public Super) - /// AutoPtr super(new Sub()); - /// AutoPtr sub = super.cast(); - /// poco_assert (sub.get()); - { - Other* pOther = dynamic_cast (_ptr); - if (pOther) - pOther->duplicate(); - return AutoPtr(pOther); - } - - C* operator -> () - { - if (_ptr) - return _ptr; - else - throw NullPointerException(); - } - - const C* operator -> () const - { - if (_ptr) - return _ptr; - else - throw NullPointerException(); - } - - C& operator * () - { - if (_ptr) - return *_ptr; - else - throw NullPointerException(); - } - - const C& operator * () const - { - if (_ptr) - return *_ptr; - else - throw NullPointerException(); - } - - C* get() - { - return _ptr; - } - - bool isNull() const - { - return _ptr == 0; - } - - operator C* () - { - return _ptr; - } - - operator const C* () const - { - return _ptr; - } - - const C* get() const - { - return _ptr; - } - - C* duplicate() - { - if (_ptr) _ptr->duplicate(); - return _ptr; - } - - bool operator == (const AutoPtr& ptr) const - { - return _ptr == ptr._ptr; - } - - bool operator == (const C* ptr) const - { - return _ptr == ptr; - } - - bool operator == (C* ptr) const - { - return _ptr == ptr; - } - - bool operator != (const AutoPtr& ptr) const - { - return _ptr != ptr._ptr; - } - - bool operator != (const C* ptr) const - { - return _ptr != ptr; - } - - bool operator != (C* ptr) const - { - return _ptr != ptr; - } - - bool operator < (const AutoPtr& ptr) const - { - return _ptr < ptr._ptr; - } - - bool operator < (const C* ptr) const - { - return _ptr < ptr; - } - - bool operator < (C* ptr) const - { - return _ptr < ptr; - } - - bool operator <= (const AutoPtr& ptr) const - { - return _ptr <= ptr._ptr; - } - - bool operator <= (const C* ptr) const - { - return _ptr <= ptr; - } - - bool operator <= (C* ptr) const - { - return _ptr <= ptr; - } - - bool operator > (const AutoPtr& ptr) const - { - return _ptr > ptr._ptr; - } - - bool operator > (const C* ptr) const - { - return _ptr > ptr; - } - - bool operator > (C* ptr) const - { - return _ptr > ptr; - } - - bool operator >= (const AutoPtr& ptr) const - { - return _ptr >= ptr._ptr; - } - - bool operator >= (const C* ptr) const - { - return _ptr >= ptr; - } - - bool operator >= (C* ptr) const - { - return _ptr >= ptr; - } - -private: - C* _ptr; -}; - - -template -inline void swap(AutoPtr& p1, AutoPtr& p2) -{ - p1.swap(p2); -} - - -} // namespace Poco - - -#endif // Foundation_AutoPtr_INCLUDED +// +// AutoPtr.h +// +// $Id: //poco/1.2/Foundation/include/Poco/AutoPtr.h#2 $ +// +// Library: Foundation +// Package: Core +// Module: AutoPtr +// +// Definition of the AutoPtr template class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_AutoPtr_INCLUDED +#define Foundation_AutoPtr_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Exception.h" +#include + + +namespace Poco { + + +template +class AutoPtr + /// AutoPtr is a "smart" pointer for classes implementing + /// reference counting based garbage collection. + /// To be usable with the AutoPtr template, a class must + /// implement the following behaviour: + /// A class must maintain a reference count. + /// The constructors of the object initialize the reference + /// count to one. + /// The class must implement a public duplicate() method: + /// void duplicate(); + /// that increments the reference count by one. + /// The class must implement a public release() method: + /// void release() + /// that decrements the reference count by one, and, + /// if the reference count reaches zero, deletes the + /// object. + /// + /// AutoPtr works in the following way: + /// If an AutoPtr is assigned an ordinary pointer to + /// an object (via the constructor or the assignment operator), + /// it takes ownership of the object and the object's reference + /// count remains unchanged. + /// If the AutoPtr is assigned another AutoPtr, the + /// object's reference count is incremented by one by + /// calling duplicate() on its object. + /// The destructor of AutoPtr calls release() on its + /// object. + /// AutoPtr supports dereferencing with both the -> + /// and the * operator. An attempt to dereference a null + /// AutoPtr results in a NullPointerException being thrown. + /// AutoPtr also implements all relational operators. + /// Note that AutoPtr allows casting of its encapsulated data types. +{ +public: + AutoPtr(): _ptr(0) + { + } + + AutoPtr(C* ptr): _ptr(ptr) + { + } + + AutoPtr(C* ptr, bool shared): _ptr(ptr) + { + if (shared && _ptr) _ptr->duplicate(); + } + + AutoPtr(const AutoPtr& ptr): _ptr(ptr._ptr) + { + if (_ptr) _ptr->duplicate(); + } + + template + AutoPtr(const AutoPtr& ptr): _ptr(const_cast(ptr.get())) + { + if (_ptr) _ptr->duplicate(); + } + + ~AutoPtr() + { + if (_ptr) _ptr->release(); + } + + AutoPtr& operator = (C* ptr) + { + if (_ptr != ptr) + { + if (_ptr) _ptr->release(); + _ptr = ptr; + } + return *this; + } + + AutoPtr& operator = (const AutoPtr& ptr) + { + if (&ptr != this) + { + if (_ptr) _ptr->release(); + _ptr = ptr._ptr; + if (_ptr) _ptr->duplicate(); + } + return *this; + } + + void swap(AutoPtr& ptr) + { + std::swap(_ptr, ptr._ptr); + } + + template + AutoPtr& operator = (const AutoPtr& ptr) + { + if (ptr.get() != _ptr) + { + if (_ptr) _ptr->release(); + _ptr = const_cast(ptr.get()); + if (_ptr) _ptr->duplicate(); + } + return *this; + } + + template + AutoPtr cast() + /// Casts the AutoPtr via a dynamic cast to the given type. + /// Returns an AutoPtr containing NULL if the cast fails. + /// Example: (assume class Sub: public Super) + /// AutoPtr super(new Sub()); + /// AutoPtr sub = super.cast(); + /// poco_assert (sub.get()); + { + Other* pOther = dynamic_cast (_ptr); + if (pOther) + pOther->duplicate(); + return AutoPtr(pOther); + } + + C* operator -> () + { + if (_ptr) + return _ptr; + else + throw NullPointerException(); + } + + const C* operator -> () const + { + if (_ptr) + return _ptr; + else + throw NullPointerException(); + } + + C& operator * () + { + if (_ptr) + return *_ptr; + else + throw NullPointerException(); + } + + const C& operator * () const + { + if (_ptr) + return *_ptr; + else + throw NullPointerException(); + } + + C* get() + { + return _ptr; + } + + bool isNull() const + { + return _ptr == 0; + } + + operator C* () + { + return _ptr; + } + + operator const C* () const + { + return _ptr; + } + + const C* get() const + { + return _ptr; + } + + C* duplicate() + { + if (_ptr) _ptr->duplicate(); + return _ptr; + } + + bool operator == (const AutoPtr& ptr) const + { + return _ptr == ptr._ptr; + } + + bool operator == (const C* ptr) const + { + return _ptr == ptr; + } + + bool operator == (C* ptr) const + { + return _ptr == ptr; + } + + bool operator != (const AutoPtr& ptr) const + { + return _ptr != ptr._ptr; + } + + bool operator != (const C* ptr) const + { + return _ptr != ptr; + } + + bool operator != (C* ptr) const + { + return _ptr != ptr; + } + + bool operator < (const AutoPtr& ptr) const + { + return _ptr < ptr._ptr; + } + + bool operator < (const C* ptr) const + { + return _ptr < ptr; + } + + bool operator < (C* ptr) const + { + return _ptr < ptr; + } + + bool operator <= (const AutoPtr& ptr) const + { + return _ptr <= ptr._ptr; + } + + bool operator <= (const C* ptr) const + { + return _ptr <= ptr; + } + + bool operator <= (C* ptr) const + { + return _ptr <= ptr; + } + + bool operator > (const AutoPtr& ptr) const + { + return _ptr > ptr._ptr; + } + + bool operator > (const C* ptr) const + { + return _ptr > ptr; + } + + bool operator > (C* ptr) const + { + return _ptr > ptr; + } + + bool operator >= (const AutoPtr& ptr) const + { + return _ptr >= ptr._ptr; + } + + bool operator >= (const C* ptr) const + { + return _ptr >= ptr; + } + + bool operator >= (C* ptr) const + { + return _ptr >= ptr; + } + +private: + C* _ptr; +}; + + +template +inline void swap(AutoPtr& p1, AutoPtr& p2) +{ + p1.swap(p2); +} + + +} // namespace Poco + + +#endif // Foundation_AutoPtr_INCLUDED diff --git a/Foundation/include/Poco/AutoReleasePool.h b/Foundation/include/Poco/AutoReleasePool.h index 11670b75c..95a5fb8da 100644 --- a/Foundation/include/Poco/AutoReleasePool.h +++ b/Foundation/include/Poco/AutoReleasePool.h @@ -1,108 +1,108 @@ -// -// AutoReleasePool.h -// -// $Id: //poco/1.2/Foundation/include/Poco/AutoReleasePool.h#1 $ -// -// Library: Foundation -// Package: Core -// Module: AutoReleasePool -// -// Definition of the AutoReleasePool class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_AutoReleasePool_INCLUDED -#define Foundation_AutoReleasePool_INCLUDED - - -#include "Poco/Foundation.h" -#include - - -namespace Poco { - - -template -class AutoReleasePool - /// An AutoReleasePool implements simple garbage collection for - /// reference-counted objects. - /// It temporarily takes ownwership of reference-counted objects that - /// nobody else wants to take ownership of and releases them - /// at a later, appropriate point in time. - /// - /// Note: The correct way to add an object hold by an AutoPtr<> to - /// an AutoReleasePool is by invoking the AutoPtr's duplicate() - /// method. Example: - /// AutoReleasePool arp; - /// AutoPtr ptr = new C; - /// ... - /// arp.add(ptr.duplicate()); -{ -public: - AutoReleasePool() - /// Creates the AutoReleasePool. - { - } - - ~AutoReleasePool() - /// Destroys the AutoReleasePool and releases - /// all objects it currently holds. - { - release(); - } - - void add(C* pObject) - /// Adds the given object to the AutoReleasePool. - /// The object's reference count is not modified - { - if (pObject) - _list.push_back(pObject); - } - - void release() - /// Releases all objects the AutoReleasePool currently holds - /// by calling each object's release() method. - { - while (!_list.empty()) - { - _list.front()->release(); - _list.pop_front(); - } - } - -private: - typedef std::list ObjectList; - - ObjectList _list; -}; - - -} // namespace Poco - - -#endif // Foundation_AutoReleasePool_INCLUDED +// +// AutoReleasePool.h +// +// $Id: //poco/1.2/Foundation/include/Poco/AutoReleasePool.h#1 $ +// +// Library: Foundation +// Package: Core +// Module: AutoReleasePool +// +// Definition of the AutoReleasePool class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_AutoReleasePool_INCLUDED +#define Foundation_AutoReleasePool_INCLUDED + + +#include "Poco/Foundation.h" +#include + + +namespace Poco { + + +template +class AutoReleasePool + /// An AutoReleasePool implements simple garbage collection for + /// reference-counted objects. + /// It temporarily takes ownwership of reference-counted objects that + /// nobody else wants to take ownership of and releases them + /// at a later, appropriate point in time. + /// + /// Note: The correct way to add an object hold by an AutoPtr<> to + /// an AutoReleasePool is by invoking the AutoPtr's duplicate() + /// method. Example: + /// AutoReleasePool arp; + /// AutoPtr ptr = new C; + /// ... + /// arp.add(ptr.duplicate()); +{ +public: + AutoReleasePool() + /// Creates the AutoReleasePool. + { + } + + ~AutoReleasePool() + /// Destroys the AutoReleasePool and releases + /// all objects it currently holds. + { + release(); + } + + void add(C* pObject) + /// Adds the given object to the AutoReleasePool. + /// The object's reference count is not modified + { + if (pObject) + _list.push_back(pObject); + } + + void release() + /// Releases all objects the AutoReleasePool currently holds + /// by calling each object's release() method. + { + while (!_list.empty()) + { + _list.front()->release(); + _list.pop_front(); + } + } + +private: + typedef std::list ObjectList; + + ObjectList _list; +}; + + +} // namespace Poco + + +#endif // Foundation_AutoReleasePool_INCLUDED diff --git a/Foundation/include/Poco/Base64Decoder.h b/Foundation/include/Poco/Base64Decoder.h index dc4051d59..89ebb4e02 100644 --- a/Foundation/include/Poco/Base64Decoder.h +++ b/Foundation/include/Poco/Base64Decoder.h @@ -1,102 +1,102 @@ -// -// Base64Decoder.h -// -// $Id: //poco/1.2/Foundation/include/Poco/Base64Decoder.h#1 $ -// -// Library: Foundation -// Package: Streams -// Module: Base64 -// -// Definition of class Base64Decoder. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_Base64Decoder_INCLUDED -#define Foundation_Base64Decoder_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/UnbufferedStreamBuf.h" -#include - - -namespace Poco { - - -class Foundation_API Base64DecoderBuf: public UnbufferedStreamBuf - /// This streambuf base64-decodes all data read - /// from the istream connected to it. -{ -public: - Base64DecoderBuf(std::istream& istr); - ~Base64DecoderBuf(); - -private: - int readFromDevice(); - int readOne(); - - unsigned char _group[3]; - int _groupLength; - int _groupIndex; - std::istream& _istr; - - static unsigned char IN_ENCODING[256]; - static bool IN_ENCODING_INIT; -}; - - -class Foundation_API Base64DecoderIOS: public virtual std::ios - /// The base class for Base64Decoder. - /// - /// This class is needed to ensure the correct initialization - /// order of the stream buffer and base classes. -{ -public: - Base64DecoderIOS(std::istream& istr); - ~Base64DecoderIOS(); - Base64DecoderBuf* rdbuf(); - -protected: - Base64DecoderBuf _buf; -}; - - -class Foundation_API Base64Decoder: public Base64DecoderIOS, public std::istream - /// This istream base64-decodes all data - /// read from the istream connected to it. -{ -public: - Base64Decoder(std::istream& istr); - ~Base64Decoder(); -}; - - -} // namespace Poco - - -#endif // Foundation_Base64Decoder_INCLUDED +// +// Base64Decoder.h +// +// $Id: //poco/1.2/Foundation/include/Poco/Base64Decoder.h#1 $ +// +// Library: Foundation +// Package: Streams +// Module: Base64 +// +// Definition of class Base64Decoder. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_Base64Decoder_INCLUDED +#define Foundation_Base64Decoder_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/UnbufferedStreamBuf.h" +#include + + +namespace Poco { + + +class Foundation_API Base64DecoderBuf: public UnbufferedStreamBuf + /// This streambuf base64-decodes all data read + /// from the istream connected to it. +{ +public: + Base64DecoderBuf(std::istream& istr); + ~Base64DecoderBuf(); + +private: + int readFromDevice(); + int readOne(); + + unsigned char _group[3]; + int _groupLength; + int _groupIndex; + std::istream& _istr; + + static unsigned char IN_ENCODING[256]; + static bool IN_ENCODING_INIT; +}; + + +class Foundation_API Base64DecoderIOS: public virtual std::ios + /// The base class for Base64Decoder. + /// + /// This class is needed to ensure the correct initialization + /// order of the stream buffer and base classes. +{ +public: + Base64DecoderIOS(std::istream& istr); + ~Base64DecoderIOS(); + Base64DecoderBuf* rdbuf(); + +protected: + Base64DecoderBuf _buf; +}; + + +class Foundation_API Base64Decoder: public Base64DecoderIOS, public std::istream + /// This istream base64-decodes all data + /// read from the istream connected to it. +{ +public: + Base64Decoder(std::istream& istr); + ~Base64Decoder(); +}; + + +} // namespace Poco + + +#endif // Foundation_Base64Decoder_INCLUDED diff --git a/Foundation/include/Poco/Base64Encoder.h b/Foundation/include/Poco/Base64Encoder.h index 69f5c0113..14f9d9270 100644 --- a/Foundation/include/Poco/Base64Encoder.h +++ b/Foundation/include/Poco/Base64Encoder.h @@ -1,112 +1,112 @@ -// -// Base64Encoder.h -// -// $Id: //poco/1.2/Foundation/include/Poco/Base64Encoder.h#1 $ -// -// Library: Foundation -// Package: Streams -// Module: Base64 -// -// Definition of class Base64Encoder. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_Base64Encoder_INCLUDED -#define Foundation_Base64Encoder_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/UnbufferedStreamBuf.h" -#include - - -namespace Poco { - - -class Foundation_API Base64EncoderBuf: public UnbufferedStreamBuf - /// This streambuf base64-encodes all data written - /// to it and forwards it to a connected - /// ostream. -{ -public: - Base64EncoderBuf(std::ostream& ostr); - ~Base64EncoderBuf(); - int close(); - void setLineLength(int lineLength); - int getLineLength() const; - -private: - int writeToDevice(char c); - - unsigned char _group[3]; - int _groupLength; - int _pos; - int _lineLength; - std::ostream& _ostr; - - static const unsigned char OUT_ENCODING[64]; - - friend class Base64DecoderBuf; -}; - - -class Foundation_API Base64EncoderIOS: public virtual std::ios - /// The base class for Base64Encoder. - /// - /// This class is needed to ensure the correct initialization - /// order of the stream buffer and base classes. -{ -public: - Base64EncoderIOS(std::ostream& ostr); - ~Base64EncoderIOS(); - int close(); - Base64EncoderBuf* rdbuf(); - -protected: - Base64EncoderBuf _buf; -}; - - -class Foundation_API Base64Encoder: public Base64EncoderIOS, public std::ostream - /// This ostream base64-encodes all data - /// written to it and forwards it to - /// a connected ostream. - /// Always call close() when done - /// writing data, to ensure proper - /// completion of the encoding operation. -{ -public: - Base64Encoder(std::ostream& ostr); - ~Base64Encoder(); -}; - - -} // namespace Poco - - -#endif // Foundation_Base64Encoder_INCLUDED +// +// Base64Encoder.h +// +// $Id: //poco/1.2/Foundation/include/Poco/Base64Encoder.h#1 $ +// +// Library: Foundation +// Package: Streams +// Module: Base64 +// +// Definition of class Base64Encoder. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_Base64Encoder_INCLUDED +#define Foundation_Base64Encoder_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/UnbufferedStreamBuf.h" +#include + + +namespace Poco { + + +class Foundation_API Base64EncoderBuf: public UnbufferedStreamBuf + /// This streambuf base64-encodes all data written + /// to it and forwards it to a connected + /// ostream. +{ +public: + Base64EncoderBuf(std::ostream& ostr); + ~Base64EncoderBuf(); + int close(); + void setLineLength(int lineLength); + int getLineLength() const; + +private: + int writeToDevice(char c); + + unsigned char _group[3]; + int _groupLength; + int _pos; + int _lineLength; + std::ostream& _ostr; + + static const unsigned char OUT_ENCODING[64]; + + friend class Base64DecoderBuf; +}; + + +class Foundation_API Base64EncoderIOS: public virtual std::ios + /// The base class for Base64Encoder. + /// + /// This class is needed to ensure the correct initialization + /// order of the stream buffer and base classes. +{ +public: + Base64EncoderIOS(std::ostream& ostr); + ~Base64EncoderIOS(); + int close(); + Base64EncoderBuf* rdbuf(); + +protected: + Base64EncoderBuf _buf; +}; + + +class Foundation_API Base64Encoder: public Base64EncoderIOS, public std::ostream + /// This ostream base64-encodes all data + /// written to it and forwards it to + /// a connected ostream. + /// Always call close() when done + /// writing data, to ensure proper + /// completion of the encoding operation. +{ +public: + Base64Encoder(std::ostream& ostr); + ~Base64Encoder(); +}; + + +} // namespace Poco + + +#endif // Foundation_Base64Encoder_INCLUDED diff --git a/Foundation/include/Poco/BasicEvent.h b/Foundation/include/Poco/BasicEvent.h index 2773d559c..5033aa5c7 100644 --- a/Foundation/include/Poco/BasicEvent.h +++ b/Foundation/include/Poco/BasicEvent.h @@ -1,88 +1,88 @@ -// -// BasicEvent.h -// -// $Id: //poco/1.2/Foundation/include/Poco/BasicEvent.h#1 $ -// -// Library: Foundation -// Package: Events -// Module: BasicEvent -// -// Implementation of the BasicEvent template. -// -// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_BasicEvent_INCLUDED -#define Foundation_BasicEvent_INCLUDED - - -#include "Poco/AbstractEvent.h" -#include "Poco/DefaultStrategy.h" -#include "Poco/AbstractDelegate.h" -#include "Poco/CompareFunctions.h" - - -namespace Poco { - - -template -class BasicEvent: public AbstractEvent < - TArgs, DefaultStrategy, p_less > >, - AbstractDelegate -> - /// A BasicEvent uses internally a DefaultStrategy which - /// invokes delegates in an arbitrary manner. - /// Note that one object can only register one method to a BasicEvent. - /// Subsequent registrations will overwrite the existing delegate. - /// For example: - /// BasicEvent event; - /// MyClass myObject; - /// event += Delegate(&myObject, &MyClass::myMethod1); - /// event += Delegate(&myObject, &MyClass::myMethod2); - /// - /// The second registration will overwrite the first one. The reason is simply that - /// function pointers can only be compared by equality but not by lower than. -{ -public: - BasicEvent() - { - } - - ~BasicEvent() - { - } - -private: - BasicEvent(const BasicEvent& e); - BasicEvent& operator = (const BasicEvent& e); -}; - - -} // namespace Poco - - -#endif +// +// BasicEvent.h +// +// $Id: //poco/1.2/Foundation/include/Poco/BasicEvent.h#1 $ +// +// Library: Foundation +// Package: Events +// Module: BasicEvent +// +// Implementation of the BasicEvent template. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_BasicEvent_INCLUDED +#define Foundation_BasicEvent_INCLUDED + + +#include "Poco/AbstractEvent.h" +#include "Poco/DefaultStrategy.h" +#include "Poco/AbstractDelegate.h" +#include "Poco/CompareFunctions.h" + + +namespace Poco { + + +template +class BasicEvent: public AbstractEvent < + TArgs, DefaultStrategy, p_less > >, + AbstractDelegate +> + /// A BasicEvent uses internally a DefaultStrategy which + /// invokes delegates in an arbitrary manner. + /// Note that one object can only register one method to a BasicEvent. + /// Subsequent registrations will overwrite the existing delegate. + /// For example: + /// BasicEvent event; + /// MyClass myObject; + /// event += Delegate(&myObject, &MyClass::myMethod1); + /// event += Delegate(&myObject, &MyClass::myMethod2); + /// + /// The second registration will overwrite the first one. The reason is simply that + /// function pointers can only be compared by equality but not by lower than. +{ +public: + BasicEvent() + { + } + + ~BasicEvent() + { + } + +private: + BasicEvent(const BasicEvent& e); + BasicEvent& operator = (const BasicEvent& e); +}; + + +} // namespace Poco + + +#endif diff --git a/Foundation/include/Poco/BinaryReader.h b/Foundation/include/Poco/BinaryReader.h index cff5aac82..8119e2736 100644 --- a/Foundation/include/Poco/BinaryReader.h +++ b/Foundation/include/Poco/BinaryReader.h @@ -1,187 +1,187 @@ -// -// BinaryReader.h -// -// $Id: //poco/1.2/Foundation/include/Poco/BinaryReader.h#1 $ -// -// Library: Foundation -// Package: Streams -// Module: BinaryReaderWriter -// -// Definition of the BinaryReader class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_BinaryReader_INCLUDED -#define Foundation_BinaryReader_INCLUDED - - -#include "Poco/Foundation.h" -#include - - -namespace Poco { - - -class Foundation_API BinaryReader - /// This class reads basic types in binary form into an input stream. - /// It provides an extractor-based interface similar to istream. - /// The reader also supports automatic conversion from big-endian - /// (network byte order) to little-endian and vice-versa. - /// Use a BinaryWriter to create a stream suitable for a BinaryReader. -{ -public: - enum StreamByteOrder - { - NATIVE_BYTE_ORDER = 1, /// the host's native byte-order - BIG_ENDIAN_BYTE_ORDER = 2, /// big-endian (network) byte-order - NETWORK_BYTE_ORDER = 2, /// big-endian (network) byte-order - LITTLE_ENDIAN_BYTE_ORDER = 3, /// little-endian byte-order - UNSPECIFIED_BYTE_ORDER = 4 /// unknown, byte-order will be determined by reading the byte-order mark - }; - - BinaryReader(std::istream& istr, StreamByteOrder byteOrder = NATIVE_BYTE_ORDER); - /// Creates the BinaryReader. - - ~BinaryReader(); - /// Destroys the BinaryReader. - - BinaryReader& operator >> (bool& value); - BinaryReader& operator >> (char& value); - BinaryReader& operator >> (unsigned char& value); - BinaryReader& operator >> (signed char& value); - BinaryReader& operator >> (short& value); - BinaryReader& operator >> (unsigned short& value); - BinaryReader& operator >> (int& value); - BinaryReader& operator >> (unsigned int& value); - BinaryReader& operator >> (long& value); - BinaryReader& operator >> (unsigned long& value); - BinaryReader& operator >> (float& value); - BinaryReader& operator >> (double& value); - -#if defined(POCO_HAVE_INT64) && !defined(POCO_LONG_IS_64_BIT) - BinaryReader& operator >> (Int64& value); - BinaryReader& operator >> (UInt64& value); -#endif - - BinaryReader& operator >> (std::string& value); - - void read7BitEncoded(UInt32& value); - /// Reads a 32-bit unsigned integer in compressed format. - /// See BinaryWriter::write7BitEncoded() for a description - /// of the compression algorithm. - -#if defined(POCO_HAVE_INT64) - void read7BitEncoded(UInt64& value); - /// Reads a 64-bit unsigned integer in compressed format. - /// See BinaryWriter::write7BitEncoded() for a description - /// of the compression algorithm. -#endif - - void readRaw(int length, std::string& value); - /// Reads length bytes of raw data into value. - - void readBOM(); - /// Reads a byte-order mark from the stream and configures - /// the reader for the encountered byte order. - /// A byte-order mark is a 16-bit integer with a value of 0xFEFF, - /// written in host byte order. - - bool good(); - /// Returns _istr.good(); - - bool fail(); - /// Returns _istr.fail(); - - bool bad(); - /// Returns _istr.bad(); - - bool eof(); - /// Returns _istr.eof(); - - std::istream& stream() const; - /// Returns the underlying stream. - - StreamByteOrder byteOrder() const; - /// Returns the byte-order used by the reader, which is - /// either BIG_ENDIAN_BYTE_ORDER or LITTLE_ENDIAN_BYTE_ORDER. - -private: - std::istream& _istr; - bool _flipBytes; -}; - - -// -// inlines -// - - -inline bool BinaryReader::good() -{ - return _istr.good(); -} - - -inline bool BinaryReader::fail() -{ - return _istr.fail(); -} - - -inline bool BinaryReader::bad() -{ - return _istr.bad(); -} - - -inline bool BinaryReader::eof() -{ - return _istr.eof(); -} - - -inline std::istream& BinaryReader::stream() const -{ - return _istr; -} - - -inline BinaryReader::StreamByteOrder BinaryReader::byteOrder() const -{ -#if defined(POCO_ARCH_BIG_ENDIAN) - return _flipBytes ? LITTLE_ENDIAN_BYTE_ORDER : BIG_ENDIAN_BYTE_ORDER; -#else - return _flipBytes ? BIG_ENDIAN_BYTE_ORDER : LITTLE_ENDIAN_BYTE_ORDER; -#endif -} - - -} // namespace Poco - - -#endif // Foundation_BinaryReader_INCLUDED +// +// BinaryReader.h +// +// $Id: //poco/1.2/Foundation/include/Poco/BinaryReader.h#1 $ +// +// Library: Foundation +// Package: Streams +// Module: BinaryReaderWriter +// +// Definition of the BinaryReader class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_BinaryReader_INCLUDED +#define Foundation_BinaryReader_INCLUDED + + +#include "Poco/Foundation.h" +#include + + +namespace Poco { + + +class Foundation_API BinaryReader + /// This class reads basic types in binary form into an input stream. + /// It provides an extractor-based interface similar to istream. + /// The reader also supports automatic conversion from big-endian + /// (network byte order) to little-endian and vice-versa. + /// Use a BinaryWriter to create a stream suitable for a BinaryReader. +{ +public: + enum StreamByteOrder + { + NATIVE_BYTE_ORDER = 1, /// the host's native byte-order + BIG_ENDIAN_BYTE_ORDER = 2, /// big-endian (network) byte-order + NETWORK_BYTE_ORDER = 2, /// big-endian (network) byte-order + LITTLE_ENDIAN_BYTE_ORDER = 3, /// little-endian byte-order + UNSPECIFIED_BYTE_ORDER = 4 /// unknown, byte-order will be determined by reading the byte-order mark + }; + + BinaryReader(std::istream& istr, StreamByteOrder byteOrder = NATIVE_BYTE_ORDER); + /// Creates the BinaryReader. + + ~BinaryReader(); + /// Destroys the BinaryReader. + + BinaryReader& operator >> (bool& value); + BinaryReader& operator >> (char& value); + BinaryReader& operator >> (unsigned char& value); + BinaryReader& operator >> (signed char& value); + BinaryReader& operator >> (short& value); + BinaryReader& operator >> (unsigned short& value); + BinaryReader& operator >> (int& value); + BinaryReader& operator >> (unsigned int& value); + BinaryReader& operator >> (long& value); + BinaryReader& operator >> (unsigned long& value); + BinaryReader& operator >> (float& value); + BinaryReader& operator >> (double& value); + +#if defined(POCO_HAVE_INT64) && !defined(POCO_LONG_IS_64_BIT) + BinaryReader& operator >> (Int64& value); + BinaryReader& operator >> (UInt64& value); +#endif + + BinaryReader& operator >> (std::string& value); + + void read7BitEncoded(UInt32& value); + /// Reads a 32-bit unsigned integer in compressed format. + /// See BinaryWriter::write7BitEncoded() for a description + /// of the compression algorithm. + +#if defined(POCO_HAVE_INT64) + void read7BitEncoded(UInt64& value); + /// Reads a 64-bit unsigned integer in compressed format. + /// See BinaryWriter::write7BitEncoded() for a description + /// of the compression algorithm. +#endif + + void readRaw(int length, std::string& value); + /// Reads length bytes of raw data into value. + + void readBOM(); + /// Reads a byte-order mark from the stream and configures + /// the reader for the encountered byte order. + /// A byte-order mark is a 16-bit integer with a value of 0xFEFF, + /// written in host byte order. + + bool good(); + /// Returns _istr.good(); + + bool fail(); + /// Returns _istr.fail(); + + bool bad(); + /// Returns _istr.bad(); + + bool eof(); + /// Returns _istr.eof(); + + std::istream& stream() const; + /// Returns the underlying stream. + + StreamByteOrder byteOrder() const; + /// Returns the byte-order used by the reader, which is + /// either BIG_ENDIAN_BYTE_ORDER or LITTLE_ENDIAN_BYTE_ORDER. + +private: + std::istream& _istr; + bool _flipBytes; +}; + + +// +// inlines +// + + +inline bool BinaryReader::good() +{ + return _istr.good(); +} + + +inline bool BinaryReader::fail() +{ + return _istr.fail(); +} + + +inline bool BinaryReader::bad() +{ + return _istr.bad(); +} + + +inline bool BinaryReader::eof() +{ + return _istr.eof(); +} + + +inline std::istream& BinaryReader::stream() const +{ + return _istr; +} + + +inline BinaryReader::StreamByteOrder BinaryReader::byteOrder() const +{ +#if defined(POCO_ARCH_BIG_ENDIAN) + return _flipBytes ? LITTLE_ENDIAN_BYTE_ORDER : BIG_ENDIAN_BYTE_ORDER; +#else + return _flipBytes ? BIG_ENDIAN_BYTE_ORDER : LITTLE_ENDIAN_BYTE_ORDER; +#endif +} + + +} // namespace Poco + + +#endif // Foundation_BinaryReader_INCLUDED diff --git a/Foundation/include/Poco/BinaryWriter.h b/Foundation/include/Poco/BinaryWriter.h index da519e953..8146f17f4 100644 --- a/Foundation/include/Poco/BinaryWriter.h +++ b/Foundation/include/Poco/BinaryWriter.h @@ -1,199 +1,199 @@ -// -// BinaryWriter.h -// -// $Id: //poco/1.2/Foundation/include/Poco/BinaryWriter.h#1 $ -// -// Library: Foundation -// Package: Streams -// Module: BinaryReaderWriter -// -// Definition of the BinaryWriter class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_BinaryWriter_INCLUDED -#define Foundation_BinaryWriter_INCLUDED - - -#include "Poco/Foundation.h" -#include - - -namespace Poco { - - -class Foundation_API BinaryWriter - /// This class writes basic types in binary form into an output stream. - /// It provides an inserter-based interface similar to ostream. - /// The writer also supports automatic conversion from big-endian - /// (network byte order) to little-endian and vice-versa. - /// Use a BinaryReader to read from a stream created by a BinaryWriter. - /// Be careful when exchanging data between systems with different - /// data type sizes (e.g., 32-bit and 64-bit architectures), as the sizes - /// of some of the basic types may be different. For example, writing a - /// long integer on a 64-bit system and reading it on a 32-bit system - /// may yield an incorrent result. Use fixed-size types (Int32, Int64, etc.) - /// in such a case. -{ -public: - enum StreamByteOrder - { - NATIVE_BYTE_ORDER = 1, /// the host's native byte-order - BIG_ENDIAN_BYTE_ORDER = 2, /// big-endian (network) byte-order - NETWORK_BYTE_ORDER = 2, /// big-endian (network) byte-order - LITTLE_ENDIAN_BYTE_ORDER = 3 /// little-endian byte-order - }; - - BinaryWriter(std::ostream& ostr, StreamByteOrder byteOrder = NATIVE_BYTE_ORDER); - /// Creates the BinaryWriter. - - ~BinaryWriter(); - /// Destroys the BinaryWriter. - - BinaryWriter& operator << (bool value); - BinaryWriter& operator << (char value); - BinaryWriter& operator << (unsigned char value); - BinaryWriter& operator << (signed char value); - BinaryWriter& operator << (short value); - BinaryWriter& operator << (unsigned short value); - BinaryWriter& operator << (int value); - BinaryWriter& operator << (unsigned int value); - BinaryWriter& operator << (long value); - BinaryWriter& operator << (unsigned long value); - BinaryWriter& operator << (float value); - BinaryWriter& operator << (double value); - -#if defined(POCO_HAVE_INT64) && !defined(POCO_LONG_IS_64_BIT) - BinaryWriter& operator << (Int64 value); - BinaryWriter& operator << (UInt64 value); -#endif - - BinaryWriter& operator << (const std::string& value); - BinaryWriter& operator << (const char* value); - - void write7BitEncoded(UInt32 value); - /// Writes a 32-bit unsigned integer in a compressed format. - /// The value is written out seven bits at a time, starting - /// with the seven least-significant bits. - /// The high bit of a byte indicates whether there are more bytes to be - /// written after this one. - /// If value will fit in seven bits, it takes only one byte of space. - /// If value will not fit in seven bits, the high bit is set on the first byte and - /// written out. value is then shifted by seven bits and the next byte is written. - /// This process is repeated until the entire integer has been written. - -#if defined(POCO_HAVE_INT64) - void write7BitEncoded(UInt64 value); - /// Writes a 64-bit unsigned integer in a compressed format. - /// The value written out seven bits at a time, starting - /// with the seven least-significant bits. - /// The high bit of a byte indicates whether there are more bytes to be - /// written after this one. - /// If value will fit in seven bits, it takes only one byte of space. - /// If value will not fit in seven bits, the high bit is set on the first byte and - /// written out. value is then shifted by seven bits and the next byte is written. - /// This process is repeated until the entire integer has been written. -#endif - - void writeRaw(const std::string& rawData); - /// Writes the string as-is to the stream. - - void writeBOM(); - /// Writes a byte-order mark to the stream. A byte order mark is - /// a 16-bit integer with a value of 0xFEFF, written in host byte-order. - /// A BinaryReader uses the byte-order mark to determine the byte-order - /// of the stream. - - void flush(); - /// Flushes the underlying stream. - - bool good(); - /// Returns _ostr.good(); - - bool fail(); - /// Returns _ostr.fail(); - - bool bad(); - /// Returns _ostr.bad(); - - std::ostream& stream() const; - /// Returns the underlying stream. - - StreamByteOrder byteOrder() const; - /// Returns the byte ordering used by the writer, which is - /// either BIG_ENDIAN_BYTE_ORDER or LITTLE_ENDIAN_BYTE_ORDER. - -private: - std::ostream& _ostr; - bool _flipBytes; -}; - - -// -// inlines -// - - -inline std::ostream& BinaryWriter::stream() const -{ - return _ostr; -} - - -inline bool BinaryWriter::good() -{ - return _ostr.good(); -} - - -inline bool BinaryWriter::fail() -{ - return _ostr.fail(); -} - - -inline bool BinaryWriter::bad() -{ - return _ostr.bad(); -} - - -inline BinaryWriter::StreamByteOrder BinaryWriter::byteOrder() const -{ -#if defined(POCO_ARCH_BIG_ENDIAN) - return _flipBytes ? LITTLE_ENDIAN_BYTE_ORDER : BIG_ENDIAN_BYTE_ORDER; -#else - return _flipBytes ? BIG_ENDIAN_BYTE_ORDER : LITTLE_ENDIAN_BYTE_ORDER; -#endif -} - - -} // namespace Poco - - -#endif // Foundation_BinaryWriter_INCLUDED +// +// BinaryWriter.h +// +// $Id: //poco/1.2/Foundation/include/Poco/BinaryWriter.h#1 $ +// +// Library: Foundation +// Package: Streams +// Module: BinaryReaderWriter +// +// Definition of the BinaryWriter class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_BinaryWriter_INCLUDED +#define Foundation_BinaryWriter_INCLUDED + + +#include "Poco/Foundation.h" +#include + + +namespace Poco { + + +class Foundation_API BinaryWriter + /// This class writes basic types in binary form into an output stream. + /// It provides an inserter-based interface similar to ostream. + /// The writer also supports automatic conversion from big-endian + /// (network byte order) to little-endian and vice-versa. + /// Use a BinaryReader to read from a stream created by a BinaryWriter. + /// Be careful when exchanging data between systems with different + /// data type sizes (e.g., 32-bit and 64-bit architectures), as the sizes + /// of some of the basic types may be different. For example, writing a + /// long integer on a 64-bit system and reading it on a 32-bit system + /// may yield an incorrent result. Use fixed-size types (Int32, Int64, etc.) + /// in such a case. +{ +public: + enum StreamByteOrder + { + NATIVE_BYTE_ORDER = 1, /// the host's native byte-order + BIG_ENDIAN_BYTE_ORDER = 2, /// big-endian (network) byte-order + NETWORK_BYTE_ORDER = 2, /// big-endian (network) byte-order + LITTLE_ENDIAN_BYTE_ORDER = 3 /// little-endian byte-order + }; + + BinaryWriter(std::ostream& ostr, StreamByteOrder byteOrder = NATIVE_BYTE_ORDER); + /// Creates the BinaryWriter. + + ~BinaryWriter(); + /// Destroys the BinaryWriter. + + BinaryWriter& operator << (bool value); + BinaryWriter& operator << (char value); + BinaryWriter& operator << (unsigned char value); + BinaryWriter& operator << (signed char value); + BinaryWriter& operator << (short value); + BinaryWriter& operator << (unsigned short value); + BinaryWriter& operator << (int value); + BinaryWriter& operator << (unsigned int value); + BinaryWriter& operator << (long value); + BinaryWriter& operator << (unsigned long value); + BinaryWriter& operator << (float value); + BinaryWriter& operator << (double value); + +#if defined(POCO_HAVE_INT64) && !defined(POCO_LONG_IS_64_BIT) + BinaryWriter& operator << (Int64 value); + BinaryWriter& operator << (UInt64 value); +#endif + + BinaryWriter& operator << (const std::string& value); + BinaryWriter& operator << (const char* value); + + void write7BitEncoded(UInt32 value); + /// Writes a 32-bit unsigned integer in a compressed format. + /// The value is written out seven bits at a time, starting + /// with the seven least-significant bits. + /// The high bit of a byte indicates whether there are more bytes to be + /// written after this one. + /// If value will fit in seven bits, it takes only one byte of space. + /// If value will not fit in seven bits, the high bit is set on the first byte and + /// written out. value is then shifted by seven bits and the next byte is written. + /// This process is repeated until the entire integer has been written. + +#if defined(POCO_HAVE_INT64) + void write7BitEncoded(UInt64 value); + /// Writes a 64-bit unsigned integer in a compressed format. + /// The value written out seven bits at a time, starting + /// with the seven least-significant bits. + /// The high bit of a byte indicates whether there are more bytes to be + /// written after this one. + /// If value will fit in seven bits, it takes only one byte of space. + /// If value will not fit in seven bits, the high bit is set on the first byte and + /// written out. value is then shifted by seven bits and the next byte is written. + /// This process is repeated until the entire integer has been written. +#endif + + void writeRaw(const std::string& rawData); + /// Writes the string as-is to the stream. + + void writeBOM(); + /// Writes a byte-order mark to the stream. A byte order mark is + /// a 16-bit integer with a value of 0xFEFF, written in host byte-order. + /// A BinaryReader uses the byte-order mark to determine the byte-order + /// of the stream. + + void flush(); + /// Flushes the underlying stream. + + bool good(); + /// Returns _ostr.good(); + + bool fail(); + /// Returns _ostr.fail(); + + bool bad(); + /// Returns _ostr.bad(); + + std::ostream& stream() const; + /// Returns the underlying stream. + + StreamByteOrder byteOrder() const; + /// Returns the byte ordering used by the writer, which is + /// either BIG_ENDIAN_BYTE_ORDER or LITTLE_ENDIAN_BYTE_ORDER. + +private: + std::ostream& _ostr; + bool _flipBytes; +}; + + +// +// inlines +// + + +inline std::ostream& BinaryWriter::stream() const +{ + return _ostr; +} + + +inline bool BinaryWriter::good() +{ + return _ostr.good(); +} + + +inline bool BinaryWriter::fail() +{ + return _ostr.fail(); +} + + +inline bool BinaryWriter::bad() +{ + return _ostr.bad(); +} + + +inline BinaryWriter::StreamByteOrder BinaryWriter::byteOrder() const +{ +#if defined(POCO_ARCH_BIG_ENDIAN) + return _flipBytes ? LITTLE_ENDIAN_BYTE_ORDER : BIG_ENDIAN_BYTE_ORDER; +#else + return _flipBytes ? BIG_ENDIAN_BYTE_ORDER : LITTLE_ENDIAN_BYTE_ORDER; +#endif +} + + +} // namespace Poco + + +#endif // Foundation_BinaryWriter_INCLUDED diff --git a/Foundation/include/Poco/Buffer.h b/Foundation/include/Poco/Buffer.h index 2d3857d46..ed0e70e00 100644 --- a/Foundation/include/Poco/Buffer.h +++ b/Foundation/include/Poco/Buffer.h @@ -1,129 +1,129 @@ -// -// Buffer.h -// -// $Id: //poco/1.2/Foundation/include/Poco/Buffer.h#1 $ -// -// Library: Foundation -// Package: Core -// Module: Buffer -// -// Definition of the Buffer class. -// -// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_Buffer_INCLUDED -#define Foundation_Buffer_INCLUDED - - -#include "Poco/Foundation.h" - - -namespace Poco { - - -template -class Buffer - /// A very simple buffer class that allocates a buffer of - /// a given type and size in the constructor and - /// deallocates the buffer in the destructor. - /// - /// This class is useful everywhere where a temporary buffer - /// is needed. -{ -public: - Buffer(int size): - _size(size), - _ptr(new T[size]) - /// Creates and allocates the Buffer. - { - } - - ~Buffer() - /// Destroys the Buffer. - { - delete [] _ptr; - } - - int size() const - /// Returns the size of the buffer. - { - return _size; - } - - T* begin() - /// Returns a pointer to the beginning of the buffer. - { - return _ptr; - } - - const T* begin() const - /// Returns a pointer to the beginning of the buffer. - { - return _ptr; - } - - T* end() - /// Returns a pointer to end of the buffer. - { - return _ptr + _size; - } - - const T* end() const - /// Returns a pointer to the end of the buffer. - { - return _ptr + _size; - } - - T& operator [] (int index) - { - poco_assert (index >= 0 && index < _size); - - return _ptr[index]; - } - - const T& operator [] (int index) const - { - poco_assert (index >= 0 && index < _size); - - return _ptr[index]; - } - -private: - Buffer(); - Buffer(const Buffer&); - Buffer& operator = (const Buffer&); - - int _size; - T* _ptr; -}; - - -} // namespace Poco - - -#endif // Foundation_Buffer_INCLUDED +// +// Buffer.h +// +// $Id: //poco/1.2/Foundation/include/Poco/Buffer.h#1 $ +// +// Library: Foundation +// Package: Core +// Module: Buffer +// +// Definition of the Buffer class. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_Buffer_INCLUDED +#define Foundation_Buffer_INCLUDED + + +#include "Poco/Foundation.h" + + +namespace Poco { + + +template +class Buffer + /// A very simple buffer class that allocates a buffer of + /// a given type and size in the constructor and + /// deallocates the buffer in the destructor. + /// + /// This class is useful everywhere where a temporary buffer + /// is needed. +{ +public: + Buffer(int size): + _size(size), + _ptr(new T[size]) + /// Creates and allocates the Buffer. + { + } + + ~Buffer() + /// Destroys the Buffer. + { + delete [] _ptr; + } + + int size() const + /// Returns the size of the buffer. + { + return _size; + } + + T* begin() + /// Returns a pointer to the beginning of the buffer. + { + return _ptr; + } + + const T* begin() const + /// Returns a pointer to the beginning of the buffer. + { + return _ptr; + } + + T* end() + /// Returns a pointer to end of the buffer. + { + return _ptr + _size; + } + + const T* end() const + /// Returns a pointer to the end of the buffer. + { + return _ptr + _size; + } + + T& operator [] (int index) + { + poco_assert (index >= 0 && index < _size); + + return _ptr[index]; + } + + const T& operator [] (int index) const + { + poco_assert (index >= 0 && index < _size); + + return _ptr[index]; + } + +private: + Buffer(); + Buffer(const Buffer&); + Buffer& operator = (const Buffer&); + + int _size; + T* _ptr; +}; + + +} // namespace Poco + + +#endif // Foundation_Buffer_INCLUDED diff --git a/Foundation/include/Poco/BufferAllocator.h b/Foundation/include/Poco/BufferAllocator.h index fa6814516..e15f51d58 100644 --- a/Foundation/include/Poco/BufferAllocator.h +++ b/Foundation/include/Poco/BufferAllocator.h @@ -1,73 +1,73 @@ -// -// BufferAllocator.h -// -// $Id: //poco/1.2/Foundation/include/Poco/BufferAllocator.h#1 $ -// -// Library: Foundation -// Package: Streams -// Module: BufferAllocator -// -// Definition of the BufferAllocator class. -// -// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_BufferAllocator_INCLUDED -#define Foundation_BufferAllocator_INCLUDED - - -#include "Poco/Foundation.h" -#include - - -namespace Poco { - - -template -class BufferAllocator - /// The BufferAllocator used if no specific - /// BufferAllocator has been specified. -{ -public: - typedef ch char_type; - - static char_type* allocate(std::streamsize size) - { - return new char_type[size]; - } - - static void deallocate(char_type* ptr, std::streamsize size) - { - delete [] ptr; - } -}; - - -} // namespace Poco - - -#endif // Foundation_BufferAllocator_INCLUDED +// +// BufferAllocator.h +// +// $Id: //poco/1.2/Foundation/include/Poco/BufferAllocator.h#1 $ +// +// Library: Foundation +// Package: Streams +// Module: BufferAllocator +// +// Definition of the BufferAllocator class. +// +// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_BufferAllocator_INCLUDED +#define Foundation_BufferAllocator_INCLUDED + + +#include "Poco/Foundation.h" +#include + + +namespace Poco { + + +template +class BufferAllocator + /// The BufferAllocator used if no specific + /// BufferAllocator has been specified. +{ +public: + typedef ch char_type; + + static char_type* allocate(std::streamsize size) + { + return new char_type[size]; + } + + static void deallocate(char_type* ptr, std::streamsize size) + { + delete [] ptr; + } +}; + + +} // namespace Poco + + +#endif // Foundation_BufferAllocator_INCLUDED diff --git a/Foundation/include/Poco/BufferedBidirectionalStreamBuf.h b/Foundation/include/Poco/BufferedBidirectionalStreamBuf.h index 73208bdc7..f528b078a 100644 --- a/Foundation/include/Poco/BufferedBidirectionalStreamBuf.h +++ b/Foundation/include/Poco/BufferedBidirectionalStreamBuf.h @@ -1,177 +1,177 @@ -// -// BufferedBidirectionalStreamBuf.h -// -// $Id: //poco/1.2/Foundation/include/Poco/BufferedBidirectionalStreamBuf.h#1 $ -// -// Library: Foundation -// Package: Streams -// Module: StreamBuf -// -// Definition of template BasicBufferedBidirectionalStreamBuf and class BufferedBidirectionalStreamBuf. -// -// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_BufferedBidirectionalStreamBuf_INCLUDED -#define Foundation_BufferedBidirectionalStreamBuf_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/BufferAllocator.h" -#include "Poco/StreamUtil.h" -#include -#include -#include - - -namespace Poco { - - -template > -class BasicBufferedBidirectionalStreamBuf: public std::basic_streambuf - /// This is an implementation of a buffered bidirectional - /// streambuf that greatly simplifies the implementation of - /// custom streambufs of various kinds. - /// Derived classes only have to override the methods - /// readFromDevice() or writeToDevice(). - /// - /// In contrast to BasicBufferedStreambuf, this class supports - /// simultaneous read and write access, so in addition to - /// istream and ostream this streambuf can also be used - /// for implementing an iostream. -{ -protected: - typedef std::basic_streambuf Base; - typedef std::basic_ios IOS; - typedef ch char_type; - typedef tr char_traits; - typedef ba Allocator; - typedef typename Base::int_type int_type; - typedef typename Base::pos_type pos_type; - typedef typename Base::off_type off_type; - typedef typename IOS::openmode openmode; - -public: - BasicBufferedBidirectionalStreamBuf(std::streamsize bufferSize, openmode mode): - _bufsize(bufferSize), - _pReadBuffer(Allocator::allocate(_bufsize)), - _pWriteBuffer(Allocator::allocate(_bufsize)), - _mode(mode) - { - this->setg(_pReadBuffer + 4, _pReadBuffer + 4, _pReadBuffer + 4); - this->setp(_pWriteBuffer, _pWriteBuffer + (_bufsize - 1)); - } - - ~BasicBufferedBidirectionalStreamBuf() - { - Allocator::deallocate(_pReadBuffer, _bufsize); - Allocator::deallocate(_pWriteBuffer, _bufsize); - } - - virtual int_type overflow(int_type c) - { - if (!(_mode & IOS::out)) return char_traits::eof(); - - if (c != char_traits::eof()) - { - *this->pptr() = char_traits::to_char_type(c); - this->pbump(1); - } - if (flush_buffer() == std::streamsize(-1)) return char_traits::eof(); - - return c; - } - - virtual int_type underflow() - { - if (!(_mode & IOS::in)) return char_traits::eof(); - - if (this->gptr() && (this->gptr() < this->egptr())) - return char_traits::to_int_type(*this->gptr()); - - int putback = int(this->gptr() - this->eback()); - if (putback > 4) putback = 4; - - char_traits::copy(_pReadBuffer + (4 - putback), this->gptr() - putback, putback); - - int n = readFromDevice(_pReadBuffer + 4, _bufsize - 4); - if (n <= 0) return char_traits::eof(); - - this->setg(_pReadBuffer + (4 - putback), _pReadBuffer + 4, _pReadBuffer + 4 + n); - - // return next character - return char_traits::to_int_type(*this->gptr()); - } - - virtual int sync() - { - if (this->pptr() && this->pptr() > this->pbase()) - { - if (flush_buffer() == -1) return -1; - } - return 0; - } - -private: - virtual int readFromDevice(char_type* buffer, std::streamsize length) - { - return 0; - } - - virtual int writeToDevice(const char_type* buffer, std::streamsize length) - { - return 0; - } - - int flush_buffer() - { - int n = int(this->pptr() - this->pbase()); - if (writeToDevice(this->pbase(), n) == n) - { - this->pbump(-n); - return n; - } - return -1; - } - - std::streamsize _bufsize; - char_type* _pReadBuffer; - char_type* _pWriteBuffer; - openmode _mode; -}; - - -// -// We provide an instantiation for char -// -typedef BasicBufferedBidirectionalStreamBuf > BufferedBidirectionalStreamBuf; - - -} // namespace Poco - - -#endif // Foundation_BufferedBidirectionalStreamBuf_INCLUDED +// +// BufferedBidirectionalStreamBuf.h +// +// $Id: //poco/1.2/Foundation/include/Poco/BufferedBidirectionalStreamBuf.h#1 $ +// +// Library: Foundation +// Package: Streams +// Module: StreamBuf +// +// Definition of template BasicBufferedBidirectionalStreamBuf and class BufferedBidirectionalStreamBuf. +// +// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_BufferedBidirectionalStreamBuf_INCLUDED +#define Foundation_BufferedBidirectionalStreamBuf_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/BufferAllocator.h" +#include "Poco/StreamUtil.h" +#include +#include +#include + + +namespace Poco { + + +template > +class BasicBufferedBidirectionalStreamBuf: public std::basic_streambuf + /// This is an implementation of a buffered bidirectional + /// streambuf that greatly simplifies the implementation of + /// custom streambufs of various kinds. + /// Derived classes only have to override the methods + /// readFromDevice() or writeToDevice(). + /// + /// In contrast to BasicBufferedStreambuf, this class supports + /// simultaneous read and write access, so in addition to + /// istream and ostream this streambuf can also be used + /// for implementing an iostream. +{ +protected: + typedef std::basic_streambuf Base; + typedef std::basic_ios IOS; + typedef ch char_type; + typedef tr char_traits; + typedef ba Allocator; + typedef typename Base::int_type int_type; + typedef typename Base::pos_type pos_type; + typedef typename Base::off_type off_type; + typedef typename IOS::openmode openmode; + +public: + BasicBufferedBidirectionalStreamBuf(std::streamsize bufferSize, openmode mode): + _bufsize(bufferSize), + _pReadBuffer(Allocator::allocate(_bufsize)), + _pWriteBuffer(Allocator::allocate(_bufsize)), + _mode(mode) + { + this->setg(_pReadBuffer + 4, _pReadBuffer + 4, _pReadBuffer + 4); + this->setp(_pWriteBuffer, _pWriteBuffer + (_bufsize - 1)); + } + + ~BasicBufferedBidirectionalStreamBuf() + { + Allocator::deallocate(_pReadBuffer, _bufsize); + Allocator::deallocate(_pWriteBuffer, _bufsize); + } + + virtual int_type overflow(int_type c) + { + if (!(_mode & IOS::out)) return char_traits::eof(); + + if (c != char_traits::eof()) + { + *this->pptr() = char_traits::to_char_type(c); + this->pbump(1); + } + if (flush_buffer() == std::streamsize(-1)) return char_traits::eof(); + + return c; + } + + virtual int_type underflow() + { + if (!(_mode & IOS::in)) return char_traits::eof(); + + if (this->gptr() && (this->gptr() < this->egptr())) + return char_traits::to_int_type(*this->gptr()); + + int putback = int(this->gptr() - this->eback()); + if (putback > 4) putback = 4; + + char_traits::copy(_pReadBuffer + (4 - putback), this->gptr() - putback, putback); + + int n = readFromDevice(_pReadBuffer + 4, _bufsize - 4); + if (n <= 0) return char_traits::eof(); + + this->setg(_pReadBuffer + (4 - putback), _pReadBuffer + 4, _pReadBuffer + 4 + n); + + // return next character + return char_traits::to_int_type(*this->gptr()); + } + + virtual int sync() + { + if (this->pptr() && this->pptr() > this->pbase()) + { + if (flush_buffer() == -1) return -1; + } + return 0; + } + +private: + virtual int readFromDevice(char_type* buffer, std::streamsize length) + { + return 0; + } + + virtual int writeToDevice(const char_type* buffer, std::streamsize length) + { + return 0; + } + + int flush_buffer() + { + int n = int(this->pptr() - this->pbase()); + if (writeToDevice(this->pbase(), n) == n) + { + this->pbump(-n); + return n; + } + return -1; + } + + std::streamsize _bufsize; + char_type* _pReadBuffer; + char_type* _pWriteBuffer; + openmode _mode; +}; + + +// +// We provide an instantiation for char +// +typedef BasicBufferedBidirectionalStreamBuf > BufferedBidirectionalStreamBuf; + + +} // namespace Poco + + +#endif // Foundation_BufferedBidirectionalStreamBuf_INCLUDED diff --git a/Foundation/include/Poco/BufferedStreamBuf.h b/Foundation/include/Poco/BufferedStreamBuf.h index f88210fcf..f293d514d 100644 --- a/Foundation/include/Poco/BufferedStreamBuf.h +++ b/Foundation/include/Poco/BufferedStreamBuf.h @@ -1,174 +1,174 @@ -// -// BufferedStreamBuf.h -// -// $Id: //poco/1.2/Foundation/include/Poco/BufferedStreamBuf.h#1 $ -// -// Library: Foundation -// Package: Streams -// Module: StreamBuf -// -// Definition of template BasicBufferedStreamBuf and class BufferedStreamBuf. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_BufferedStreamBuf_INCLUDED -#define Foundation_BufferedStreamBuf_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/BufferAllocator.h" -#include "Poco/StreamUtil.h" -#include -#include -#include - - -namespace Poco { - - -template > -class BasicBufferedStreamBuf: public std::basic_streambuf - /// This is an implementation of a buffered streambuf - /// that greatly simplifies the implementation of - /// custom streambufs of various kinds. - /// Derived classes only have to override the methods - /// readFromDevice() or writeToDevice(). - /// - /// This streambuf only supports unidirectional streams. - /// In other words, the BasicBufferedStreamBuf can be - /// used for the implementation of an istream or an - /// ostream, but not for an iostream. -{ -protected: - typedef std::basic_streambuf Base; - typedef std::basic_ios IOS; - typedef ch char_type; - typedef tr char_traits; - typedef ba Allocator; - typedef typename Base::int_type int_type; - typedef typename Base::pos_type pos_type; - typedef typename Base::off_type off_type; - typedef typename IOS::openmode openmode; - -public: - BasicBufferedStreamBuf(std::streamsize bufferSize, openmode mode): - _bufsize(bufferSize), - _pBuffer(Allocator::allocate(_bufsize)), - _mode(mode) - { - this->setg(_pBuffer + 4, _pBuffer + 4, _pBuffer + 4); - this->setp(_pBuffer, _pBuffer + (_bufsize - 1)); - } - - ~BasicBufferedStreamBuf() - { - Allocator::deallocate(_pBuffer, _bufsize); - } - - virtual int_type overflow(int_type c) - { - if (!(_mode & IOS::out)) return char_traits::eof(); - - if (c != char_traits::eof()) - { - *this->pptr() = char_traits::to_char_type(c); - this->pbump(1); - } - if (flush_buffer() == std::streamsize(-1)) return char_traits::eof(); - - return c; - } - - virtual int_type underflow() - { - if (!(_mode & IOS::in)) return char_traits::eof(); - - if (this->gptr() && (this->gptr() < this->egptr())) - return char_traits::to_int_type(*this->gptr()); - - int putback = int(this->gptr() - this->eback()); - if (putback > 4) putback = 4; - - char_traits::copy(_pBuffer + (4 - putback), this->gptr() - putback, putback); - - int n = readFromDevice(_pBuffer + 4, _bufsize - 4); - if (n <= 0) return char_traits::eof(); - - this->setg(_pBuffer + (4 - putback), _pBuffer + 4, _pBuffer + 4 + n); - - // return next character - return char_traits::to_int_type(*this->gptr()); - } - - virtual int sync() - { - if (this->pptr() && this->pptr() > this->pbase()) - { - if (flush_buffer() == -1) return -1; - } - return 0; - } - -private: - virtual int readFromDevice(char_type* buffer, std::streamsize length) - { - return 0; - } - - virtual int writeToDevice(const char_type* buffer, std::streamsize length) - { - return 0; - } - - int flush_buffer() - { - int n = int(this->pptr() - this->pbase()); - if (writeToDevice(this->pbase(), n) == n) - { - this->pbump(-n); - return n; - } - return -1; - } - - std::streamsize _bufsize; - char_type* _pBuffer; - openmode _mode; -}; - - -// -// We provide an instantiation for char -// -typedef BasicBufferedStreamBuf > BufferedStreamBuf; - - -} // namespace Poco - - -#endif // Foundation_BufferedStreamBuf_INCLUDED +// +// BufferedStreamBuf.h +// +// $Id: //poco/1.2/Foundation/include/Poco/BufferedStreamBuf.h#1 $ +// +// Library: Foundation +// Package: Streams +// Module: StreamBuf +// +// Definition of template BasicBufferedStreamBuf and class BufferedStreamBuf. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_BufferedStreamBuf_INCLUDED +#define Foundation_BufferedStreamBuf_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/BufferAllocator.h" +#include "Poco/StreamUtil.h" +#include +#include +#include + + +namespace Poco { + + +template > +class BasicBufferedStreamBuf: public std::basic_streambuf + /// This is an implementation of a buffered streambuf + /// that greatly simplifies the implementation of + /// custom streambufs of various kinds. + /// Derived classes only have to override the methods + /// readFromDevice() or writeToDevice(). + /// + /// This streambuf only supports unidirectional streams. + /// In other words, the BasicBufferedStreamBuf can be + /// used for the implementation of an istream or an + /// ostream, but not for an iostream. +{ +protected: + typedef std::basic_streambuf Base; + typedef std::basic_ios IOS; + typedef ch char_type; + typedef tr char_traits; + typedef ba Allocator; + typedef typename Base::int_type int_type; + typedef typename Base::pos_type pos_type; + typedef typename Base::off_type off_type; + typedef typename IOS::openmode openmode; + +public: + BasicBufferedStreamBuf(std::streamsize bufferSize, openmode mode): + _bufsize(bufferSize), + _pBuffer(Allocator::allocate(_bufsize)), + _mode(mode) + { + this->setg(_pBuffer + 4, _pBuffer + 4, _pBuffer + 4); + this->setp(_pBuffer, _pBuffer + (_bufsize - 1)); + } + + ~BasicBufferedStreamBuf() + { + Allocator::deallocate(_pBuffer, _bufsize); + } + + virtual int_type overflow(int_type c) + { + if (!(_mode & IOS::out)) return char_traits::eof(); + + if (c != char_traits::eof()) + { + *this->pptr() = char_traits::to_char_type(c); + this->pbump(1); + } + if (flush_buffer() == std::streamsize(-1)) return char_traits::eof(); + + return c; + } + + virtual int_type underflow() + { + if (!(_mode & IOS::in)) return char_traits::eof(); + + if (this->gptr() && (this->gptr() < this->egptr())) + return char_traits::to_int_type(*this->gptr()); + + int putback = int(this->gptr() - this->eback()); + if (putback > 4) putback = 4; + + char_traits::copy(_pBuffer + (4 - putback), this->gptr() - putback, putback); + + int n = readFromDevice(_pBuffer + 4, _bufsize - 4); + if (n <= 0) return char_traits::eof(); + + this->setg(_pBuffer + (4 - putback), _pBuffer + 4, _pBuffer + 4 + n); + + // return next character + return char_traits::to_int_type(*this->gptr()); + } + + virtual int sync() + { + if (this->pptr() && this->pptr() > this->pbase()) + { + if (flush_buffer() == -1) return -1; + } + return 0; + } + +private: + virtual int readFromDevice(char_type* buffer, std::streamsize length) + { + return 0; + } + + virtual int writeToDevice(const char_type* buffer, std::streamsize length) + { + return 0; + } + + int flush_buffer() + { + int n = int(this->pptr() - this->pbase()); + if (writeToDevice(this->pbase(), n) == n) + { + this->pbump(-n); + return n; + } + return -1; + } + + std::streamsize _bufsize; + char_type* _pBuffer; + openmode _mode; +}; + + +// +// We provide an instantiation for char +// +typedef BasicBufferedStreamBuf > BufferedStreamBuf; + + +} // namespace Poco + + +#endif // Foundation_BufferedStreamBuf_INCLUDED diff --git a/Foundation/include/Poco/Bugcheck.h b/Foundation/include/Poco/Bugcheck.h index 193c08eeb..a040bf120 100644 --- a/Foundation/include/Poco/Bugcheck.h +++ b/Foundation/include/Poco/Bugcheck.h @@ -1,126 +1,126 @@ -// -// Bugcheck.h -// -// $Id: //poco/1.2/Foundation/include/Poco/Bugcheck.h#1 $ -// -// Library: Foundation -// Package: Core -// Module: Bugcheck -// -// Definition of the Bugcheck class and the self-testing macros. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_Bugcheck_INCLUDED -#define Foundation_Bugcheck_INCLUDED - - -#include "Poco/Foundation.h" -#include - - -namespace Poco { - - -class Foundation_API Bugcheck - /// This class provides some static methods that are - /// used by the - /// poco_assert_dbg(), poco_assert(), poco_check_ptr() - /// and poco_bugcheck() macros. - /// You should not invoke these methods - /// directly. Use the macros instead, as they - /// automatically provide useful context information. -{ -public: - static void assertion(const char* cond, const char* file, int line); - /// An assertion failed. Break into the debugger, if - /// possible, then throw an AssertionViolationException. - - static void nullPointer(const char* ptr, const char* file, int line); - /// An null pointer was encountered. Break into the debugger, if - /// possible, then throw an NullPointerException. - - static void bugcheck(const char* file, int line); - /// An internal error was encountered. Break into the debugger, if - /// possible, then throw an BugcheckException. - - static void bugcheck(const char* msg, const char* file, int line); - /// An internal error was encountered. Break into the debugger, if - /// possible, then throw an BugcheckException. - - static void debugger(const char* file, int line); - /// An internal error was encountered. Break into the debugger, if - /// possible. - - static void debugger(const char* msg, const char* file, int line); - /// An internal error was encountered. Break into the debugger, if - /// possible. - -protected: - static std::string what(const char* msg, const char* file, int line); -}; - - -// -// useful macros (these automatically supply line number and file name) -// -#if defined(_DEBUG) - #define poco_assert_dbg(cond) if (!(cond)) Poco::Bugcheck::assertion(#cond, __FILE__, __LINE__); else (void) 0 -#else - #define poco_assert_dbg(cond) -#endif - - -#define poco_assert(cond) \ - if (!(cond)) Poco::Bugcheck::assertion(#cond, __FILE__, __LINE__); else (void) 0 - - -#define poco_check_ptr(ptr) \ - if (!(ptr)) Poco::Bugcheck::nullPointer(#ptr, __FILE__, __LINE__); else (void) 0 - - -#define poco_bugcheck() \ - Poco::Bugcheck::bugcheck(__FILE__, __LINE__) - - -#define poco_bugcheck_msg(msg) \ - Poco::Bugcheck::bugcheck(msg, __FILE__, __LINE__) - - -#define poco_debugger() \ - Poco::Bugcheck::debugger(__FILE__, __LINE__) - - -#define poco_debugger_msg(msg) \ - Poco::Bugcheck::debugger(msg, __FILE__, __LINE__) - - -} // namespace Poco - - -#endif // Foundation_Bugcheck_INCLUDED +// +// Bugcheck.h +// +// $Id: //poco/1.2/Foundation/include/Poco/Bugcheck.h#1 $ +// +// Library: Foundation +// Package: Core +// Module: Bugcheck +// +// Definition of the Bugcheck class and the self-testing macros. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_Bugcheck_INCLUDED +#define Foundation_Bugcheck_INCLUDED + + +#include "Poco/Foundation.h" +#include + + +namespace Poco { + + +class Foundation_API Bugcheck + /// This class provides some static methods that are + /// used by the + /// poco_assert_dbg(), poco_assert(), poco_check_ptr() + /// and poco_bugcheck() macros. + /// You should not invoke these methods + /// directly. Use the macros instead, as they + /// automatically provide useful context information. +{ +public: + static void assertion(const char* cond, const char* file, int line); + /// An assertion failed. Break into the debugger, if + /// possible, then throw an AssertionViolationException. + + static void nullPointer(const char* ptr, const char* file, int line); + /// An null pointer was encountered. Break into the debugger, if + /// possible, then throw an NullPointerException. + + static void bugcheck(const char* file, int line); + /// An internal error was encountered. Break into the debugger, if + /// possible, then throw an BugcheckException. + + static void bugcheck(const char* msg, const char* file, int line); + /// An internal error was encountered. Break into the debugger, if + /// possible, then throw an BugcheckException. + + static void debugger(const char* file, int line); + /// An internal error was encountered. Break into the debugger, if + /// possible. + + static void debugger(const char* msg, const char* file, int line); + /// An internal error was encountered. Break into the debugger, if + /// possible. + +protected: + static std::string what(const char* msg, const char* file, int line); +}; + + +// +// useful macros (these automatically supply line number and file name) +// +#if defined(_DEBUG) + #define poco_assert_dbg(cond) if (!(cond)) Poco::Bugcheck::assertion(#cond, __FILE__, __LINE__); else (void) 0 +#else + #define poco_assert_dbg(cond) +#endif + + +#define poco_assert(cond) \ + if (!(cond)) Poco::Bugcheck::assertion(#cond, __FILE__, __LINE__); else (void) 0 + + +#define poco_check_ptr(ptr) \ + if (!(ptr)) Poco::Bugcheck::nullPointer(#ptr, __FILE__, __LINE__); else (void) 0 + + +#define poco_bugcheck() \ + Poco::Bugcheck::bugcheck(__FILE__, __LINE__) + + +#define poco_bugcheck_msg(msg) \ + Poco::Bugcheck::bugcheck(msg, __FILE__, __LINE__) + + +#define poco_debugger() \ + Poco::Bugcheck::debugger(__FILE__, __LINE__) + + +#define poco_debugger_msg(msg) \ + Poco::Bugcheck::debugger(msg, __FILE__, __LINE__) + + +} // namespace Poco + + +#endif // Foundation_Bugcheck_INCLUDED diff --git a/Foundation/include/Poco/ByteOrder.h b/Foundation/include/Poco/ByteOrder.h index c0610ca35..10a41ff70 100644 --- a/Foundation/include/Poco/ByteOrder.h +++ b/Foundation/include/Poco/ByteOrder.h @@ -1,227 +1,227 @@ -// -// ByteOrder.h -// -// $Id: //poco/1.2/Foundation/include/Poco/ByteOrder.h#1 $ -// -// Library: Foundation -// Package: Core -// Module: ByteOrder -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_ByteOrder_INCLUDED -#define Foundation_ByteOrder_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/Types.h" - - -namespace Poco { - - -class Foundation_API ByteOrder - /// This class contains a number of static methods - /// to convert between big-endian and little-endian - /// integers of various sizes. -{ -public: - static Int16 flipBytes(Int16 value); - static UInt16 flipBytes(UInt16 value); - static Int32 flipBytes(Int32 value); - static UInt32 flipBytes(UInt32 value); -#if defined(POCO_HAVE_INT64) - static Int64 flipBytes(Int64 value); - static UInt64 flipBytes(UInt64 value); -#endif - - static Int16 toBigEndian(Int16 value); - static UInt16 toBigEndian (UInt16 value); - static Int32 toBigEndian(Int32 value); - static UInt32 toBigEndian (UInt32 value); -#if defined(POCO_HAVE_INT64) - static Int64 toBigEndian(Int64 value); - static UInt64 toBigEndian (UInt64 value); -#endif - - static Int16 fromBigEndian(Int16 value); - static UInt16 fromBigEndian (UInt16 value); - static Int32 fromBigEndian(Int32 value); - static UInt32 fromBigEndian (UInt32 value); -#if defined(POCO_HAVE_INT64) - static Int64 fromBigEndian(Int64 value); - static UInt64 fromBigEndian (UInt64 value); -#endif - - static Int16 toLittleEndian(Int16 value); - static UInt16 toLittleEndian (UInt16 value); - static Int32 toLittleEndian(Int32 value); - static UInt32 toLittleEndian (UInt32 value); -#if defined(POCO_HAVE_INT64) - static Int64 toLittleEndian(Int64 value); - static UInt64 toLittleEndian (UInt64 value); -#endif - - static Int16 fromLittleEndian(Int16 value); - static UInt16 fromLittleEndian (UInt16 value); - static Int32 fromLittleEndian(Int32 value); - static UInt32 fromLittleEndian (UInt32 value); -#if defined(POCO_HAVE_INT64) - static Int64 fromLittleEndian(Int64 value); - static UInt64 fromLittleEndian (UInt64 value); -#endif - - static Int16 toNetwork(Int16 value); - static UInt16 toNetwork (UInt16 value); - static Int32 toNetwork(Int32 value); - static UInt32 toNetwork (UInt32 value); -#if defined(POCO_HAVE_INT64) - static Int64 toNetwork(Int64 value); - static UInt64 toNetwork (UInt64 value); -#endif - - static Int16 fromNetwork(Int16 value); - static UInt16 fromNetwork (UInt16 value); - static Int32 fromNetwork(Int32 value); - static UInt32 fromNetwork (UInt32 value); -#if defined(POCO_HAVE_INT64) - static Int64 fromNetwork(Int64 value); - static UInt64 fromNetwork (UInt64 value); -#endif -}; - - -// -// inlines -// -inline UInt16 ByteOrder::flipBytes(UInt16 value) -{ - return ((value >> 8) & 0x00FF) | ((value << 8) & 0xFF00); -} - - -inline Int16 ByteOrder::flipBytes(Int16 value) -{ - return Int16(flipBytes(UInt16(value))); -} - - -inline UInt32 ByteOrder::flipBytes(UInt32 value) -{ - return ((value >> 24) & 0x000000FF) | ((value >> 8) & 0x0000FF00) - | ((value << 8) & 0x00FF0000) | ((value << 24) & 0xFF000000); -} - - -inline Int32 ByteOrder::flipBytes(Int32 value) -{ - return Int32(flipBytes(UInt32(value))); -} - - -#if defined(POCO_HAVE_INT64) -inline UInt64 ByteOrder::flipBytes(UInt64 value) -{ - UInt32 hi = UInt32(value >> 32); - UInt32 lo = UInt32(value & 0xFFFFFFFF); - return UInt64(flipBytes(hi)) | (UInt64(flipBytes(lo)) << 32); -} - - -inline Int64 ByteOrder::flipBytes(Int64 value) -{ - return Int64(flipBytes(UInt64(value))); -} -#endif // POCO_HAVE_INT64 - - -// -// some macro trickery to automate the method implementation -// -#define POCO_IMPLEMENT_BYTEORDER_NOOP_(op, type) \ - inline type ByteOrder::op(type value) \ - { \ - return value; \ - } -#define POCO_IMPLEMENT_BYTEORDER_FLIP_(op, type) \ - inline type ByteOrder::op(type value) \ - { \ - return flipBytes(value); \ - } - - -#if defined(POCO_HAVE_INT64) - #define POCO_IMPLEMENT_BYTEORDER_NOOP(op) \ - POCO_IMPLEMENT_BYTEORDER_NOOP_(op, Int16) \ - POCO_IMPLEMENT_BYTEORDER_NOOP_(op, UInt16) \ - POCO_IMPLEMENT_BYTEORDER_NOOP_(op, Int32) \ - POCO_IMPLEMENT_BYTEORDER_NOOP_(op, UInt32) \ - POCO_IMPLEMENT_BYTEORDER_NOOP_(op, Int64) \ - POCO_IMPLEMENT_BYTEORDER_NOOP_(op, UInt64) - #define POCO_IMPLEMENT_BYTEORDER_FLIP(op) \ - POCO_IMPLEMENT_BYTEORDER_FLIP_(op, Int16) \ - POCO_IMPLEMENT_BYTEORDER_FLIP_(op, UInt16) \ - POCO_IMPLEMENT_BYTEORDER_FLIP_(op, Int32) \ - POCO_IMPLEMENT_BYTEORDER_FLIP_(op, UInt32) \ - POCO_IMPLEMENT_BYTEORDER_FLIP_(op, Int64) \ - POCO_IMPLEMENT_BYTEORDER_FLIP_(op, UInt64) -#else - #define POCO_IMPLEMENT_BYTEORDER_NOOP(op) \ - POCO_IMPLEMENT_BYTEORDER_NOOP_(op, Int16) \ - POCO_IMPLEMENT_BYTEORDER_NOOP_(op, UInt16) \ - POCO_IMPLEMENT_BYTEORDER_NOOP_(op, Int32) \ - POCO_IMPLEMENT_BYTEORDER_NOOP_(op, UInt32) - #define POCO_IMPLEMENT_BYTEORDER_FLIP(op) \ - POCO_IMPLEMENT_BYTEORDER_FLIP_(op, Int16) \ - POCO_IMPLEMENT_BYTEORDER_FLIP_(op, UInt16) \ - POCO_IMPLEMENT_BYTEORDER_FLIP_(op, Int32) \ - POCO_IMPLEMENT_BYTEORDER_FLIP_(op, UInt32) -#endif - - -#if defined(POCO_ARCH_BIG_ENDIAN) - #define POCO_IMPLEMENT_BYTEORDER_BIG POCO_IMPLEMENT_BYTEORDER_NOOP - #define POCO_IMPLEMENT_BYTEORDER_LIT POCO_IMPLEMENT_BYTEORDER_FLIP -#else - #define POCO_IMPLEMENT_BYTEORDER_BIG POCO_IMPLEMENT_BYTEORDER_FLIP - #define POCO_IMPLEMENT_BYTEORDER_LIT POCO_IMPLEMENT_BYTEORDER_NOOP -#endif - - -POCO_IMPLEMENT_BYTEORDER_BIG(toBigEndian) -POCO_IMPLEMENT_BYTEORDER_BIG(fromBigEndian) -POCO_IMPLEMENT_BYTEORDER_BIG(toNetwork) -POCO_IMPLEMENT_BYTEORDER_BIG(fromNetwork) -POCO_IMPLEMENT_BYTEORDER_LIT(toLittleEndian) -POCO_IMPLEMENT_BYTEORDER_LIT(fromLittleEndian) - - -} // namespace Poco - - -#endif // Foundation_ByteOrder_INCLUDED +// +// ByteOrder.h +// +// $Id: //poco/1.2/Foundation/include/Poco/ByteOrder.h#1 $ +// +// Library: Foundation +// Package: Core +// Module: ByteOrder +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_ByteOrder_INCLUDED +#define Foundation_ByteOrder_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Types.h" + + +namespace Poco { + + +class Foundation_API ByteOrder + /// This class contains a number of static methods + /// to convert between big-endian and little-endian + /// integers of various sizes. +{ +public: + static Int16 flipBytes(Int16 value); + static UInt16 flipBytes(UInt16 value); + static Int32 flipBytes(Int32 value); + static UInt32 flipBytes(UInt32 value); +#if defined(POCO_HAVE_INT64) + static Int64 flipBytes(Int64 value); + static UInt64 flipBytes(UInt64 value); +#endif + + static Int16 toBigEndian(Int16 value); + static UInt16 toBigEndian (UInt16 value); + static Int32 toBigEndian(Int32 value); + static UInt32 toBigEndian (UInt32 value); +#if defined(POCO_HAVE_INT64) + static Int64 toBigEndian(Int64 value); + static UInt64 toBigEndian (UInt64 value); +#endif + + static Int16 fromBigEndian(Int16 value); + static UInt16 fromBigEndian (UInt16 value); + static Int32 fromBigEndian(Int32 value); + static UInt32 fromBigEndian (UInt32 value); +#if defined(POCO_HAVE_INT64) + static Int64 fromBigEndian(Int64 value); + static UInt64 fromBigEndian (UInt64 value); +#endif + + static Int16 toLittleEndian(Int16 value); + static UInt16 toLittleEndian (UInt16 value); + static Int32 toLittleEndian(Int32 value); + static UInt32 toLittleEndian (UInt32 value); +#if defined(POCO_HAVE_INT64) + static Int64 toLittleEndian(Int64 value); + static UInt64 toLittleEndian (UInt64 value); +#endif + + static Int16 fromLittleEndian(Int16 value); + static UInt16 fromLittleEndian (UInt16 value); + static Int32 fromLittleEndian(Int32 value); + static UInt32 fromLittleEndian (UInt32 value); +#if defined(POCO_HAVE_INT64) + static Int64 fromLittleEndian(Int64 value); + static UInt64 fromLittleEndian (UInt64 value); +#endif + + static Int16 toNetwork(Int16 value); + static UInt16 toNetwork (UInt16 value); + static Int32 toNetwork(Int32 value); + static UInt32 toNetwork (UInt32 value); +#if defined(POCO_HAVE_INT64) + static Int64 toNetwork(Int64 value); + static UInt64 toNetwork (UInt64 value); +#endif + + static Int16 fromNetwork(Int16 value); + static UInt16 fromNetwork (UInt16 value); + static Int32 fromNetwork(Int32 value); + static UInt32 fromNetwork (UInt32 value); +#if defined(POCO_HAVE_INT64) + static Int64 fromNetwork(Int64 value); + static UInt64 fromNetwork (UInt64 value); +#endif +}; + + +// +// inlines +// +inline UInt16 ByteOrder::flipBytes(UInt16 value) +{ + return ((value >> 8) & 0x00FF) | ((value << 8) & 0xFF00); +} + + +inline Int16 ByteOrder::flipBytes(Int16 value) +{ + return Int16(flipBytes(UInt16(value))); +} + + +inline UInt32 ByteOrder::flipBytes(UInt32 value) +{ + return ((value >> 24) & 0x000000FF) | ((value >> 8) & 0x0000FF00) + | ((value << 8) & 0x00FF0000) | ((value << 24) & 0xFF000000); +} + + +inline Int32 ByteOrder::flipBytes(Int32 value) +{ + return Int32(flipBytes(UInt32(value))); +} + + +#if defined(POCO_HAVE_INT64) +inline UInt64 ByteOrder::flipBytes(UInt64 value) +{ + UInt32 hi = UInt32(value >> 32); + UInt32 lo = UInt32(value & 0xFFFFFFFF); + return UInt64(flipBytes(hi)) | (UInt64(flipBytes(lo)) << 32); +} + + +inline Int64 ByteOrder::flipBytes(Int64 value) +{ + return Int64(flipBytes(UInt64(value))); +} +#endif // POCO_HAVE_INT64 + + +// +// some macro trickery to automate the method implementation +// +#define POCO_IMPLEMENT_BYTEORDER_NOOP_(op, type) \ + inline type ByteOrder::op(type value) \ + { \ + return value; \ + } +#define POCO_IMPLEMENT_BYTEORDER_FLIP_(op, type) \ + inline type ByteOrder::op(type value) \ + { \ + return flipBytes(value); \ + } + + +#if defined(POCO_HAVE_INT64) + #define POCO_IMPLEMENT_BYTEORDER_NOOP(op) \ + POCO_IMPLEMENT_BYTEORDER_NOOP_(op, Int16) \ + POCO_IMPLEMENT_BYTEORDER_NOOP_(op, UInt16) \ + POCO_IMPLEMENT_BYTEORDER_NOOP_(op, Int32) \ + POCO_IMPLEMENT_BYTEORDER_NOOP_(op, UInt32) \ + POCO_IMPLEMENT_BYTEORDER_NOOP_(op, Int64) \ + POCO_IMPLEMENT_BYTEORDER_NOOP_(op, UInt64) + #define POCO_IMPLEMENT_BYTEORDER_FLIP(op) \ + POCO_IMPLEMENT_BYTEORDER_FLIP_(op, Int16) \ + POCO_IMPLEMENT_BYTEORDER_FLIP_(op, UInt16) \ + POCO_IMPLEMENT_BYTEORDER_FLIP_(op, Int32) \ + POCO_IMPLEMENT_BYTEORDER_FLIP_(op, UInt32) \ + POCO_IMPLEMENT_BYTEORDER_FLIP_(op, Int64) \ + POCO_IMPLEMENT_BYTEORDER_FLIP_(op, UInt64) +#else + #define POCO_IMPLEMENT_BYTEORDER_NOOP(op) \ + POCO_IMPLEMENT_BYTEORDER_NOOP_(op, Int16) \ + POCO_IMPLEMENT_BYTEORDER_NOOP_(op, UInt16) \ + POCO_IMPLEMENT_BYTEORDER_NOOP_(op, Int32) \ + POCO_IMPLEMENT_BYTEORDER_NOOP_(op, UInt32) + #define POCO_IMPLEMENT_BYTEORDER_FLIP(op) \ + POCO_IMPLEMENT_BYTEORDER_FLIP_(op, Int16) \ + POCO_IMPLEMENT_BYTEORDER_FLIP_(op, UInt16) \ + POCO_IMPLEMENT_BYTEORDER_FLIP_(op, Int32) \ + POCO_IMPLEMENT_BYTEORDER_FLIP_(op, UInt32) +#endif + + +#if defined(POCO_ARCH_BIG_ENDIAN) + #define POCO_IMPLEMENT_BYTEORDER_BIG POCO_IMPLEMENT_BYTEORDER_NOOP + #define POCO_IMPLEMENT_BYTEORDER_LIT POCO_IMPLEMENT_BYTEORDER_FLIP +#else + #define POCO_IMPLEMENT_BYTEORDER_BIG POCO_IMPLEMENT_BYTEORDER_FLIP + #define POCO_IMPLEMENT_BYTEORDER_LIT POCO_IMPLEMENT_BYTEORDER_NOOP +#endif + + +POCO_IMPLEMENT_BYTEORDER_BIG(toBigEndian) +POCO_IMPLEMENT_BYTEORDER_BIG(fromBigEndian) +POCO_IMPLEMENT_BYTEORDER_BIG(toNetwork) +POCO_IMPLEMENT_BYTEORDER_BIG(fromNetwork) +POCO_IMPLEMENT_BYTEORDER_LIT(toLittleEndian) +POCO_IMPLEMENT_BYTEORDER_LIT(fromLittleEndian) + + +} // namespace Poco + + +#endif // Foundation_ByteOrder_INCLUDED diff --git a/Foundation/include/Poco/Channel.h b/Foundation/include/Poco/Channel.h index 1d91d73f7..885646236 100644 --- a/Foundation/include/Poco/Channel.h +++ b/Foundation/include/Poco/Channel.h @@ -1,96 +1,96 @@ -// -// Channel.h -// -// $Id: //poco/1.2/Foundation/include/Poco/Channel.h#1 $ -// -// Library: Foundation -// Package: Logging -// Module: Channel -// -// Definition of the Channel class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_Channel_INCLUDED -#define Foundation_Channel_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/Configurable.h" -#include "Poco/Mutex.h" -#include "Poco/RefCountedObject.h" - - -namespace Poco { - - -class Message; - - -class Foundation_API Channel: public Configurable, public RefCountedObject - /// The base class for all Channel classes. - /// - /// Supports reference counting based garbage - /// collection and provides trivial implementations - /// of getProperty() and setProperty(). -{ -public: - Channel(); - /// Creates the channel and initializes - /// the reference count to one. - - virtual void open(); - /// Does whatever is necessary to open the channel. - /// The default implementation does nothing. - - virtual void close(); - /// Does whatever is necessary to close the channel. - /// The default implementation does nothing. - - virtual void log(const Message& msg) = 0; - /// Logs the given message to the channel. Must be - /// overridden by subclasses. - /// - /// If the channel has not been opened yet, the log() - /// method will open it. - - void setProperty(const std::string& name, const std::string& value); - /// Throws a PropertyNotSupportedException. - - std::string getProperty(const std::string& name) const; - /// Throws a PropertyNotSupportedException. - -protected: - virtual ~Channel(); -}; - - -} // namespace Poco - - -#endif // Foundation_Channel_INCLUDED +// +// Channel.h +// +// $Id: //poco/1.2/Foundation/include/Poco/Channel.h#1 $ +// +// Library: Foundation +// Package: Logging +// Module: Channel +// +// Definition of the Channel class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_Channel_INCLUDED +#define Foundation_Channel_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Configurable.h" +#include "Poco/Mutex.h" +#include "Poco/RefCountedObject.h" + + +namespace Poco { + + +class Message; + + +class Foundation_API Channel: public Configurable, public RefCountedObject + /// The base class for all Channel classes. + /// + /// Supports reference counting based garbage + /// collection and provides trivial implementations + /// of getProperty() and setProperty(). +{ +public: + Channel(); + /// Creates the channel and initializes + /// the reference count to one. + + virtual void open(); + /// Does whatever is necessary to open the channel. + /// The default implementation does nothing. + + virtual void close(); + /// Does whatever is necessary to close the channel. + /// The default implementation does nothing. + + virtual void log(const Message& msg) = 0; + /// Logs the given message to the channel. Must be + /// overridden by subclasses. + /// + /// If the channel has not been opened yet, the log() + /// method will open it. + + void setProperty(const std::string& name, const std::string& value); + /// Throws a PropertyNotSupportedException. + + std::string getProperty(const std::string& name) const; + /// Throws a PropertyNotSupportedException. + +protected: + virtual ~Channel(); +}; + + +} // namespace Poco + + +#endif // Foundation_Channel_INCLUDED diff --git a/Foundation/include/Poco/ClassLibrary.h b/Foundation/include/Poco/ClassLibrary.h index 7ab7f278e..89c463cf6 100644 --- a/Foundation/include/Poco/ClassLibrary.h +++ b/Foundation/include/Poco/ClassLibrary.h @@ -1,104 +1,104 @@ -// -// ClassLibrary.h -// -// $Id: //poco/1.2/Foundation/include/Poco/ClassLibrary.h#1 $ -// -// Library: Foundation -// Package: SharedLibrary -// Module: ClassLoader -// -// Definitions for class libraries. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_ClassLibrary_INCLUDED -#define Foundation_ClassLibrary_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/Manifest.h" -#include - - -#if defined(_WIN32) - #define POCO_LIBRARY_API __declspec(dllexport) -#else - #define POCO_LIBRARY_API -#endif - - -// -// the entry point for every class library -// -extern "C" -{ - bool POCO_LIBRARY_API pocoBuildManifest(Poco::ManifestBase* pManifest); - void POCO_LIBRARY_API pocoInitializeLibrary(); - void POCO_LIBRARY_API pocoUninitializeLibrary(); -} - - -// -// Macros to automatically implement pocoBuildManifest -// -// usage: -// -// POCO_BEGIN_MANIFEST(MyBaseClass) -// POCO_EXPORT_CLASS(MyFirstClass) -// POCO_EXPORT_CLASS(MySecondClass) -// ... -// POCO_END_MANIFEST -// -#define POCO_BEGIN_MANIFEST(base) \ - bool pocoBuildManifest(Poco::ManifestBase* pManifest_) \ - { \ - typedef base _Base; \ - typedef Poco::Manifest<_Base> _Manifest; \ - std::string requiredType(typeid(_Manifest).name()); \ - std::string actualType(pManifest_->className()); \ - if (requiredType == actualType) \ - { \ - Poco::Manifest<_Base>* pManifest = static_cast<_Manifest*>(pManifest_); - - -#define POCO_END_MANIFEST \ - return true; \ - } \ - else return false; \ - } - - -#define POCO_EXPORT_CLASS(cls) \ - pManifest->insert(new Poco::MetaObject(#cls)); - - -#define POCO_EXPORT_SINGLETON(cls) \ - pManifest->insert(new Poco::MetaSingleton(#cls)); - - -#endif // Foundation_ClassLibrary_INCLUDED +// +// ClassLibrary.h +// +// $Id: //poco/1.2/Foundation/include/Poco/ClassLibrary.h#1 $ +// +// Library: Foundation +// Package: SharedLibrary +// Module: ClassLoader +// +// Definitions for class libraries. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_ClassLibrary_INCLUDED +#define Foundation_ClassLibrary_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Manifest.h" +#include + + +#if defined(_WIN32) + #define POCO_LIBRARY_API __declspec(dllexport) +#else + #define POCO_LIBRARY_API +#endif + + +// +// the entry point for every class library +// +extern "C" +{ + bool POCO_LIBRARY_API pocoBuildManifest(Poco::ManifestBase* pManifest); + void POCO_LIBRARY_API pocoInitializeLibrary(); + void POCO_LIBRARY_API pocoUninitializeLibrary(); +} + + +// +// Macros to automatically implement pocoBuildManifest +// +// usage: +// +// POCO_BEGIN_MANIFEST(MyBaseClass) +// POCO_EXPORT_CLASS(MyFirstClass) +// POCO_EXPORT_CLASS(MySecondClass) +// ... +// POCO_END_MANIFEST +// +#define POCO_BEGIN_MANIFEST(base) \ + bool pocoBuildManifest(Poco::ManifestBase* pManifest_) \ + { \ + typedef base _Base; \ + typedef Poco::Manifest<_Base> _Manifest; \ + std::string requiredType(typeid(_Manifest).name()); \ + std::string actualType(pManifest_->className()); \ + if (requiredType == actualType) \ + { \ + Poco::Manifest<_Base>* pManifest = static_cast<_Manifest*>(pManifest_); + + +#define POCO_END_MANIFEST \ + return true; \ + } \ + else return false; \ + } + + +#define POCO_EXPORT_CLASS(cls) \ + pManifest->insert(new Poco::MetaObject(#cls)); + + +#define POCO_EXPORT_SINGLETON(cls) \ + pManifest->insert(new Poco::MetaSingleton(#cls)); + + +#endif // Foundation_ClassLibrary_INCLUDED diff --git a/Foundation/include/Poco/ClassLoader.h b/Foundation/include/Poco/ClassLoader.h index d7bd564cf..99498f2ed 100644 --- a/Foundation/include/Poco/ClassLoader.h +++ b/Foundation/include/Poco/ClassLoader.h @@ -1,358 +1,358 @@ -// -// ClassLoader.h -// -// $Id: //poco/1.2/Foundation/include/Poco/ClassLoader.h#1 $ -// -// Library: Foundation -// Package: SharedLibrary -// Module: ClassLoader -// -// Definition of the ClassLoader class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_ClassLoader_INCLUDED -#define Foundation_ClassLoader_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/MetaObject.h" -#include "Poco/Manifest.h" -#include "Poco/SharedLibrary.h" -#include "Poco/Mutex.h" -#include "Poco/Exception.h" -#include - - -namespace Poco { - - -template -class ClassLoader - /// The ClassLoader loads C++ classes from shared libraries - /// at runtime. It must be instantiated with a root class - /// of the loadable classes. - /// For a class to be loadable from a library, the library - /// must provide a Manifest of all the classes it contains. - /// The Manifest for a shared library can be easily built - /// with the help of the macros in the header file - /// "Foundation/ClassLibrary.h". -{ -public: - typedef AbstractMetaObject Meta; - typedef Manifest Manif; - typedef void (*InitializeLibraryFunc)(); - typedef void (*UninitializeLibraryFunc)(); - typedef bool (*BuildManifestFunc)(ManifestBase*); - - struct LibraryInfo - { - SharedLibrary* pLibrary; - const Manif* pManifest; - int refCount; - }; - typedef std::map LibraryMap; - - class Iterator - /// The ClassLoader's very own iterator class. - { - public: - typedef std::pair Pair; - - Iterator(const typename LibraryMap::const_iterator& it) - { - _it = it; - } - Iterator(const Iterator& it) - { - _it = it._it; - } - ~Iterator() - { - } - Iterator& operator = (const Iterator& it) - { - _it = it._it; - return *this; - } - inline bool operator == (const Iterator& it) const - { - return _it == it._it; - } - inline bool operator != (const Iterator& it) const - { - return _it != it._it; - } - Iterator& operator ++ () // prefix - { - ++_it; - return *this; - } - Iterator operator ++ (int) // postfix - { - Iterator result(_it); - ++_it; - return result; - } - inline const Pair* operator * () const - { - _pair.first = _it->first; - _pair.second = _it->second.pManifest; - return &_pair; - } - inline const Pair* operator -> () const - { - _pair.first = _it->first; - _pair.second = _it->second.pManifest; - return &_pair; - } - - private: - typename LibraryMap::const_iterator _it; - mutable Pair _pair; - }; - - ClassLoader() - /// Creates the ClassLoader. - { - } - - virtual ~ClassLoader() - /// Destroys the ClassLoader. - { - for (typename LibraryMap::const_iterator it = _map.begin(); it != _map.end(); ++it) - { - delete it->second.pLibrary; - delete it->second.pManifest; - } - } - - void loadLibrary(const std::string& path) - /// Loads a library from the given path. Does nothing - /// if the library is already loaded. - /// Throws a LibraryLoadException if the library - /// cannot be loaded or does not have a Manifest. - /// If the library exports a function named "pocoInitializeLibrary", - /// this function is executed. - /// If called multiple times for the same library, - /// the number of calls to unloadLibrary() must be the same - /// for the library to become unloaded. - { - FastMutex::ScopedLock lock(_mutex); - - typename LibraryMap::iterator it = _map.find(path); - if (it == _map.end()) - { - LibraryInfo li; - li.pLibrary = new SharedLibrary(path); - li.pManifest = new Manif(); - li.refCount = 1; - try - { - if (li.pLibrary->hasSymbol("pocoInitializeLibrary")) - { - InitializeLibraryFunc initializeLibrary = (InitializeLibraryFunc) li.pLibrary->getSymbol("pocoInitializeLibrary"); - initializeLibrary(); - } - if (li.pLibrary->hasSymbol("pocoBuildManifest")) - { - BuildManifestFunc buildManifest = (BuildManifestFunc) li.pLibrary->getSymbol("pocoBuildManifest"); - if (buildManifest(const_cast(li.pManifest))) - _map[path] = li; - else - throw LibraryLoadException(std::string("Manifest class mismatch in ") + path); - } - else throw LibraryLoadException(std::string("No manifest in ") + path); - } - catch (...) - { - delete li.pLibrary; - delete li.pManifest; - throw; - } - } - else - { - ++it->second.refCount; - } - } - - void unloadLibrary(const std::string& path) - /// Unloads the given library. - /// Be extremely cautious when unloading shared libraries. - /// If objects from the library are still referenced somewhere, - /// a total crash is very likely. - /// If the library exports a function named "pocoUninitializeLibrary", - /// this function is executed before it is unloaded. - /// If loadLibrary() has been called multiple times for the same - /// library, the number of calls to unloadLibrary() must be the same - /// for the library to become unloaded. - { - FastMutex::ScopedLock lock(_mutex); - - typename LibraryMap::iterator it = _map.find(path); - if (it != _map.end()) - { - if (--it->second.refCount == 0) - { - if (it->second.pLibrary->hasSymbol("pocoUninitializeLibrary")) - { - UninitializeLibraryFunc uninitializeLibrary = (UninitializeLibraryFunc) it->second.pLibrary->getSymbol("pocoUninitializeLibrary"); - uninitializeLibrary(); - } - delete it->second.pManifest; - it->second.pLibrary->unload(); - delete it->second.pLibrary; - _map.erase(it); - } - } - else throw NotFoundException(path); - } - - const Meta* findClass(const std::string& className) const - /// Returns a pointer to the MetaObject for the given - /// class, or a null pointer if the class is not known. - { - FastMutex::ScopedLock lock(_mutex); - - for (typename LibraryMap::const_iterator it = _map.begin(); it != _map.end(); ++it) - { - const Manif* pManif = it->second.pManifest; - typename Manif::Iterator itm = pManif->find(className); - if (itm != pManif->end()) - return *itm; - } - return 0; - } - - const Meta& classFor(const std::string& className) const - /// Returns a reference to the MetaObject for the given - /// class. Throws a NotFoundException if the class - /// is not known. - { - const Meta* pMeta = findClass(className); - if (pMeta) - return *pMeta; - else - throw NotFoundException(className); - } - - Base* create(const std::string& className) const - /// Creates an instance of the given class. - /// Throws a NotFoundException if the class - /// is not known. - { - return classFor(className).create(); - } - - Base& instance(const std::string& className) const - /// Returns a reference to the sole instance of - /// the given class. The class must be a singleton, - /// otherwise an InvalidAccessException will be thrown. - /// Throws a NotFoundException if the class - /// is not known. - { - return classFor(className).instance(); - } - - bool canCreate(const std::string& className) const - /// Returns true if create() can create new instances - /// of the class. - { - return classFor(className).canCreate(); - } - - void destroy(const std::string& className, Base* pObject) const - /// Destroys the object pObject points to. - /// Does nothing if object is not found. - { - classFor(className).destroy(pObject); - } - - bool isAutoDelete(const std::string& className, Base* pObject) const - /// Returns true if the object is automatically - /// deleted by its meta object. - { - return classFor(className).isAutoDelete(pObject); - } - - const Manif* findManifest(const std::string& path) const - /// Returns a pointer to the Manifest for the given - /// library, or a null pointer if the library has not been loaded. - { - FastMutex::ScopedLock lock(_mutex); - - typename LibraryMap::const_iterator it = _map.find(path); - if (it != _map.end()) - return it->second.pManifest; - else - return 0; - } - - const Manif& manifestFor(const std::string& path) const - /// Returns a reference to the Manifest for the given library - /// Throws a NotFoundException if the library has not been loaded. - { - const Manif* pManif = findManifest(path); - if (pManif) - return *pManif; - else - throw NotFoundException(path); - } - - bool isLibraryLoaded(const std::string& path) const - /// Returns true if the library with the given name - /// has already been loaded. - { - return findManifest(path) != 0; - } - - Iterator begin() const - { - FastMutex::ScopedLock lock(_mutex); - - return Iterator(_map.begin()); - } - - Iterator end() const - { - FastMutex::ScopedLock lock(_mutex); - - return Iterator(_map.end()); - } - -private: - LibraryMap _map; - mutable FastMutex _mutex; -}; - - -} // namespace Poco - - -#endif // Foundation_ClassLoader_INCLUDED +// +// ClassLoader.h +// +// $Id: //poco/1.2/Foundation/include/Poco/ClassLoader.h#1 $ +// +// Library: Foundation +// Package: SharedLibrary +// Module: ClassLoader +// +// Definition of the ClassLoader class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_ClassLoader_INCLUDED +#define Foundation_ClassLoader_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/MetaObject.h" +#include "Poco/Manifest.h" +#include "Poco/SharedLibrary.h" +#include "Poco/Mutex.h" +#include "Poco/Exception.h" +#include + + +namespace Poco { + + +template +class ClassLoader + /// The ClassLoader loads C++ classes from shared libraries + /// at runtime. It must be instantiated with a root class + /// of the loadable classes. + /// For a class to be loadable from a library, the library + /// must provide a Manifest of all the classes it contains. + /// The Manifest for a shared library can be easily built + /// with the help of the macros in the header file + /// "Foundation/ClassLibrary.h". +{ +public: + typedef AbstractMetaObject Meta; + typedef Manifest Manif; + typedef void (*InitializeLibraryFunc)(); + typedef void (*UninitializeLibraryFunc)(); + typedef bool (*BuildManifestFunc)(ManifestBase*); + + struct LibraryInfo + { + SharedLibrary* pLibrary; + const Manif* pManifest; + int refCount; + }; + typedef std::map LibraryMap; + + class Iterator + /// The ClassLoader's very own iterator class. + { + public: + typedef std::pair Pair; + + Iterator(const typename LibraryMap::const_iterator& it) + { + _it = it; + } + Iterator(const Iterator& it) + { + _it = it._it; + } + ~Iterator() + { + } + Iterator& operator = (const Iterator& it) + { + _it = it._it; + return *this; + } + inline bool operator == (const Iterator& it) const + { + return _it == it._it; + } + inline bool operator != (const Iterator& it) const + { + return _it != it._it; + } + Iterator& operator ++ () // prefix + { + ++_it; + return *this; + } + Iterator operator ++ (int) // postfix + { + Iterator result(_it); + ++_it; + return result; + } + inline const Pair* operator * () const + { + _pair.first = _it->first; + _pair.second = _it->second.pManifest; + return &_pair; + } + inline const Pair* operator -> () const + { + _pair.first = _it->first; + _pair.second = _it->second.pManifest; + return &_pair; + } + + private: + typename LibraryMap::const_iterator _it; + mutable Pair _pair; + }; + + ClassLoader() + /// Creates the ClassLoader. + { + } + + virtual ~ClassLoader() + /// Destroys the ClassLoader. + { + for (typename LibraryMap::const_iterator it = _map.begin(); it != _map.end(); ++it) + { + delete it->second.pLibrary; + delete it->second.pManifest; + } + } + + void loadLibrary(const std::string& path) + /// Loads a library from the given path. Does nothing + /// if the library is already loaded. + /// Throws a LibraryLoadException if the library + /// cannot be loaded or does not have a Manifest. + /// If the library exports a function named "pocoInitializeLibrary", + /// this function is executed. + /// If called multiple times for the same library, + /// the number of calls to unloadLibrary() must be the same + /// for the library to become unloaded. + { + FastMutex::ScopedLock lock(_mutex); + + typename LibraryMap::iterator it = _map.find(path); + if (it == _map.end()) + { + LibraryInfo li; + li.pLibrary = new SharedLibrary(path); + li.pManifest = new Manif(); + li.refCount = 1; + try + { + if (li.pLibrary->hasSymbol("pocoInitializeLibrary")) + { + InitializeLibraryFunc initializeLibrary = (InitializeLibraryFunc) li.pLibrary->getSymbol("pocoInitializeLibrary"); + initializeLibrary(); + } + if (li.pLibrary->hasSymbol("pocoBuildManifest")) + { + BuildManifestFunc buildManifest = (BuildManifestFunc) li.pLibrary->getSymbol("pocoBuildManifest"); + if (buildManifest(const_cast(li.pManifest))) + _map[path] = li; + else + throw LibraryLoadException(std::string("Manifest class mismatch in ") + path); + } + else throw LibraryLoadException(std::string("No manifest in ") + path); + } + catch (...) + { + delete li.pLibrary; + delete li.pManifest; + throw; + } + } + else + { + ++it->second.refCount; + } + } + + void unloadLibrary(const std::string& path) + /// Unloads the given library. + /// Be extremely cautious when unloading shared libraries. + /// If objects from the library are still referenced somewhere, + /// a total crash is very likely. + /// If the library exports a function named "pocoUninitializeLibrary", + /// this function is executed before it is unloaded. + /// If loadLibrary() has been called multiple times for the same + /// library, the number of calls to unloadLibrary() must be the same + /// for the library to become unloaded. + { + FastMutex::ScopedLock lock(_mutex); + + typename LibraryMap::iterator it = _map.find(path); + if (it != _map.end()) + { + if (--it->second.refCount == 0) + { + if (it->second.pLibrary->hasSymbol("pocoUninitializeLibrary")) + { + UninitializeLibraryFunc uninitializeLibrary = (UninitializeLibraryFunc) it->second.pLibrary->getSymbol("pocoUninitializeLibrary"); + uninitializeLibrary(); + } + delete it->second.pManifest; + it->second.pLibrary->unload(); + delete it->second.pLibrary; + _map.erase(it); + } + } + else throw NotFoundException(path); + } + + const Meta* findClass(const std::string& className) const + /// Returns a pointer to the MetaObject for the given + /// class, or a null pointer if the class is not known. + { + FastMutex::ScopedLock lock(_mutex); + + for (typename LibraryMap::const_iterator it = _map.begin(); it != _map.end(); ++it) + { + const Manif* pManif = it->second.pManifest; + typename Manif::Iterator itm = pManif->find(className); + if (itm != pManif->end()) + return *itm; + } + return 0; + } + + const Meta& classFor(const std::string& className) const + /// Returns a reference to the MetaObject for the given + /// class. Throws a NotFoundException if the class + /// is not known. + { + const Meta* pMeta = findClass(className); + if (pMeta) + return *pMeta; + else + throw NotFoundException(className); + } + + Base* create(const std::string& className) const + /// Creates an instance of the given class. + /// Throws a NotFoundException if the class + /// is not known. + { + return classFor(className).create(); + } + + Base& instance(const std::string& className) const + /// Returns a reference to the sole instance of + /// the given class. The class must be a singleton, + /// otherwise an InvalidAccessException will be thrown. + /// Throws a NotFoundException if the class + /// is not known. + { + return classFor(className).instance(); + } + + bool canCreate(const std::string& className) const + /// Returns true if create() can create new instances + /// of the class. + { + return classFor(className).canCreate(); + } + + void destroy(const std::string& className, Base* pObject) const + /// Destroys the object pObject points to. + /// Does nothing if object is not found. + { + classFor(className).destroy(pObject); + } + + bool isAutoDelete(const std::string& className, Base* pObject) const + /// Returns true if the object is automatically + /// deleted by its meta object. + { + return classFor(className).isAutoDelete(pObject); + } + + const Manif* findManifest(const std::string& path) const + /// Returns a pointer to the Manifest for the given + /// library, or a null pointer if the library has not been loaded. + { + FastMutex::ScopedLock lock(_mutex); + + typename LibraryMap::const_iterator it = _map.find(path); + if (it != _map.end()) + return it->second.pManifest; + else + return 0; + } + + const Manif& manifestFor(const std::string& path) const + /// Returns a reference to the Manifest for the given library + /// Throws a NotFoundException if the library has not been loaded. + { + const Manif* pManif = findManifest(path); + if (pManif) + return *pManif; + else + throw NotFoundException(path); + } + + bool isLibraryLoaded(const std::string& path) const + /// Returns true if the library with the given name + /// has already been loaded. + { + return findManifest(path) != 0; + } + + Iterator begin() const + { + FastMutex::ScopedLock lock(_mutex); + + return Iterator(_map.begin()); + } + + Iterator end() const + { + FastMutex::ScopedLock lock(_mutex); + + return Iterator(_map.end()); + } + +private: + LibraryMap _map; + mutable FastMutex _mutex; +}; + + +} // namespace Poco + + +#endif // Foundation_ClassLoader_INCLUDED diff --git a/Foundation/include/Poco/CompareFunctions.h b/Foundation/include/Poco/CompareFunctions.h index 8da3cb5de..60b2d71f3 100644 --- a/Foundation/include/Poco/CompareFunctions.h +++ b/Foundation/include/Poco/CompareFunctions.h @@ -1,63 +1,63 @@ -// -// CompareFunctions.h -// -// $Id: //poco/1.2/Foundation/include/Poco/CompareFunctions.h#1 $ -// -// Library: Foundation -// Package: Events -// Module: CompareFunctions -// -// Compare operators for the NotificationStrategies. -// -// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_CompareFunctions_INCLUDED -#define Foundation_CompareFunctions_INCLUDED - - -#include "Poco/Foundation.h" -#include - - -namespace Poco { - - -template -struct p_less: std::binary_function -{ - bool operator () (const T* const & x, const T* const & y) const - { - return *x < *y; - } -}; - - -} // namespace Poco - - -#endif +// +// CompareFunctions.h +// +// $Id: //poco/1.2/Foundation/include/Poco/CompareFunctions.h#1 $ +// +// Library: Foundation +// Package: Events +// Module: CompareFunctions +// +// Compare operators for the NotificationStrategies. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_CompareFunctions_INCLUDED +#define Foundation_CompareFunctions_INCLUDED + + +#include "Poco/Foundation.h" +#include + + +namespace Poco { + + +template +struct p_less: std::binary_function +{ + bool operator () (const T* const & x, const T* const & y) const + { + return *x < *y; + } +}; + + +} // namespace Poco + + +#endif diff --git a/Foundation/include/Poco/Config.h b/Foundation/include/Poco/Config.h index 9790308a8..2c7717e53 100644 --- a/Foundation/include/Poco/Config.h +++ b/Foundation/include/Poco/Config.h @@ -1,55 +1,55 @@ -// -// Config.h -// -// $Id: //poco/1.2/Foundation/include/Poco/Config.h#2 $ -// -// Library: Foundation -// Package: Core -// Module: Foundation -// -// Feature configuration for the POCO libraries. -// -// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_Config_INCLUDED -#define Foundation_Config_INCLUDED - - -// Define to enable Windows Unicode (UTF-8) support. -// #define POCO_WIN32_UTF8 - - -// Define to disable FPEnvironment support -// #define POCO_NO_FPENVIRONMENT - - -// Define if std::wstring is not available -// #define POCO_NO_WSTRING - - -#endif // Foundation_Config_INCLUDED +// +// Config.h +// +// $Id: //poco/1.2/Foundation/include/Poco/Config.h#2 $ +// +// Library: Foundation +// Package: Core +// Module: Foundation +// +// Feature configuration for the POCO libraries. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_Config_INCLUDED +#define Foundation_Config_INCLUDED + + +// Define to enable Windows Unicode (UTF-8) support. +// #define POCO_WIN32_UTF8 + + +// Define to disable FPEnvironment support +// #define POCO_NO_FPENVIRONMENT + + +// Define if std::wstring is not available +// #define POCO_NO_WSTRING + + +#endif // Foundation_Config_INCLUDED diff --git a/Foundation/include/Poco/Configurable.h b/Foundation/include/Poco/Configurable.h index 7a7a0d8e9..b368820ac 100644 --- a/Foundation/include/Poco/Configurable.h +++ b/Foundation/include/Poco/Configurable.h @@ -1,92 +1,92 @@ -// -// Configurable.h -// -// $Id: //poco/1.2/Foundation/include/Poco/Configurable.h#2 $ -// -// Library: Foundation -// Package: Logging -// Module: Configurable -// -// Definition of the Configurable class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_Configurable_INCLUDED -#define Foundation_Configurable_INCLUDED - - -#include "Poco/Foundation.h" - - -namespace Poco { - - -class Foundation_API Configurable - /// A simple interface that defines - /// getProperty() and setProperty() methods. - /// - /// This interface is implemented by Formatter and - /// Channel and is used to configure arbitrary - /// channels and formatters. - /// - /// A property is basically a name-value pair. For - /// simplicity, both names and values are strings. - /// Every property controls a certain aspect of a - /// Formatter or Channel. For example, the PatternFormatter's - /// formatting pattern is set via a property. - /// - /// NOTE: The following property names are use internally - /// by the logging framework and must not be used by - /// channels or formatters: - /// - class - /// - pattern (Channel) - /// - formatter (Channel) -{ -public: - Configurable(); - /// Creates the Configurable. - - virtual ~Configurable(); - /// Destroys the Configurable. - - virtual void setProperty(const std::string& name, const std::string& value) = 0; - /// Sets the property with the given name to the given value. - /// If a property with the given name is not supported, a - /// PropertyNotSupportedException is thrown. - - virtual std::string getProperty(const std::string& name) const = 0; - /// Returns the value of the property with the given name. - /// If a property with the given name is not supported, a - /// PropertyNotSupportedException is thrown. -}; - - -} // namespace Poco - - -#endif // Foundation_Configurable_INCLUDED +// +// Configurable.h +// +// $Id: //poco/1.2/Foundation/include/Poco/Configurable.h#2 $ +// +// Library: Foundation +// Package: Logging +// Module: Configurable +// +// Definition of the Configurable class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_Configurable_INCLUDED +#define Foundation_Configurable_INCLUDED + + +#include "Poco/Foundation.h" + + +namespace Poco { + + +class Foundation_API Configurable + /// A simple interface that defines + /// getProperty() and setProperty() methods. + /// + /// This interface is implemented by Formatter and + /// Channel and is used to configure arbitrary + /// channels and formatters. + /// + /// A property is basically a name-value pair. For + /// simplicity, both names and values are strings. + /// Every property controls a certain aspect of a + /// Formatter or Channel. For example, the PatternFormatter's + /// formatting pattern is set via a property. + /// + /// NOTE: The following property names are use internally + /// by the logging framework and must not be used by + /// channels or formatters: + /// - class + /// - pattern (Channel) + /// - formatter (Channel) +{ +public: + Configurable(); + /// Creates the Configurable. + + virtual ~Configurable(); + /// Destroys the Configurable. + + virtual void setProperty(const std::string& name, const std::string& value) = 0; + /// Sets the property with the given name to the given value. + /// If a property with the given name is not supported, a + /// PropertyNotSupportedException is thrown. + + virtual std::string getProperty(const std::string& name) const = 0; + /// Returns the value of the property with the given name. + /// If a property with the given name is not supported, a + /// PropertyNotSupportedException is thrown. +}; + + +} // namespace Poco + + +#endif // Foundation_Configurable_INCLUDED diff --git a/Foundation/include/Poco/ConsoleChannel.h b/Foundation/include/Poco/ConsoleChannel.h index fb436b752..4ac5cc16a 100644 --- a/Foundation/include/Poco/ConsoleChannel.h +++ b/Foundation/include/Poco/ConsoleChannel.h @@ -1,89 +1,89 @@ -// -// ConsoleChannel.h -// -// $Id: //poco/1.2/Foundation/include/Poco/ConsoleChannel.h#1 $ -// -// Library: Foundation -// Package: Logging -// Module: ConsoleChannel -// -// Definition of the ConsoleChannel class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_ConsoleChannel_INCLUDED -#define Foundation_ConsoleChannel_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/Channel.h" -#include "Poco/Mutex.h" -#include - - -namespace Poco { - - -class Foundation_API ConsoleChannel: public Channel - /// A channel that writes to an ostream. - /// - /// Only the message's text is written, followed - /// by a newline. - /// - /// Chain this channel to a FormattingChannel with an - /// appropriate Formatter to control what is contained - /// in the text. - /// - /// Similar to StreamChannel, except that a static - /// mutex is used to protect against multiple - /// console channels concurrently writing to the - /// same stream. -{ -public: - ConsoleChannel(); - /// Creates the channel and attached std::clog. - - ConsoleChannel(std::ostream& str); - /// Creates the channel. - - void log(const Message& msg); - /// Logs the given message to the channel's stream. - -protected: - ~ConsoleChannel(); - -private: - std::ostream& _str; - static FastMutex _mutex; -}; - - -} // namespace Poco - - -#endif // Foundation_ConsoleChannel_INCLUDED +// +// ConsoleChannel.h +// +// $Id: //poco/1.2/Foundation/include/Poco/ConsoleChannel.h#1 $ +// +// Library: Foundation +// Package: Logging +// Module: ConsoleChannel +// +// Definition of the ConsoleChannel class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_ConsoleChannel_INCLUDED +#define Foundation_ConsoleChannel_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Channel.h" +#include "Poco/Mutex.h" +#include + + +namespace Poco { + + +class Foundation_API ConsoleChannel: public Channel + /// A channel that writes to an ostream. + /// + /// Only the message's text is written, followed + /// by a newline. + /// + /// Chain this channel to a FormattingChannel with an + /// appropriate Formatter to control what is contained + /// in the text. + /// + /// Similar to StreamChannel, except that a static + /// mutex is used to protect against multiple + /// console channels concurrently writing to the + /// same stream. +{ +public: + ConsoleChannel(); + /// Creates the channel and attached std::clog. + + ConsoleChannel(std::ostream& str); + /// Creates the channel. + + void log(const Message& msg); + /// Logs the given message to the channel's stream. + +protected: + ~ConsoleChannel(); + +private: + std::ostream& _str; + static FastMutex _mutex; +}; + + +} // namespace Poco + + +#endif // Foundation_ConsoleChannel_INCLUDED diff --git a/Foundation/include/Poco/CountingStream.h b/Foundation/include/Poco/CountingStream.h index 042db5d3d..704880153 100644 --- a/Foundation/include/Poco/CountingStream.h +++ b/Foundation/include/Poco/CountingStream.h @@ -1,241 +1,241 @@ -// -// CountingStream.h -// -// $Id: //poco/1.2/Foundation/include/Poco/CountingStream.h#1 $ -// -// Library: Foundation -// Package: Streams -// Module: CountingStream -// -// Definition of the CountingStreamBuf, CountingInputStream and CountingOutputStream classes. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_CountingStream_INCLUDED -#define Foundation_CountingStream_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/UnbufferedStreamBuf.h" -#include -#include - - -namespace Poco { - - -class Foundation_API CountingStreamBuf: public UnbufferedStreamBuf - /// This stream buffer counts all characters and lines - /// going through it. -{ -public: - CountingStreamBuf(); - /// Creates an unconnected CountingStreamBuf. - - CountingStreamBuf(std::istream& istr); - /// Creates the CountingStreamBuf and connects it - /// to the given input stream. - - CountingStreamBuf(std::ostream& ostr); - /// Creates the CountingStreamBuf and connects it - /// to the given output stream. - - ~CountingStreamBuf(); - /// Destroys the CountingStream. - - int chars() const; - /// Returns the total number of characters. - - int lines() const; - /// Returns the total number of lines. - - int pos() const; - /// Returns the number of characters on the current line. - - void reset(); - /// Resets all counters. - - void setCurrentLineNumber(int line); - /// Sets the current line number. - /// - /// This is mainly useful when parsing C/C++ - /// preprocessed source code containing #line directives. - - int getCurrentLineNumber() const; - /// Returns the current line number (same as lines()). - -protected: - int readFromDevice(); - int writeToDevice(char c); - -private: - std::istream* _pIstr; - std::ostream* _pOstr; - int _chars; - int _lines; - int _pos; -}; - - -class Foundation_API CountingIOS: public virtual std::ios - /// The base class for CountingInputStream and CountingOutputStream. - /// - /// This class is needed to ensure the correct initialization - /// order of the stream buffer and base classes. -{ -public: - CountingIOS(); - /// Creates the basic stream and leaves it unconnected. - - CountingIOS(std::istream& istr); - /// Creates the basic stream and connects it - /// to the given input stream. - - CountingIOS(std::ostream& ostr); - /// Creates the basic stream and connects it - /// to the given output stream. - - ~CountingIOS(); - /// Destroys the stream. - - int chars() const; - /// Returns the total number of characters. - - int lines() const; - /// Returns the total number of lines. - - int pos() const; - /// Returns the number of characters on the current line. - - void reset(); - /// Resets all counters. - - void setCurrentLineNumber(int line); - /// Sets the current line number. - /// - /// This is mainly useful when parsing C/C++ - /// preprocessed source code containing #line directives. - - int getCurrentLineNumber() const; - /// Returns the current line number (same as lines()). - - CountingStreamBuf* rdbuf(); - /// Returns a pointer to the underlying streambuf. - -protected: - CountingStreamBuf _buf; -}; - - -class Foundation_API CountingInputStream: public CountingIOS, public std::istream - /// This stream counts all characters and lines - /// going through it. This is useful for lexers and parsers - /// that need to determine the current position in the stream. -{ -public: - CountingInputStream(std::istream& istr); - /// Creates the CountingInputStream and connects it - /// to the given input stream. - - ~CountingInputStream(); - /// Destroys the stream. -}; - - -class Foundation_API CountingOutputStream: public CountingIOS, public std::ostream - /// This stream counts all characters and lines - /// going through it. -{ -public: - CountingOutputStream(); - /// Creates an unconnected CountingOutputStream. - - CountingOutputStream(std::ostream& ostr); - /// Creates the CountingOutputStream and connects it - /// to the given input stream. - - ~CountingOutputStream(); - /// Destroys the CountingOutputStream. -}; - - -// -// inlines -// -inline int CountingStreamBuf::chars() const -{ - return _chars; -} - - -inline int CountingStreamBuf::lines() const -{ - return _lines; -} - - -inline int CountingStreamBuf::pos() const -{ - return _pos; -} - - -inline int CountingStreamBuf::getCurrentLineNumber() const -{ - return _lines; -} - - -inline int CountingIOS::chars() const -{ - return _buf.chars(); -} - - -inline int CountingIOS::lines() const -{ - return _buf.lines(); -} - - -inline int CountingIOS::pos() const -{ - return _buf.pos(); -} - - -inline int CountingIOS::getCurrentLineNumber() const -{ - return _buf.getCurrentLineNumber(); -} - - -} // namespace Poco - - -#endif // Foundation_CountingStream_INCLUDED +// +// CountingStream.h +// +// $Id: //poco/1.2/Foundation/include/Poco/CountingStream.h#1 $ +// +// Library: Foundation +// Package: Streams +// Module: CountingStream +// +// Definition of the CountingStreamBuf, CountingInputStream and CountingOutputStream classes. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_CountingStream_INCLUDED +#define Foundation_CountingStream_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/UnbufferedStreamBuf.h" +#include +#include + + +namespace Poco { + + +class Foundation_API CountingStreamBuf: public UnbufferedStreamBuf + /// This stream buffer counts all characters and lines + /// going through it. +{ +public: + CountingStreamBuf(); + /// Creates an unconnected CountingStreamBuf. + + CountingStreamBuf(std::istream& istr); + /// Creates the CountingStreamBuf and connects it + /// to the given input stream. + + CountingStreamBuf(std::ostream& ostr); + /// Creates the CountingStreamBuf and connects it + /// to the given output stream. + + ~CountingStreamBuf(); + /// Destroys the CountingStream. + + int chars() const; + /// Returns the total number of characters. + + int lines() const; + /// Returns the total number of lines. + + int pos() const; + /// Returns the number of characters on the current line. + + void reset(); + /// Resets all counters. + + void setCurrentLineNumber(int line); + /// Sets the current line number. + /// + /// This is mainly useful when parsing C/C++ + /// preprocessed source code containing #line directives. + + int getCurrentLineNumber() const; + /// Returns the current line number (same as lines()). + +protected: + int readFromDevice(); + int writeToDevice(char c); + +private: + std::istream* _pIstr; + std::ostream* _pOstr; + int _chars; + int _lines; + int _pos; +}; + + +class Foundation_API CountingIOS: public virtual std::ios + /// The base class for CountingInputStream and CountingOutputStream. + /// + /// This class is needed to ensure the correct initialization + /// order of the stream buffer and base classes. +{ +public: + CountingIOS(); + /// Creates the basic stream and leaves it unconnected. + + CountingIOS(std::istream& istr); + /// Creates the basic stream and connects it + /// to the given input stream. + + CountingIOS(std::ostream& ostr); + /// Creates the basic stream and connects it + /// to the given output stream. + + ~CountingIOS(); + /// Destroys the stream. + + int chars() const; + /// Returns the total number of characters. + + int lines() const; + /// Returns the total number of lines. + + int pos() const; + /// Returns the number of characters on the current line. + + void reset(); + /// Resets all counters. + + void setCurrentLineNumber(int line); + /// Sets the current line number. + /// + /// This is mainly useful when parsing C/C++ + /// preprocessed source code containing #line directives. + + int getCurrentLineNumber() const; + /// Returns the current line number (same as lines()). + + CountingStreamBuf* rdbuf(); + /// Returns a pointer to the underlying streambuf. + +protected: + CountingStreamBuf _buf; +}; + + +class Foundation_API CountingInputStream: public CountingIOS, public std::istream + /// This stream counts all characters and lines + /// going through it. This is useful for lexers and parsers + /// that need to determine the current position in the stream. +{ +public: + CountingInputStream(std::istream& istr); + /// Creates the CountingInputStream and connects it + /// to the given input stream. + + ~CountingInputStream(); + /// Destroys the stream. +}; + + +class Foundation_API CountingOutputStream: public CountingIOS, public std::ostream + /// This stream counts all characters and lines + /// going through it. +{ +public: + CountingOutputStream(); + /// Creates an unconnected CountingOutputStream. + + CountingOutputStream(std::ostream& ostr); + /// Creates the CountingOutputStream and connects it + /// to the given input stream. + + ~CountingOutputStream(); + /// Destroys the CountingOutputStream. +}; + + +// +// inlines +// +inline int CountingStreamBuf::chars() const +{ + return _chars; +} + + +inline int CountingStreamBuf::lines() const +{ + return _lines; +} + + +inline int CountingStreamBuf::pos() const +{ + return _pos; +} + + +inline int CountingStreamBuf::getCurrentLineNumber() const +{ + return _lines; +} + + +inline int CountingIOS::chars() const +{ + return _buf.chars(); +} + + +inline int CountingIOS::lines() const +{ + return _buf.lines(); +} + + +inline int CountingIOS::pos() const +{ + return _buf.pos(); +} + + +inline int CountingIOS::getCurrentLineNumber() const +{ + return _buf.getCurrentLineNumber(); +} + + +} // namespace Poco + + +#endif // Foundation_CountingStream_INCLUDED diff --git a/Foundation/include/Poco/DateTime.h b/Foundation/include/Poco/DateTime.h index 3091b888b..a5af83203 100644 --- a/Foundation/include/Poco/DateTime.h +++ b/Foundation/include/Poco/DateTime.h @@ -1,427 +1,427 @@ -// -// DateTime.h -// -// $Id: //poco/1.2/Foundation/include/Poco/DateTime.h#1 $ -// -// Library: Foundation -// Package: DateTime -// Module: DateTime -// -// Definition of the DateTime class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_DateTime_INCLUDED -#define Foundation_DateTime_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/Timestamp.h" -#include "Poco/Timespan.h" - - -namespace Poco { - - -class Foundation_API DateTime - /// This class represents an instant in time, expressed - /// in years, months, days, hours, minutes, seconds - /// and milliseconds based on the Gregorian calendar. - /// The class is mainly useful for conversions between - /// UTC, Julian day and Gregorian calendar dates. - /// - /// Conversion calculations are based on algorithms - /// collected and described by Peter Baum at - /// http://vsg.cape.com/~pbaum/date/date0.htm - /// - /// Internally, this class stores a date/time in two - /// forms (UTC and broken down) for performance reasons. Only use - /// this class for conversions between date/time representations. - /// Use the Timestamp class for everything else. - /// - /// Notes: - /// * Zero is a valid year (in accordance with ISO 8601 and astronomical year numbering) - /// * Year zero (0) is a leap year - /// * Negative years (years preceding 1 BC) are not supported - /// - /// For more information, please see: - /// * http://en.wikipedia.org/wiki/Gregorian_Calendar - /// * http://en.wikipedia.org/wiki/Julian_day - /// * http://en.wikipedia.org/wiki/UTC - /// * http://en.wikipedia.org/wiki/ISO_8601 -{ -public: - enum Months - /// Symbolic names for month numbers (1 to 12). - { - JANUARY = 1, - FEBRUARY, - MARCH, - APRIL, - MAY, - JUNE, - JULY, - AUGUST, - SEPTEMBER, - OCTOBER, - NOVEMBER, - DECEMBER - }; - - enum DaysOfWeek - /// Symbolic names for week day numbers (0 to 6). - { - SUNDAY = 0, - MONDAY, - TUESDAY, - WEDNESDAY, - THURSDAY, - FRIDAY, - SATURDAY - }; - - DateTime(); - /// Creates a DateTime for the current date and time. - - DateTime(const Timestamp& timestamp); - /// Creates a DateTime for the date and time given in - /// a Timestamp. - - DateTime(int year, int month, int day, int hour = 0, int minute = 0, int second = 0, int millisecond = 0, int microsecond = 0); - /// Creates a DateTime for the given Gregorian date and time. - /// * year is from 0 to 9999. - /// * month is from 1 to 12. - /// * day is from 1 to 31. - /// * hour is from 0 to 23. - /// * minute is from 0 to 59. - /// * second is from 0 to 59. - /// * millisecond is from 0 to 999. - /// * microsecond is from 0 to 999. - - DateTime(double julianDay); - /// Creates a DateTime for the given Julian day. - - DateTime(Timestamp::UtcTimeVal utcTime, Timestamp::TimeDiff diff); - /// Creates a DateTime from an UtcTimeVal and a TimeDiff. - /// - /// Mainly used internally by DateTime and friends. - - DateTime(const DateTime& dateTime); - /// Copy constructor. Creates the DateTime from another one. - - ~DateTime(); - /// Destroys the DateTime. - - DateTime& operator = (const DateTime& dateTime); - /// Assigns another DateTime. - - DateTime& operator = (const Timestamp& timestamp); - /// Assigns a Timestamp. - - DateTime& operator = (double julianDay); - /// Assigns a Julian day. - - DateTime& assign(int year, int month, int day, int hour = 0, int minute = 0, int second = 0, int millisecond = 0, int microseconds = 0); - /// Assigns a Gregorian date and time. - /// * year is from 0 to 9999. - /// * month is from 1 to 12. - /// * day is from 1 to 31. - /// * hour is from 0 to 23. - /// * minute is from 0 to 59. - /// * second is from 0 to 59. - /// * millisecond is from 0 to 999. - /// * microsecond is from 0 to 999. - - void swap(DateTime& dateTime); - /// Swaps the DateTime with another one. - - int year() const; - /// Returns the year. - - int month() const; - /// Returns the month (1 to 12). - - int week(int firstDayOfWeek = MONDAY) const; - /// Returns the week number within the year. - /// FirstDayOfWeek should be either SUNDAY (0) or MONDAY (1). - /// The returned week number will be from 0 to 53. Week number 1 is the week - /// containing January 4. This is in accordance to ISO 8601. - /// - /// The following example assumes that firstDayOfWeek is MONDAY. For 2005, which started - /// on a Saturday, week 1 will be the week starting on Monday, January 3. - /// January 1 and 2 will fall within week 0 (or the last week of the previous year). - /// - /// For 2007, which starts on a Monday, week 1 will be the week startung on Monday, January 1. - /// There will be no week 0 in 2007. - - int day() const; - /// Returns the day witin the month (1 to 31). - - int dayOfWeek() const; - /// Returns the weekday (0 to 6, where - /// 0 = Sunday, 1 = Monday, ..., 6 = Saturday). - - int dayOfYear() const; - /// Returns the number of the day in the year. - /// January 1 is 1, February 1 is 32, etc. - - int hour() const; - /// Returns the hour (0 to 23). - - int hourAMPM() const; - /// Returns the hour (0 to 12). - - bool isAM() const; - /// Returns true if hour < 12; - - bool isPM() const; - /// Returns true if hour >= 12. - - int minute() const; - /// Returns the minute (0 to 59). - - int second() const; - /// Returns the second (0 to 59). - - int millisecond() const; - /// Returns the millisecond (0 to 999) - - int microsecond() const; - /// Returns the microsecond (0 to 999) - - double julianDay() const; - /// Returns the julian day for the date and time. - - Timestamp timestamp() const; - /// Returns the date and time expressed as a Timestamp. - - Timestamp::UtcTimeVal utcTime() const; - /// Returns the date and time expressed in UTC-based - /// time. UTC base time is midnight, October 15, 1582. - /// Resolution is 100 nanoseconds. - - bool operator == (const DateTime& dateTime) const; - bool operator != (const DateTime& dateTime) const; - bool operator < (const DateTime& dateTime) const; - bool operator <= (const DateTime& dateTime) const; - bool operator > (const DateTime& dateTime) const; - bool operator >= (const DateTime& dateTime) const; - - DateTime operator + (const Timespan& span) const; - DateTime operator - (const Timespan& span) const; - Timespan operator - (const DateTime& dateTime) const; - DateTime& operator += (const Timespan& span); - DateTime& operator -= (const Timespan& span); - - static bool isLeapYear(int year); - /// Returns true if the given year is a leap year; - /// false otherwise. - - static int daysOfMonth(int year, int month); - /// Returns the number of days in the given month - /// and year. Month is from 1 to 12. - - static bool isValid(int year, int month, int day, int hour = 0, int minute = 0, int second = 0, int millisecond = 0, int microsecond = 0); - /// Checks if the given date and time is valid - /// (all arguments are within a proper range). - /// - /// Returns true if all arguments are valid, false otherwise. - -protected: - static double toJulianDay(Timestamp::UtcTimeVal utcTime); - /// Computes the Julian day for an UTC time. - - static double toJulianDay(int year, int month, int day, int hour = 0, int minute = 0, int second = 0, int millisecond = 0, int microsecond = 0); - /// Computes the Julian day for a gregorian calendar date and time. - /// See , section 2.3.1 for the algorithm. - - static Timestamp::UtcTimeVal toUtcTime(double julianDay); - /// Computes the UTC time for a Julian day. - - void computeGregorian(double julianDay); - /// Computes the Gregorian date for the given Julian day. - /// See , section 3.3.1 for the algorithm. - - void computeDaytime(); - /// Extracts the daytime (hours, minutes, seconds, etc.) from the stored utcTime. - -private: - void checkLimit(short& lower, short& higher, short limit); - void normalize(); - ///utility functions used to correct the overflow in computeGregorian - - Timestamp::UtcTimeVal _utcTime; - short _year; - short _month; - short _day; - short _hour; - short _minute; - short _second; - short _millisecond; - short _microsecond; -}; - - -// -// inlines -// -inline Timestamp DateTime::timestamp() const -{ - return Timestamp::fromUtcTime(_utcTime); -} - - -inline Timestamp::UtcTimeVal DateTime::utcTime() const -{ - return _utcTime; -} - - -inline int DateTime::year() const -{ - return _year; -} - - -inline int DateTime::month() const -{ - return _month; -} - - -inline int DateTime::day() const -{ - return _day; -} - - -inline int DateTime::hour() const -{ - return _hour; -} - - -inline int DateTime::hourAMPM() const -{ - if (_hour < 1) - return 12; - else if (_hour > 12) - return _hour - 12; - else - return _hour; -} - - -inline bool DateTime::isAM() const -{ - return _hour < 12; -} - - -inline bool DateTime::isPM() const -{ - return _hour >= 12; -} - - -inline int DateTime::minute() const -{ - return _minute; -} - - -inline int DateTime::second() const -{ - return _second; -} - - -inline int DateTime::millisecond() const -{ - return _millisecond; -} - - -inline int DateTime::microsecond() const -{ - return _microsecond; -} - - -inline bool DateTime::operator == (const DateTime& dateTime) const -{ - return _utcTime == dateTime._utcTime; -} - - -inline bool DateTime::operator != (const DateTime& dateTime) const -{ - return _utcTime != dateTime._utcTime; -} - - -inline bool DateTime::operator < (const DateTime& dateTime) const -{ - return _utcTime < dateTime._utcTime; -} - - -inline bool DateTime::operator <= (const DateTime& dateTime) const -{ - return _utcTime <= dateTime._utcTime; -} - - -inline bool DateTime::operator > (const DateTime& dateTime) const -{ - return _utcTime > dateTime._utcTime; -} - - -inline bool DateTime::operator >= (const DateTime& dateTime) const -{ - return _utcTime >= dateTime._utcTime; -} - - -inline bool DateTime::isLeapYear(int year) -{ - return (year % 4) == 0 && ((year % 100) != 0 || (year % 400) == 0); -} - - -inline void swap(DateTime& d1, DateTime& d2) -{ - d1.swap(d2); -} - - -} // namespace Poco - - -#endif // Foundation_DateTime_INCLUDED +// +// DateTime.h +// +// $Id: //poco/1.2/Foundation/include/Poco/DateTime.h#1 $ +// +// Library: Foundation +// Package: DateTime +// Module: DateTime +// +// Definition of the DateTime class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_DateTime_INCLUDED +#define Foundation_DateTime_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Timestamp.h" +#include "Poco/Timespan.h" + + +namespace Poco { + + +class Foundation_API DateTime + /// This class represents an instant in time, expressed + /// in years, months, days, hours, minutes, seconds + /// and milliseconds based on the Gregorian calendar. + /// The class is mainly useful for conversions between + /// UTC, Julian day and Gregorian calendar dates. + /// + /// Conversion calculations are based on algorithms + /// collected and described by Peter Baum at + /// http://vsg.cape.com/~pbaum/date/date0.htm + /// + /// Internally, this class stores a date/time in two + /// forms (UTC and broken down) for performance reasons. Only use + /// this class for conversions between date/time representations. + /// Use the Timestamp class for everything else. + /// + /// Notes: + /// * Zero is a valid year (in accordance with ISO 8601 and astronomical year numbering) + /// * Year zero (0) is a leap year + /// * Negative years (years preceding 1 BC) are not supported + /// + /// For more information, please see: + /// * http://en.wikipedia.org/wiki/Gregorian_Calendar + /// * http://en.wikipedia.org/wiki/Julian_day + /// * http://en.wikipedia.org/wiki/UTC + /// * http://en.wikipedia.org/wiki/ISO_8601 +{ +public: + enum Months + /// Symbolic names for month numbers (1 to 12). + { + JANUARY = 1, + FEBRUARY, + MARCH, + APRIL, + MAY, + JUNE, + JULY, + AUGUST, + SEPTEMBER, + OCTOBER, + NOVEMBER, + DECEMBER + }; + + enum DaysOfWeek + /// Symbolic names for week day numbers (0 to 6). + { + SUNDAY = 0, + MONDAY, + TUESDAY, + WEDNESDAY, + THURSDAY, + FRIDAY, + SATURDAY + }; + + DateTime(); + /// Creates a DateTime for the current date and time. + + DateTime(const Timestamp& timestamp); + /// Creates a DateTime for the date and time given in + /// a Timestamp. + + DateTime(int year, int month, int day, int hour = 0, int minute = 0, int second = 0, int millisecond = 0, int microsecond = 0); + /// Creates a DateTime for the given Gregorian date and time. + /// * year is from 0 to 9999. + /// * month is from 1 to 12. + /// * day is from 1 to 31. + /// * hour is from 0 to 23. + /// * minute is from 0 to 59. + /// * second is from 0 to 59. + /// * millisecond is from 0 to 999. + /// * microsecond is from 0 to 999. + + DateTime(double julianDay); + /// Creates a DateTime for the given Julian day. + + DateTime(Timestamp::UtcTimeVal utcTime, Timestamp::TimeDiff diff); + /// Creates a DateTime from an UtcTimeVal and a TimeDiff. + /// + /// Mainly used internally by DateTime and friends. + + DateTime(const DateTime& dateTime); + /// Copy constructor. Creates the DateTime from another one. + + ~DateTime(); + /// Destroys the DateTime. + + DateTime& operator = (const DateTime& dateTime); + /// Assigns another DateTime. + + DateTime& operator = (const Timestamp& timestamp); + /// Assigns a Timestamp. + + DateTime& operator = (double julianDay); + /// Assigns a Julian day. + + DateTime& assign(int year, int month, int day, int hour = 0, int minute = 0, int second = 0, int millisecond = 0, int microseconds = 0); + /// Assigns a Gregorian date and time. + /// * year is from 0 to 9999. + /// * month is from 1 to 12. + /// * day is from 1 to 31. + /// * hour is from 0 to 23. + /// * minute is from 0 to 59. + /// * second is from 0 to 59. + /// * millisecond is from 0 to 999. + /// * microsecond is from 0 to 999. + + void swap(DateTime& dateTime); + /// Swaps the DateTime with another one. + + int year() const; + /// Returns the year. + + int month() const; + /// Returns the month (1 to 12). + + int week(int firstDayOfWeek = MONDAY) const; + /// Returns the week number within the year. + /// FirstDayOfWeek should be either SUNDAY (0) or MONDAY (1). + /// The returned week number will be from 0 to 53. Week number 1 is the week + /// containing January 4. This is in accordance to ISO 8601. + /// + /// The following example assumes that firstDayOfWeek is MONDAY. For 2005, which started + /// on a Saturday, week 1 will be the week starting on Monday, January 3. + /// January 1 and 2 will fall within week 0 (or the last week of the previous year). + /// + /// For 2007, which starts on a Monday, week 1 will be the week startung on Monday, January 1. + /// There will be no week 0 in 2007. + + int day() const; + /// Returns the day witin the month (1 to 31). + + int dayOfWeek() const; + /// Returns the weekday (0 to 6, where + /// 0 = Sunday, 1 = Monday, ..., 6 = Saturday). + + int dayOfYear() const; + /// Returns the number of the day in the year. + /// January 1 is 1, February 1 is 32, etc. + + int hour() const; + /// Returns the hour (0 to 23). + + int hourAMPM() const; + /// Returns the hour (0 to 12). + + bool isAM() const; + /// Returns true if hour < 12; + + bool isPM() const; + /// Returns true if hour >= 12. + + int minute() const; + /// Returns the minute (0 to 59). + + int second() const; + /// Returns the second (0 to 59). + + int millisecond() const; + /// Returns the millisecond (0 to 999) + + int microsecond() const; + /// Returns the microsecond (0 to 999) + + double julianDay() const; + /// Returns the julian day for the date and time. + + Timestamp timestamp() const; + /// Returns the date and time expressed as a Timestamp. + + Timestamp::UtcTimeVal utcTime() const; + /// Returns the date and time expressed in UTC-based + /// time. UTC base time is midnight, October 15, 1582. + /// Resolution is 100 nanoseconds. + + bool operator == (const DateTime& dateTime) const; + bool operator != (const DateTime& dateTime) const; + bool operator < (const DateTime& dateTime) const; + bool operator <= (const DateTime& dateTime) const; + bool operator > (const DateTime& dateTime) const; + bool operator >= (const DateTime& dateTime) const; + + DateTime operator + (const Timespan& span) const; + DateTime operator - (const Timespan& span) const; + Timespan operator - (const DateTime& dateTime) const; + DateTime& operator += (const Timespan& span); + DateTime& operator -= (const Timespan& span); + + static bool isLeapYear(int year); + /// Returns true if the given year is a leap year; + /// false otherwise. + + static int daysOfMonth(int year, int month); + /// Returns the number of days in the given month + /// and year. Month is from 1 to 12. + + static bool isValid(int year, int month, int day, int hour = 0, int minute = 0, int second = 0, int millisecond = 0, int microsecond = 0); + /// Checks if the given date and time is valid + /// (all arguments are within a proper range). + /// + /// Returns true if all arguments are valid, false otherwise. + +protected: + static double toJulianDay(Timestamp::UtcTimeVal utcTime); + /// Computes the Julian day for an UTC time. + + static double toJulianDay(int year, int month, int day, int hour = 0, int minute = 0, int second = 0, int millisecond = 0, int microsecond = 0); + /// Computes the Julian day for a gregorian calendar date and time. + /// See , section 2.3.1 for the algorithm. + + static Timestamp::UtcTimeVal toUtcTime(double julianDay); + /// Computes the UTC time for a Julian day. + + void computeGregorian(double julianDay); + /// Computes the Gregorian date for the given Julian day. + /// See , section 3.3.1 for the algorithm. + + void computeDaytime(); + /// Extracts the daytime (hours, minutes, seconds, etc.) from the stored utcTime. + +private: + void checkLimit(short& lower, short& higher, short limit); + void normalize(); + ///utility functions used to correct the overflow in computeGregorian + + Timestamp::UtcTimeVal _utcTime; + short _year; + short _month; + short _day; + short _hour; + short _minute; + short _second; + short _millisecond; + short _microsecond; +}; + + +// +// inlines +// +inline Timestamp DateTime::timestamp() const +{ + return Timestamp::fromUtcTime(_utcTime); +} + + +inline Timestamp::UtcTimeVal DateTime::utcTime() const +{ + return _utcTime; +} + + +inline int DateTime::year() const +{ + return _year; +} + + +inline int DateTime::month() const +{ + return _month; +} + + +inline int DateTime::day() const +{ + return _day; +} + + +inline int DateTime::hour() const +{ + return _hour; +} + + +inline int DateTime::hourAMPM() const +{ + if (_hour < 1) + return 12; + else if (_hour > 12) + return _hour - 12; + else + return _hour; +} + + +inline bool DateTime::isAM() const +{ + return _hour < 12; +} + + +inline bool DateTime::isPM() const +{ + return _hour >= 12; +} + + +inline int DateTime::minute() const +{ + return _minute; +} + + +inline int DateTime::second() const +{ + return _second; +} + + +inline int DateTime::millisecond() const +{ + return _millisecond; +} + + +inline int DateTime::microsecond() const +{ + return _microsecond; +} + + +inline bool DateTime::operator == (const DateTime& dateTime) const +{ + return _utcTime == dateTime._utcTime; +} + + +inline bool DateTime::operator != (const DateTime& dateTime) const +{ + return _utcTime != dateTime._utcTime; +} + + +inline bool DateTime::operator < (const DateTime& dateTime) const +{ + return _utcTime < dateTime._utcTime; +} + + +inline bool DateTime::operator <= (const DateTime& dateTime) const +{ + return _utcTime <= dateTime._utcTime; +} + + +inline bool DateTime::operator > (const DateTime& dateTime) const +{ + return _utcTime > dateTime._utcTime; +} + + +inline bool DateTime::operator >= (const DateTime& dateTime) const +{ + return _utcTime >= dateTime._utcTime; +} + + +inline bool DateTime::isLeapYear(int year) +{ + return (year % 4) == 0 && ((year % 100) != 0 || (year % 400) == 0); +} + + +inline void swap(DateTime& d1, DateTime& d2) +{ + d1.swap(d2); +} + + +} // namespace Poco + + +#endif // Foundation_DateTime_INCLUDED diff --git a/Foundation/include/Poco/DateTimeFormat.h b/Foundation/include/Poco/DateTimeFormat.h index 4df5285d9..a0952f131 100644 --- a/Foundation/include/Poco/DateTimeFormat.h +++ b/Foundation/include/Poco/DateTimeFormat.h @@ -1,123 +1,123 @@ -// -// DateTimeFormat.h -// -// $Id: //poco/1.2/Foundation/include/Poco/DateTimeFormat.h#1 $ -// -// Library: Foundation -// Package: DateTime -// Module: DateTimeFormat -// -// Definition of the DateTimeFormat class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_DateTimeFormat_INCLUDED -#define Foundation_DateTimeFormat_INCLUDED - - -#include "Poco/Foundation.h" - - -namespace Poco { - - -class Foundation_API DateTimeFormat - /// Definition of date/time formats and various - /// constants used by DateTimeFormatter and DateTimeParser. -{ -public: - // predefined date formats - static const std::string ISO8601_FORMAT; - /// The date/time format defined in the ISO 8601 standard. - /// - /// Examples: - /// 2005-01-01T12:00:00+01:00 - /// 2005-01-01T11:00:00Z - - static const std::string RFC822_FORMAT; - /// The date/time format defined in RFC 822 (obsoleted by RFC 1123). - /// - /// Examples: - /// Sat, 1 Jan 05 12:00:00 +0100 - /// Sat, 1 Jan 05 11:00:00 GMT - - static const std::string RFC1123_FORMAT; - /// The date/time format defined in RFC 1123 (obsoletes RFC 822). - /// - /// Examples: - /// Sat, 1 Jan 2005 12:00:00 +0100 - /// Sat, 1 Jan 2005 11:00:00 GMT - - static const std::string HTTP_FORMAT; - /// The date/time format defined in the HTTP specification (RFC 2616), - /// which is basically a variant of RFC 1036 with a zero-padded day field. - /// - /// Examples: - /// Sat, 01 Jan 2005 12:00:00 +0100 - /// Sat, 01 Jan 2005 11:00:00 GMT - - static const std::string RFC850_FORMAT; - /// The date/time format defined in RFC 850 (obsoleted by RFC 1036). - /// - /// Examples: - /// Saturday, 1-Jan-05 12:00:00 +0100 - /// Saturday, 1-Jan-05 11:00:00 GMT - - static const std::string RFC1036_FORMAT; - /// The date/time format defined in RFC 1036 (obsoletes RFC 850). - /// - /// Examples: - /// Saturday, 1 Jan 05 12:00:00 +0100 - /// Saturday, 1 Jan 05 11:00:00 GMT - - static const std::string ASCTIME_FORMAT; - /// The date/time format produced by the ANSI C asctime() function. - /// - /// Example: - /// Sat Jan 1 12:00:00 2005 - - static const std::string SORTABLE_FORMAT; - /// A simple, sortable date/time format. - /// - /// Example: - /// 2005-01-01 12:00:00 - - - // names used by formatter and parser - static const std::string WEEKDAY_NAMES[7]; - /// English names of week days (Sunday, Monday, Tuesday, ...). - - static const std::string MONTH_NAMES[12]; - /// English names of months (January, February, ...). -}; - - -} // namespace Poco - - -#endif // Foundation_DateTimeFormat_INCLUDED +// +// DateTimeFormat.h +// +// $Id: //poco/1.2/Foundation/include/Poco/DateTimeFormat.h#1 $ +// +// Library: Foundation +// Package: DateTime +// Module: DateTimeFormat +// +// Definition of the DateTimeFormat class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_DateTimeFormat_INCLUDED +#define Foundation_DateTimeFormat_INCLUDED + + +#include "Poco/Foundation.h" + + +namespace Poco { + + +class Foundation_API DateTimeFormat + /// Definition of date/time formats and various + /// constants used by DateTimeFormatter and DateTimeParser. +{ +public: + // predefined date formats + static const std::string ISO8601_FORMAT; + /// The date/time format defined in the ISO 8601 standard. + /// + /// Examples: + /// 2005-01-01T12:00:00+01:00 + /// 2005-01-01T11:00:00Z + + static const std::string RFC822_FORMAT; + /// The date/time format defined in RFC 822 (obsoleted by RFC 1123). + /// + /// Examples: + /// Sat, 1 Jan 05 12:00:00 +0100 + /// Sat, 1 Jan 05 11:00:00 GMT + + static const std::string RFC1123_FORMAT; + /// The date/time format defined in RFC 1123 (obsoletes RFC 822). + /// + /// Examples: + /// Sat, 1 Jan 2005 12:00:00 +0100 + /// Sat, 1 Jan 2005 11:00:00 GMT + + static const std::string HTTP_FORMAT; + /// The date/time format defined in the HTTP specification (RFC 2616), + /// which is basically a variant of RFC 1036 with a zero-padded day field. + /// + /// Examples: + /// Sat, 01 Jan 2005 12:00:00 +0100 + /// Sat, 01 Jan 2005 11:00:00 GMT + + static const std::string RFC850_FORMAT; + /// The date/time format defined in RFC 850 (obsoleted by RFC 1036). + /// + /// Examples: + /// Saturday, 1-Jan-05 12:00:00 +0100 + /// Saturday, 1-Jan-05 11:00:00 GMT + + static const std::string RFC1036_FORMAT; + /// The date/time format defined in RFC 1036 (obsoletes RFC 850). + /// + /// Examples: + /// Saturday, 1 Jan 05 12:00:00 +0100 + /// Saturday, 1 Jan 05 11:00:00 GMT + + static const std::string ASCTIME_FORMAT; + /// The date/time format produced by the ANSI C asctime() function. + /// + /// Example: + /// Sat Jan 1 12:00:00 2005 + + static const std::string SORTABLE_FORMAT; + /// A simple, sortable date/time format. + /// + /// Example: + /// 2005-01-01 12:00:00 + + + // names used by formatter and parser + static const std::string WEEKDAY_NAMES[7]; + /// English names of week days (Sunday, Monday, Tuesday, ...). + + static const std::string MONTH_NAMES[12]; + /// English names of months (January, February, ...). +}; + + +} // namespace Poco + + +#endif // Foundation_DateTimeFormat_INCLUDED diff --git a/Foundation/include/Poco/DateTimeFormatter.h b/Foundation/include/Poco/DateTimeFormatter.h index 14125c986..0ccea5ab2 100644 --- a/Foundation/include/Poco/DateTimeFormatter.h +++ b/Foundation/include/Poco/DateTimeFormatter.h @@ -1,137 +1,137 @@ -// -// DateTimeFormatter.h -// -// $Id: //poco/1.2/Foundation/include/Poco/DateTimeFormatter.h#1 $ -// -// Library: Foundation -// Package: DateTime -// Module: DateTimeFormatter -// -// Definition of the DateTimeFormatter class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_DateTimeFormatter_INCLUDED -#define Foundation_DateTimeFormatter_INCLUDED - - -#include "Poco/Foundation.h" - - -namespace Poco { - - -class DateTime; -class LocalDateTime; -class Timestamp; -class Timespan; - - -class Foundation_API DateTimeFormatter - /// This class converts dates and times into strings, supporting a - /// variety of standard and custom formats. -{ -public: - enum - { - UTC = 0xFFFF /// Special value for timeZoneDifferential denoting UTC. - }; - - static std::string format(const Timestamp& timestamp, const std::string& fmt, int timeZoneDifferential = UTC); - /// Formats the given timestamp according to the given format. - /// The format string is used as a template to format the date and - /// is copied character by character except for the following special characters, - /// which are replaced by the corresponding value. - /// - /// * %w - abbreviated weekday (Mon, Tue, ...) - /// * %W - full weekday (Monday, Tuesday, ...) - /// * %b - abbreviated month (Jan, Feb, ...) - /// * %B - full month (January, February, ...) - /// * %d - zero-padded day of month (01 .. 31) - /// * %e - day of month (1 .. 31) - /// * %f - space-padded day of month ( 1 .. 31) - /// * %m - zero-padded month (01 .. 12) - /// * %n - month (1 .. 12) - /// * %o - space-padded month ( 1 .. 12) - /// * %y - year without century (70) - /// * %Y - year with century (1970) - /// * %H - hour (00 .. 23) - /// * %h - hour (00 .. 12) - /// * %a - am/pm - /// * %A - AM/PM - /// * %M - minute (00 .. 59) - /// * %S - second (00 .. 59) - /// * %i - millisecond (000 .. 999) - /// * %c - centisecond (0 .. 9) - /// * %z - time zone differential in ISO 8601 format (Z or +NN.NN). - /// * %Z - time zone differential in RFC format (GMT or +NNNN) - /// * %% - percent sign - /// - /// Class DateTimeFormat defines format strings for various standard date/time formats. - - static std::string format(const DateTime& dateTime, const std::string& fmt, int timeZoneDifferential = UTC); - /// Formats the given date and time according to the given format. - /// See format(const Timestamp&, const std::string&, int) for more information. - - static std::string format(const LocalDateTime& dateTime, const std::string& fmt); - /// Formats the given local date and time according to the given format. - /// See format(const Timestamp&, const std::string&, int) for more information. - - static std::string format(const Timespan& timespan, const std::string& fmt = "%dd %H:%M:%S.%i"); - /// Formats the given timespan according to the given format. - /// The format string is used as a template to format the date and - /// is copied character by character except for the following special characters, - /// which are replaced by the corresponding value. - /// - /// * %d - days - /// * %H - hours (00 .. 23) - /// * %h - total hours (0 .. n) - /// * %M - minutes (00 .. 59) - /// * %m - total minutes (0 .. n) - /// * %S - seconds (00 .. 59) - /// * %s - total seconds (0 .. n) - /// * %i - milliseconds (000 .. 999) - /// * %c - centisecond (0 .. 9) - /// * %% - percent sign - - static std::string tzdISO(int timeZoneDifferential); - /// Formats the given timezone differential in ISO format. - /// If timeZoneDifferential is UTC, "Z" is returned, - /// otherwise, +HH.MM (or -HH.MM) is returned. - - static std::string tzdRFC(int timeZoneDifferential); - /// Formats the given timezone differential in RFC format. - /// If timeZoneDifferential is UTC, "GMT" is returned, - /// otherwise ++HHMM (or -HHMM) is returned. -}; - - -} // namespace Poco - - -#endif // Foundation_DateTimeFormatter_INCLUDED +// +// DateTimeFormatter.h +// +// $Id: //poco/1.2/Foundation/include/Poco/DateTimeFormatter.h#1 $ +// +// Library: Foundation +// Package: DateTime +// Module: DateTimeFormatter +// +// Definition of the DateTimeFormatter class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_DateTimeFormatter_INCLUDED +#define Foundation_DateTimeFormatter_INCLUDED + + +#include "Poco/Foundation.h" + + +namespace Poco { + + +class DateTime; +class LocalDateTime; +class Timestamp; +class Timespan; + + +class Foundation_API DateTimeFormatter + /// This class converts dates and times into strings, supporting a + /// variety of standard and custom formats. +{ +public: + enum + { + UTC = 0xFFFF /// Special value for timeZoneDifferential denoting UTC. + }; + + static std::string format(const Timestamp& timestamp, const std::string& fmt, int timeZoneDifferential = UTC); + /// Formats the given timestamp according to the given format. + /// The format string is used as a template to format the date and + /// is copied character by character except for the following special characters, + /// which are replaced by the corresponding value. + /// + /// * %w - abbreviated weekday (Mon, Tue, ...) + /// * %W - full weekday (Monday, Tuesday, ...) + /// * %b - abbreviated month (Jan, Feb, ...) + /// * %B - full month (January, February, ...) + /// * %d - zero-padded day of month (01 .. 31) + /// * %e - day of month (1 .. 31) + /// * %f - space-padded day of month ( 1 .. 31) + /// * %m - zero-padded month (01 .. 12) + /// * %n - month (1 .. 12) + /// * %o - space-padded month ( 1 .. 12) + /// * %y - year without century (70) + /// * %Y - year with century (1970) + /// * %H - hour (00 .. 23) + /// * %h - hour (00 .. 12) + /// * %a - am/pm + /// * %A - AM/PM + /// * %M - minute (00 .. 59) + /// * %S - second (00 .. 59) + /// * %i - millisecond (000 .. 999) + /// * %c - centisecond (0 .. 9) + /// * %z - time zone differential in ISO 8601 format (Z or +NN.NN). + /// * %Z - time zone differential in RFC format (GMT or +NNNN) + /// * %% - percent sign + /// + /// Class DateTimeFormat defines format strings for various standard date/time formats. + + static std::string format(const DateTime& dateTime, const std::string& fmt, int timeZoneDifferential = UTC); + /// Formats the given date and time according to the given format. + /// See format(const Timestamp&, const std::string&, int) for more information. + + static std::string format(const LocalDateTime& dateTime, const std::string& fmt); + /// Formats the given local date and time according to the given format. + /// See format(const Timestamp&, const std::string&, int) for more information. + + static std::string format(const Timespan& timespan, const std::string& fmt = "%dd %H:%M:%S.%i"); + /// Formats the given timespan according to the given format. + /// The format string is used as a template to format the date and + /// is copied character by character except for the following special characters, + /// which are replaced by the corresponding value. + /// + /// * %d - days + /// * %H - hours (00 .. 23) + /// * %h - total hours (0 .. n) + /// * %M - minutes (00 .. 59) + /// * %m - total minutes (0 .. n) + /// * %S - seconds (00 .. 59) + /// * %s - total seconds (0 .. n) + /// * %i - milliseconds (000 .. 999) + /// * %c - centisecond (0 .. 9) + /// * %% - percent sign + + static std::string tzdISO(int timeZoneDifferential); + /// Formats the given timezone differential in ISO format. + /// If timeZoneDifferential is UTC, "Z" is returned, + /// otherwise, +HH.MM (or -HH.MM) is returned. + + static std::string tzdRFC(int timeZoneDifferential); + /// Formats the given timezone differential in RFC format. + /// If timeZoneDifferential is UTC, "GMT" is returned, + /// otherwise ++HHMM (or -HHMM) is returned. +}; + + +} // namespace Poco + + +#endif // Foundation_DateTimeFormatter_INCLUDED diff --git a/Foundation/include/Poco/DateTimeParser.h b/Foundation/include/Poco/DateTimeParser.h index 141151466..0cee10a45 100644 --- a/Foundation/include/Poco/DateTimeParser.h +++ b/Foundation/include/Poco/DateTimeParser.h @@ -1,119 +1,119 @@ -// -// DateTimeParser.h -// -// $Id: //poco/1.2/Foundation/include/Poco/DateTimeParser.h#1 $ -// -// Library: Foundation -// Package: DateTime -// Module: DateTimeParser -// -// Definition of the DateTimeParser class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_DateTimeParser_INCLUDED -#define Foundation_DateTimeParser_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/DateTime.h" - - -namespace Poco { - - -class Foundation_API DateTimeParser - /// This class provides a method for parsing dates and times - /// from strings. All parsing methods do their best to - /// parse a meaningful result, even from malformed input - /// strings. - /// - /// Note: When parsing a time in 12-hour (AM/PM) format, the hour - /// (%h) must be parsed before the AM/PM designator (%a, %A), - /// otherwise the AM/PM designator will be ignored. -{ -public: - static void parse(const std::string& fmt, const std::string& str, DateTime& dateTime, int& timeZoneDifferential); - /// Parses a date and time in the given format from the given string. - /// Throws a SyntaxException if the string cannot be successfully parsed. - /// Please see DateTimeFormatter::format() for a description of the format string. - /// Class DateTimeFormat defines format strings for various standard date/time formats. - - static DateTime parse(const std::string& fmt, const std::string& str, int& timeZoneDifferential); - /// Parses a date and time in the given format from the given string. - /// Throws a SyntaxException if the string cannot be successfully parsed. - /// Please see DateTimeFormatter::format() for a description of the format string. - /// Class DateTimeFormat defines format strings for various standard date/time formats. - - static bool tryParse(const std::string& fmt, const std::string& str, DateTime& dateTime, int& timeZoneDifferential); - /// Parses a date and time in the given format from the given string. - /// Returns true if the string has been successfully parsed, false otherwise. - /// Please see DateTimeFormatter::format() for a description of the format string. - /// Class DateTimeFormat defines format strings for various standard date/time formats. - - static void parse(const std::string& str, DateTime& dateTime, int& timeZoneDifferential); - /// Parses a date and time from the given dateTime string. Before parsing, the method - /// examines the dateTime string for a known date/time format. - /// Throws a SyntaxException if the string cannot be successfully parsed. - /// Please see DateTimeFormatter::format() for a description of the format string. - /// Class DateTimeFormat defines format strings for various standard date/time formats. - - static DateTime parse(const std::string& str, int& timeZoneDifferential); - /// Parses a date and time from the given dateTime string. Before parsing, the method - /// examines the dateTime string for a known date/time format. - /// Please see DateTimeFormatter::format() for a description of the format string. - /// Class DateTimeFormat defines format strings for various standard date/time formats. - - static bool tryParse(const std::string& str, DateTime& dateTime, int& timeZoneDifferential); - /// Parses a date and time from the given dateTime string. Before parsing, the method - /// examines the dateTime string for a known date/time format. - /// Please see DateTimeFormatter::format() for a description of the format string. - /// Class DateTimeFormat defines format strings for various standard date/time formats. - - static int parseMonth(std::string::const_iterator& it, const std::string::const_iterator& end); - /// Tries to interpret the given range as a month name. The range must be at least - /// three characters long. - /// Returns the month number (1 .. 12) if the month name is valid. Otherwise throws - /// a SyntaxException. - - static int parseDayOfWeek(std::string::const_iterator& it, const std::string::const_iterator& end); - /// Tries to interpret the given range as a weekday name. The range must be at least - /// three characters long. - /// Returns the weekday number (0 .. 6, where 0 = Synday, 1 = Monday, etc.) if the - /// weekday name is valid. Otherwise throws a SyntaxException. - -protected: - static int parseTZD(std::string::const_iterator& it, const std::string::const_iterator& end); - static int parseAMPM(std::string::const_iterator& it, const std::string::const_iterator& end, int hour); -}; - - -} // namespace Poco - - -#endif // Foundation_DateTimeParser_INCLUDED +// +// DateTimeParser.h +// +// $Id: //poco/1.2/Foundation/include/Poco/DateTimeParser.h#1 $ +// +// Library: Foundation +// Package: DateTime +// Module: DateTimeParser +// +// Definition of the DateTimeParser class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_DateTimeParser_INCLUDED +#define Foundation_DateTimeParser_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/DateTime.h" + + +namespace Poco { + + +class Foundation_API DateTimeParser + /// This class provides a method for parsing dates and times + /// from strings. All parsing methods do their best to + /// parse a meaningful result, even from malformed input + /// strings. + /// + /// Note: When parsing a time in 12-hour (AM/PM) format, the hour + /// (%h) must be parsed before the AM/PM designator (%a, %A), + /// otherwise the AM/PM designator will be ignored. +{ +public: + static void parse(const std::string& fmt, const std::string& str, DateTime& dateTime, int& timeZoneDifferential); + /// Parses a date and time in the given format from the given string. + /// Throws a SyntaxException if the string cannot be successfully parsed. + /// Please see DateTimeFormatter::format() for a description of the format string. + /// Class DateTimeFormat defines format strings for various standard date/time formats. + + static DateTime parse(const std::string& fmt, const std::string& str, int& timeZoneDifferential); + /// Parses a date and time in the given format from the given string. + /// Throws a SyntaxException if the string cannot be successfully parsed. + /// Please see DateTimeFormatter::format() for a description of the format string. + /// Class DateTimeFormat defines format strings for various standard date/time formats. + + static bool tryParse(const std::string& fmt, const std::string& str, DateTime& dateTime, int& timeZoneDifferential); + /// Parses a date and time in the given format from the given string. + /// Returns true if the string has been successfully parsed, false otherwise. + /// Please see DateTimeFormatter::format() for a description of the format string. + /// Class DateTimeFormat defines format strings for various standard date/time formats. + + static void parse(const std::string& str, DateTime& dateTime, int& timeZoneDifferential); + /// Parses a date and time from the given dateTime string. Before parsing, the method + /// examines the dateTime string for a known date/time format. + /// Throws a SyntaxException if the string cannot be successfully parsed. + /// Please see DateTimeFormatter::format() for a description of the format string. + /// Class DateTimeFormat defines format strings for various standard date/time formats. + + static DateTime parse(const std::string& str, int& timeZoneDifferential); + /// Parses a date and time from the given dateTime string. Before parsing, the method + /// examines the dateTime string for a known date/time format. + /// Please see DateTimeFormatter::format() for a description of the format string. + /// Class DateTimeFormat defines format strings for various standard date/time formats. + + static bool tryParse(const std::string& str, DateTime& dateTime, int& timeZoneDifferential); + /// Parses a date and time from the given dateTime string. Before parsing, the method + /// examines the dateTime string for a known date/time format. + /// Please see DateTimeFormatter::format() for a description of the format string. + /// Class DateTimeFormat defines format strings for various standard date/time formats. + + static int parseMonth(std::string::const_iterator& it, const std::string::const_iterator& end); + /// Tries to interpret the given range as a month name. The range must be at least + /// three characters long. + /// Returns the month number (1 .. 12) if the month name is valid. Otherwise throws + /// a SyntaxException. + + static int parseDayOfWeek(std::string::const_iterator& it, const std::string::const_iterator& end); + /// Tries to interpret the given range as a weekday name. The range must be at least + /// three characters long. + /// Returns the weekday number (0 .. 6, where 0 = Synday, 1 = Monday, etc.) if the + /// weekday name is valid. Otherwise throws a SyntaxException. + +protected: + static int parseTZD(std::string::const_iterator& it, const std::string::const_iterator& end); + static int parseAMPM(std::string::const_iterator& it, const std::string::const_iterator& end, int hour); +}; + + +} // namespace Poco + + +#endif // Foundation_DateTimeParser_INCLUDED diff --git a/Foundation/include/Poco/Debugger.h b/Foundation/include/Poco/Debugger.h index 62d488409..b12bbfd64 100644 --- a/Foundation/include/Poco/Debugger.h +++ b/Foundation/include/Poco/Debugger.h @@ -1,95 +1,95 @@ -// -// Debugger.h -// -// $Id: //poco/1.2/Foundation/include/Poco/Debugger.h#1 $ -// -// Library: Foundation -// Package: Core -// Module: Debugger -// -// Definition of the Debugger class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_Debugger_INCLUDED -#define Foundation_Debugger_INCLUDED - - -#include "Poco/Foundation.h" - - -namespace Poco { - - -class Foundation_API Debugger - /// The Debugger class provides an interface to the debugger. - /// The presence of a debugger can be checked for, - /// messages can be written to the debugger's log window - /// and a break into the debugger can be enforced. - /// The methods only work if the program is compiled - /// in debug mode (the macro _DEBUG is defined). -{ -public: - static bool isAvailable(); - /// Returns true if a debugger is available, false otherwise. - /// On Windows, this function uses the IsDebuggerPresent() - /// function. - /// On Unix, this function returns true if the environment - /// variable POCO_ENABLE_DEBUGGER is set. - /// On OpenVMS, this function always returns true in debug, - /// mode, false otherwise. - - static void message(const std::string& msg); - /// Writes a message to the debugger log, if available, otherwise to - /// standard error output. - - static void message(const std::string& msg, const char* file, int line); - /// Writes a message to the debugger log, if available, otherwise to - /// standard error output. - - static void enter(); - /// Breaks into the debugger, if it is available. - /// On Windows, this is done using the DebugBreak() function. - /// On Unix, the SIGINT signal is raised. - /// On OpenVMS, the SS$_DEBUG signal is raised. - - static void enter(const std::string& msg); - /// Writes a debug message to the debugger log and breaks into it. - - static void enter(const std::string& msg, const char* file, int line); - /// Writes a debug message to the debugger log and breaks into it. - - static void enter(const char* file, int line); - /// Writes a debug message to the debugger log and breaks into it. -}; - - -} // namespace Poco - - -#endif // Foundation_Debugger_INCLUDED +// +// Debugger.h +// +// $Id: //poco/1.2/Foundation/include/Poco/Debugger.h#1 $ +// +// Library: Foundation +// Package: Core +// Module: Debugger +// +// Definition of the Debugger class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_Debugger_INCLUDED +#define Foundation_Debugger_INCLUDED + + +#include "Poco/Foundation.h" + + +namespace Poco { + + +class Foundation_API Debugger + /// The Debugger class provides an interface to the debugger. + /// The presence of a debugger can be checked for, + /// messages can be written to the debugger's log window + /// and a break into the debugger can be enforced. + /// The methods only work if the program is compiled + /// in debug mode (the macro _DEBUG is defined). +{ +public: + static bool isAvailable(); + /// Returns true if a debugger is available, false otherwise. + /// On Windows, this function uses the IsDebuggerPresent() + /// function. + /// On Unix, this function returns true if the environment + /// variable POCO_ENABLE_DEBUGGER is set. + /// On OpenVMS, this function always returns true in debug, + /// mode, false otherwise. + + static void message(const std::string& msg); + /// Writes a message to the debugger log, if available, otherwise to + /// standard error output. + + static void message(const std::string& msg, const char* file, int line); + /// Writes a message to the debugger log, if available, otherwise to + /// standard error output. + + static void enter(); + /// Breaks into the debugger, if it is available. + /// On Windows, this is done using the DebugBreak() function. + /// On Unix, the SIGINT signal is raised. + /// On OpenVMS, the SS$_DEBUG signal is raised. + + static void enter(const std::string& msg); + /// Writes a debug message to the debugger log and breaks into it. + + static void enter(const std::string& msg, const char* file, int line); + /// Writes a debug message to the debugger log and breaks into it. + + static void enter(const char* file, int line); + /// Writes a debug message to the debugger log and breaks into it. +}; + + +} // namespace Poco + + +#endif // Foundation_Debugger_INCLUDED diff --git a/Foundation/include/Poco/DefaultStrategy.h b/Foundation/include/Poco/DefaultStrategy.h index cd068063d..ba96bcf72 100644 --- a/Foundation/include/Poco/DefaultStrategy.h +++ b/Foundation/include/Poco/DefaultStrategy.h @@ -1,154 +1,154 @@ -// -// DefaultStrategy.h -// -// $Id: //poco/1.2/Foundation/include/Poco/DefaultStrategy.h#1 $ -// -// Library: Foundation -// Package: Events -// Module: DefaultStrategy -// -// Implementation of the DefaultStrategy template. -// -// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_DefaultStrategy_INCLUDED -#define Foundation_DefaultStrategy_INCLUDED - - -#include "Poco/NotificationStrategy.h" -#include -#include -#include - - -namespace Poco { - - -template -class DefaultStrategy: public NotificationStrategy - /// Default notification strategy. Allows one observer - /// to register exactly once. The observer must provide an - /// < (less-than) operator. -{ -public: - typedef std::set Delegates; - typedef typename Delegates::iterator Iterator; - typedef typename Delegates::const_iterator ConstIterator; - -public: - DefaultStrategy() - { - } - - DefaultStrategy(const DefaultStrategy& s) - { - operator = (s); - } - - ~DefaultStrategy() - { - clear(); - } - - void notify(const void* sender, TArgs& arguments) - { - std::vector delMe; - - for (Iterator it = _observers.begin(); it != _observers.end(); it++) - { - if (!(*it)->notify(sender, arguments)) - { - // schedule for deletion - delMe.push_back(it); - } - } - - while (!delMe.empty()) - { - typename std::vector::iterator vit = delMe.end(); - --vit; - delete **vit; - _observers.erase(*vit); - delMe.pop_back(); - } - } - - void add(const TDelegate& delegate) - { - Iterator it = _observers.find(const_cast(&delegate)); - if (it != _observers.end()) - { - delete *it; - _observers.erase(it); - } - std::auto_ptr pDelegate(delegate.clone()); - bool tmp = _observers.insert(pDelegate.get()).second; - poco_assert (tmp); - pDelegate.release(); - } - - void remove(const TDelegate& delegate) - { - Iterator it = _observers.find(const_cast(&delegate)); - if (it != _observers.end()) - { - delete *it; - _observers.erase(it); - } - } - - DefaultStrategy& operator = (const DefaultStrategy& s) - { - if (this != &s) - { - for (ConstIterator it = s._observers.begin(); it != s._observers.end(); ++it) - { - add(**it); - } - } - return *this; - } - - void clear() - { - for (Iterator it = _observers.begin(); it != _observers.end(); ++it) - { - delete *it; - } - _observers.clear(); - } - -protected: - Delegates _observers; -}; - - -} // namespace Poco - - -#endif +// +// DefaultStrategy.h +// +// $Id: //poco/1.2/Foundation/include/Poco/DefaultStrategy.h#1 $ +// +// Library: Foundation +// Package: Events +// Module: DefaultStrategy +// +// Implementation of the DefaultStrategy template. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_DefaultStrategy_INCLUDED +#define Foundation_DefaultStrategy_INCLUDED + + +#include "Poco/NotificationStrategy.h" +#include +#include +#include + + +namespace Poco { + + +template +class DefaultStrategy: public NotificationStrategy + /// Default notification strategy. Allows one observer + /// to register exactly once. The observer must provide an + /// < (less-than) operator. +{ +public: + typedef std::set Delegates; + typedef typename Delegates::iterator Iterator; + typedef typename Delegates::const_iterator ConstIterator; + +public: + DefaultStrategy() + { + } + + DefaultStrategy(const DefaultStrategy& s) + { + operator = (s); + } + + ~DefaultStrategy() + { + clear(); + } + + void notify(const void* sender, TArgs& arguments) + { + std::vector delMe; + + for (Iterator it = _observers.begin(); it != _observers.end(); it++) + { + if (!(*it)->notify(sender, arguments)) + { + // schedule for deletion + delMe.push_back(it); + } + } + + while (!delMe.empty()) + { + typename std::vector::iterator vit = delMe.end(); + --vit; + delete **vit; + _observers.erase(*vit); + delMe.pop_back(); + } + } + + void add(const TDelegate& delegate) + { + Iterator it = _observers.find(const_cast(&delegate)); + if (it != _observers.end()) + { + delete *it; + _observers.erase(it); + } + std::auto_ptr pDelegate(delegate.clone()); + bool tmp = _observers.insert(pDelegate.get()).second; + poco_assert (tmp); + pDelegate.release(); + } + + void remove(const TDelegate& delegate) + { + Iterator it = _observers.find(const_cast(&delegate)); + if (it != _observers.end()) + { + delete *it; + _observers.erase(it); + } + } + + DefaultStrategy& operator = (const DefaultStrategy& s) + { + if (this != &s) + { + for (ConstIterator it = s._observers.begin(); it != s._observers.end(); ++it) + { + add(**it); + } + } + return *this; + } + + void clear() + { + for (Iterator it = _observers.begin(); it != _observers.end(); ++it) + { + delete *it; + } + _observers.clear(); + } + +protected: + Delegates _observers; +}; + + +} // namespace Poco + + +#endif diff --git a/Foundation/include/Poco/DeflatingStream.h b/Foundation/include/Poco/DeflatingStream.h index c3eebce88..326a57c39 100644 --- a/Foundation/include/Poco/DeflatingStream.h +++ b/Foundation/include/Poco/DeflatingStream.h @@ -1,141 +1,141 @@ -// -// DeflatingStream.h -// -// $Id: //poco/1.2/Foundation/include/Poco/DeflatingStream.h#1 $ -// -// Library: Foundation -// Package: Streams -// Module: ZLibStream -// -// Definition of the DeflatingStream class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_DeflatingStream_INCLUDED -#define Foundation_DeflatingStream_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/BufferedStreamBuf.h" -#include -#include -#include "Poco/zlib.h" - - -namespace Poco { - - -class Foundation_API DeflatingStreamBuf: public BufferedStreamBuf - /// This is the streambuf class used by DeflatingInputStream and DeflatingOutputStream. - /// The actual work is delegated to zlib 1.2.1 (see http://www.gzip.org). - /// Both zlib (deflate) streams and gzip streams are supported. - /// Output streams should always call close() to ensure - /// proper completion of compression. - /// A compression level (0 to 9) can be specified in the constructor. -{ -public: - enum StreamType - { - STREAM_ZLIB, - STREAM_GZIP - }; - - DeflatingStreamBuf(std::istream& istr, StreamType type, int level); - DeflatingStreamBuf(std::ostream& ostr, StreamType type, int level); - ~DeflatingStreamBuf(); - int close(); - -protected: - int readFromDevice(char* buffer, std::streamsize length); - int writeToDevice(const char* buffer, std::streamsize length); - -private: - enum - { - STREAM_BUFFER_SIZE = 1024, - DEFLATE_BUFFER_SIZE = 32768 - }; - - std::istream* _pIstr; - std::ostream* _pOstr; - char* _buffer; - z_stream _zstr; - bool _eof; -}; - - -class Foundation_API DeflatingIOS: public virtual std::ios - /// The base class for DeflatingOutputStream and DeflatingInputStream. - /// - /// This class is needed to ensure the correct initialization - /// order of the stream buffer and base classes. -{ -public: - DeflatingIOS(std::ostream& ostr, DeflatingStreamBuf::StreamType type = DeflatingStreamBuf::STREAM_ZLIB, int level = Z_DEFAULT_COMPRESSION); - DeflatingIOS(std::istream& istr, DeflatingStreamBuf::StreamType type = DeflatingStreamBuf::STREAM_ZLIB, int level = Z_DEFAULT_COMPRESSION); - ~DeflatingIOS(); - DeflatingStreamBuf* rdbuf(); - -protected: - DeflatingStreamBuf _buf; -}; - - -class Foundation_API DeflatingOutputStream: public DeflatingIOS, public std::ostream - /// This stream compresses all data passing through it - /// using zlib's deflate algorithm. - /// After all data has been written to the stream, close() - /// must be called to ensure completion of compression. - /// Example: - /// std::ofstream ostr("data.gz", std::ios::binary); - /// DeflatingOutputStream deflater(ostr, DeflatingStreamBuf::STREAM_GZIP); - /// deflater << "Hello, world!" << std::endl; - /// deflater.close(); - /// ostr.close(); -{ -public: - DeflatingOutputStream(std::ostream& ostr, DeflatingStreamBuf::StreamType type = DeflatingStreamBuf::STREAM_ZLIB, int level = Z_DEFAULT_COMPRESSION); - ~DeflatingOutputStream(); - int close(); -}; - - -class Foundation_API DeflatingInputStream: public DeflatingIOS, public std::istream - /// This stream compresses all data passing through it - /// using zlib's deflate algorithm. -{ -public: - DeflatingInputStream(std::istream& istr, DeflatingStreamBuf::StreamType type = DeflatingStreamBuf::STREAM_ZLIB, int level = Z_DEFAULT_COMPRESSION); - ~DeflatingInputStream(); -}; - - -} // namespace Poco - - -#endif // Foundation_DeflatingStream_INCLUDED +// +// DeflatingStream.h +// +// $Id: //poco/1.2/Foundation/include/Poco/DeflatingStream.h#1 $ +// +// Library: Foundation +// Package: Streams +// Module: ZLibStream +// +// Definition of the DeflatingStream class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_DeflatingStream_INCLUDED +#define Foundation_DeflatingStream_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/BufferedStreamBuf.h" +#include +#include +#include "Poco/zlib.h" + + +namespace Poco { + + +class Foundation_API DeflatingStreamBuf: public BufferedStreamBuf + /// This is the streambuf class used by DeflatingInputStream and DeflatingOutputStream. + /// The actual work is delegated to zlib 1.2.1 (see http://www.gzip.org). + /// Both zlib (deflate) streams and gzip streams are supported. + /// Output streams should always call close() to ensure + /// proper completion of compression. + /// A compression level (0 to 9) can be specified in the constructor. +{ +public: + enum StreamType + { + STREAM_ZLIB, + STREAM_GZIP + }; + + DeflatingStreamBuf(std::istream& istr, StreamType type, int level); + DeflatingStreamBuf(std::ostream& ostr, StreamType type, int level); + ~DeflatingStreamBuf(); + int close(); + +protected: + int readFromDevice(char* buffer, std::streamsize length); + int writeToDevice(const char* buffer, std::streamsize length); + +private: + enum + { + STREAM_BUFFER_SIZE = 1024, + DEFLATE_BUFFER_SIZE = 32768 + }; + + std::istream* _pIstr; + std::ostream* _pOstr; + char* _buffer; + z_stream _zstr; + bool _eof; +}; + + +class Foundation_API DeflatingIOS: public virtual std::ios + /// The base class for DeflatingOutputStream and DeflatingInputStream. + /// + /// This class is needed to ensure the correct initialization + /// order of the stream buffer and base classes. +{ +public: + DeflatingIOS(std::ostream& ostr, DeflatingStreamBuf::StreamType type = DeflatingStreamBuf::STREAM_ZLIB, int level = Z_DEFAULT_COMPRESSION); + DeflatingIOS(std::istream& istr, DeflatingStreamBuf::StreamType type = DeflatingStreamBuf::STREAM_ZLIB, int level = Z_DEFAULT_COMPRESSION); + ~DeflatingIOS(); + DeflatingStreamBuf* rdbuf(); + +protected: + DeflatingStreamBuf _buf; +}; + + +class Foundation_API DeflatingOutputStream: public DeflatingIOS, public std::ostream + /// This stream compresses all data passing through it + /// using zlib's deflate algorithm. + /// After all data has been written to the stream, close() + /// must be called to ensure completion of compression. + /// Example: + /// std::ofstream ostr("data.gz", std::ios::binary); + /// DeflatingOutputStream deflater(ostr, DeflatingStreamBuf::STREAM_GZIP); + /// deflater << "Hello, world!" << std::endl; + /// deflater.close(); + /// ostr.close(); +{ +public: + DeflatingOutputStream(std::ostream& ostr, DeflatingStreamBuf::StreamType type = DeflatingStreamBuf::STREAM_ZLIB, int level = Z_DEFAULT_COMPRESSION); + ~DeflatingOutputStream(); + int close(); +}; + + +class Foundation_API DeflatingInputStream: public DeflatingIOS, public std::istream + /// This stream compresses all data passing through it + /// using zlib's deflate algorithm. +{ +public: + DeflatingInputStream(std::istream& istr, DeflatingStreamBuf::StreamType type = DeflatingStreamBuf::STREAM_ZLIB, int level = Z_DEFAULT_COMPRESSION); + ~DeflatingInputStream(); +}; + + +} // namespace Poco + + +#endif // Foundation_DeflatingStream_INCLUDED diff --git a/Foundation/include/Poco/Delegate.h b/Foundation/include/Poco/Delegate.h index 850f7c6cd..0aae0c0a8 100644 --- a/Foundation/include/Poco/Delegate.h +++ b/Foundation/include/Poco/Delegate.h @@ -1,109 +1,109 @@ -// -// Delegate.h -// -// $Id: //poco/1.2/Foundation/include/Poco/Delegate.h#3 $ -// -// Library: Foundation -// Package: Events -// Module: Delegate -// -// Implementation of the Delegate template. -// -// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_Delegate_INCLUDED -#define Foundation_Delegate_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/AbstractDelegate.h" -#include "Poco/Expire.h" - - -namespace Poco { - - -template -class Delegate: public AbstractDelegate -{ -public: - typedef void (TObj::*NotifyMethod)(const void*, TArgs&); - - Delegate(TObj* obj, NotifyMethod method): - AbstractDelegate(obj), - _receiverObject(obj), - _receiverMethod(method) - { - } - - Delegate(const Delegate& delegate): - AbstractDelegate(delegate), - _receiverObject(delegate._receiverObject), - _receiverMethod(delegate._receiverMethod) - { - } - - ~Delegate() - { - } - - Delegate& operator = (const Delegate& delegate) - { - if (&delegate != this) - { - this->_pTarget = delegate._pTarget; - this->_receiverObject = delegate._receiverObject; - this->_receiverMethod = delegate._receiverMethod; - } - return *this; - } - - bool notify(const void* sender, TArgs& arguments) - { - (_receiverObject->*_receiverMethod)(sender, arguments); - return true; // a "standard" delegate never expires - } - - AbstractDelegate* clone() const - { - return new Delegate(*this); - } - -protected: - TObj* _receiverObject; - NotifyMethod _receiverMethod; - -private: - Delegate(); -}; - - -} // namespace Poco - - -#endif +// +// Delegate.h +// +// $Id: //poco/1.2/Foundation/include/Poco/Delegate.h#3 $ +// +// Library: Foundation +// Package: Events +// Module: Delegate +// +// Implementation of the Delegate template. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_Delegate_INCLUDED +#define Foundation_Delegate_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/AbstractDelegate.h" +#include "Poco/Expire.h" + + +namespace Poco { + + +template +class Delegate: public AbstractDelegate +{ +public: + typedef void (TObj::*NotifyMethod)(const void*, TArgs&); + + Delegate(TObj* obj, NotifyMethod method): + AbstractDelegate(obj), + _receiverObject(obj), + _receiverMethod(method) + { + } + + Delegate(const Delegate& delegate): + AbstractDelegate(delegate), + _receiverObject(delegate._receiverObject), + _receiverMethod(delegate._receiverMethod) + { + } + + ~Delegate() + { + } + + Delegate& operator = (const Delegate& delegate) + { + if (&delegate != this) + { + this->_pTarget = delegate._pTarget; + this->_receiverObject = delegate._receiverObject; + this->_receiverMethod = delegate._receiverMethod; + } + return *this; + } + + bool notify(const void* sender, TArgs& arguments) + { + (_receiverObject->*_receiverMethod)(sender, arguments); + return true; // a "standard" delegate never expires + } + + AbstractDelegate* clone() const + { + return new Delegate(*this); + } + +protected: + TObj* _receiverObject; + NotifyMethod _receiverMethod; + +private: + Delegate(); +}; + + +} // namespace Poco + + +#endif diff --git a/Foundation/include/Poco/DigestEngine.h b/Foundation/include/Poco/DigestEngine.h index f2b3d9d67..c541650f0 100644 --- a/Foundation/include/Poco/DigestEngine.h +++ b/Foundation/include/Poco/DigestEngine.h @@ -1,125 +1,125 @@ -// -// DigestEngine.h -// -// $Id: //poco/1.2/Foundation/include/Poco/DigestEngine.h#1 $ -// -// Library: Foundation -// Package: Crypt -// Module: DigestEngine -// -// Definition of class DigestEngine. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_DigestEngine_INCLUDED -#define Foundation_DigestEngine_INCLUDED - - -#include "Poco/Foundation.h" -#include - - -namespace Poco { - - -class Foundation_API DigestEngine - /// This class is an abstract base class - /// for all classes implementing a message - /// digest algorithm, like MD5Engine - /// and SHA1Engine. - /// Call update() repeatedly with data to - /// compute the digest from. When done, - /// call digest() to obtain the message - /// digest. -{ -public: - typedef std::vector Digest; - - DigestEngine(); - virtual ~DigestEngine(); - - void update(const void* data, unsigned length); - void update(char data); - void update(const std::string& data); - /// Updates the digest with the given data. - - virtual unsigned digestLength() const = 0; - /// Returns the length of the digest in bytes. - - virtual void reset() = 0; - /// Resets the engine so that a new - /// digest can be computed. - - virtual const Digest& digest() = 0; - /// Finishes the computation of the digest and - /// returns the message digest. Resets the engine - /// and can thus only be called once for every digest. - /// The returned reference is valid until the next - /// time digest() is called, or the engine object is destroyed. - - static std::string digestToHex(const Digest& bytes); - /// Converts a message digest into a string of hexadecimal numbers. - -protected: - virtual void updateImpl(const void* data, unsigned length) = 0; - /// Updates the digest with the given data. Must be implemented - /// by subclasses. - -private: - DigestEngine(const DigestEngine&); - DigestEngine& operator = (const DigestEngine&); -}; - - -// -// inlines -// - - -inline void DigestEngine::update(const void* data, unsigned length) -{ - updateImpl(data, length); -} - - -inline void DigestEngine::update(char data) -{ - updateImpl(&data, 1); -} - - -inline void DigestEngine::update(const std::string& data) -{ - updateImpl(data.data(), (unsigned) data.size()); -} - - -} // namespace Poco - - -#endif // Foundation_DigestEngine_INCLUDED +// +// DigestEngine.h +// +// $Id: //poco/1.2/Foundation/include/Poco/DigestEngine.h#1 $ +// +// Library: Foundation +// Package: Crypt +// Module: DigestEngine +// +// Definition of class DigestEngine. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_DigestEngine_INCLUDED +#define Foundation_DigestEngine_INCLUDED + + +#include "Poco/Foundation.h" +#include + + +namespace Poco { + + +class Foundation_API DigestEngine + /// This class is an abstract base class + /// for all classes implementing a message + /// digest algorithm, like MD5Engine + /// and SHA1Engine. + /// Call update() repeatedly with data to + /// compute the digest from. When done, + /// call digest() to obtain the message + /// digest. +{ +public: + typedef std::vector Digest; + + DigestEngine(); + virtual ~DigestEngine(); + + void update(const void* data, unsigned length); + void update(char data); + void update(const std::string& data); + /// Updates the digest with the given data. + + virtual unsigned digestLength() const = 0; + /// Returns the length of the digest in bytes. + + virtual void reset() = 0; + /// Resets the engine so that a new + /// digest can be computed. + + virtual const Digest& digest() = 0; + /// Finishes the computation of the digest and + /// returns the message digest. Resets the engine + /// and can thus only be called once for every digest. + /// The returned reference is valid until the next + /// time digest() is called, or the engine object is destroyed. + + static std::string digestToHex(const Digest& bytes); + /// Converts a message digest into a string of hexadecimal numbers. + +protected: + virtual void updateImpl(const void* data, unsigned length) = 0; + /// Updates the digest with the given data. Must be implemented + /// by subclasses. + +private: + DigestEngine(const DigestEngine&); + DigestEngine& operator = (const DigestEngine&); +}; + + +// +// inlines +// + + +inline void DigestEngine::update(const void* data, unsigned length) +{ + updateImpl(data, length); +} + + +inline void DigestEngine::update(char data) +{ + updateImpl(&data, 1); +} + + +inline void DigestEngine::update(const std::string& data) +{ + updateImpl(data.data(), (unsigned) data.size()); +} + + +} // namespace Poco + + +#endif // Foundation_DigestEngine_INCLUDED diff --git a/Foundation/include/Poco/DigestStream.h b/Foundation/include/Poco/DigestStream.h index bc114ab54..545e42a54 100644 --- a/Foundation/include/Poco/DigestStream.h +++ b/Foundation/include/Poco/DigestStream.h @@ -1,122 +1,122 @@ -// -// DigestStream.h -// -// $Id: //poco/1.2/Foundation/include/Poco/DigestStream.h#1 $ -// -// Library: Foundation -// Package: Crypt -// Module: DigestStream -// -// Definition of classes DigestInputStream and DigestOutputStream. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_DigestStream_INCLUDED -#define Foundation_DigestStream_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/BufferedStreamBuf.h" -#include "Poco/DigestEngine.h" -#include -#include - - -namespace Poco { - - -class Foundation_API DigestBuf: public BufferedStreamBuf - /// This streambuf computes a digest of all data going - /// through it. -{ -public: - DigestBuf(DigestEngine& eng); - DigestBuf(DigestEngine& eng, std::istream& istr); - DigestBuf(DigestEngine& eng, std::ostream& ostr); - ~DigestBuf(); - int readFromDevice(char* buffer, std::streamsize length); - int writeToDevice(const char* buffer, std::streamsize length); - void close(); - -private: - DigestEngine& _eng; - std::istream* _pIstr; - std::ostream* _pOstr; - static const int BUFFER_SIZE; -}; - - -class Foundation_API DigestIOS: public virtual std::ios - /// The base class for DigestInputStream and DigestOutputStream. - /// - /// This class is needed to ensure the correct initialization - /// order of the stream buffer and base classes. -{ -public: - DigestIOS(DigestEngine& eng); - DigestIOS(DigestEngine& eng, std::istream& istr); - DigestIOS(DigestEngine& eng, std::ostream& ostr); - ~DigestIOS(); - DigestBuf* rdbuf(); - -protected: - DigestBuf _buf; -}; - - -class Foundation_API DigestInputStream: public DigestIOS, public std::istream - /// This istream computes a digest of - /// all the data passing through it, - /// using a DigestEngine. -{ -public: - DigestInputStream(DigestEngine& eng, std::istream& istr); - ~DigestInputStream(); -}; - - -class Foundation_API DigestOutputStream: public DigestIOS, public std::ostream - /// This ostream computes a digest of - /// all the data passing through it, - /// using a DigestEngine. - /// To ensure that all data has been incorporated - /// into the digest, call close() or flush() before - /// you obtain the digest from the digest engine. -{ -public: - DigestOutputStream(DigestEngine& eng); - DigestOutputStream(DigestEngine& eng, std::ostream& ostr); - ~DigestOutputStream(); - void close(); -}; - - -} // namespace Poco - - -#endif // Foundation_DigestStream_INCLUDED +// +// DigestStream.h +// +// $Id: //poco/1.2/Foundation/include/Poco/DigestStream.h#1 $ +// +// Library: Foundation +// Package: Crypt +// Module: DigestStream +// +// Definition of classes DigestInputStream and DigestOutputStream. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_DigestStream_INCLUDED +#define Foundation_DigestStream_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/BufferedStreamBuf.h" +#include "Poco/DigestEngine.h" +#include +#include + + +namespace Poco { + + +class Foundation_API DigestBuf: public BufferedStreamBuf + /// This streambuf computes a digest of all data going + /// through it. +{ +public: + DigestBuf(DigestEngine& eng); + DigestBuf(DigestEngine& eng, std::istream& istr); + DigestBuf(DigestEngine& eng, std::ostream& ostr); + ~DigestBuf(); + int readFromDevice(char* buffer, std::streamsize length); + int writeToDevice(const char* buffer, std::streamsize length); + void close(); + +private: + DigestEngine& _eng; + std::istream* _pIstr; + std::ostream* _pOstr; + static const int BUFFER_SIZE; +}; + + +class Foundation_API DigestIOS: public virtual std::ios + /// The base class for DigestInputStream and DigestOutputStream. + /// + /// This class is needed to ensure the correct initialization + /// order of the stream buffer and base classes. +{ +public: + DigestIOS(DigestEngine& eng); + DigestIOS(DigestEngine& eng, std::istream& istr); + DigestIOS(DigestEngine& eng, std::ostream& ostr); + ~DigestIOS(); + DigestBuf* rdbuf(); + +protected: + DigestBuf _buf; +}; + + +class Foundation_API DigestInputStream: public DigestIOS, public std::istream + /// This istream computes a digest of + /// all the data passing through it, + /// using a DigestEngine. +{ +public: + DigestInputStream(DigestEngine& eng, std::istream& istr); + ~DigestInputStream(); +}; + + +class Foundation_API DigestOutputStream: public DigestIOS, public std::ostream + /// This ostream computes a digest of + /// all the data passing through it, + /// using a DigestEngine. + /// To ensure that all data has been incorporated + /// into the digest, call close() or flush() before + /// you obtain the digest from the digest engine. +{ +public: + DigestOutputStream(DigestEngine& eng); + DigestOutputStream(DigestEngine& eng, std::ostream& ostr); + ~DigestOutputStream(); + void close(); +}; + + +} // namespace Poco + + +#endif // Foundation_DigestStream_INCLUDED diff --git a/Foundation/include/Poco/DirectoryIterator.h b/Foundation/include/Poco/DirectoryIterator.h index 2f8d3d82b..57187c4f0 100644 --- a/Foundation/include/Poco/DirectoryIterator.h +++ b/Foundation/include/Poco/DirectoryIterator.h @@ -1,158 +1,158 @@ -// -// DirectoryIterator.h -// -// $Id: //poco/1.2/Foundation/include/Poco/DirectoryIterator.h#1 $ -// -// Library: Foundation -// Package: Filesystem -// Module: DirectoryIterator -// -// Definition of the DirectoryIterator class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_DirectoryIterator_INCLUDED -#define Foundation_DirectoryIterator_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/File.h" -#include "Poco/Path.h" - - -namespace Poco { - - -class DirectoryIteratorImpl; - - -class Foundation_API DirectoryIterator - /// The DirectoryIterator class is used to enumerate - /// all files in a directory. -{ -public: - DirectoryIterator(); - /// Creates the end iterator. - - DirectoryIterator(const std::string& path); - /// Creates a directory iterator for the given path. - - DirectoryIterator(const DirectoryIterator& iterator); - /// Creates a directory iterator for the given path. - - DirectoryIterator(const File& file); - /// Creates a directory iterator for the given file. - - DirectoryIterator(const Path& path); - /// Creates a directory iterator for the given path. - - ~DirectoryIterator(); - /// Destroys the DirectoryIterator. - - const std::string& name() const; - /// Returns the current filename. - - const Path& path() const; - /// Returns the current path. - - DirectoryIterator& operator = (const DirectoryIterator& it); - DirectoryIterator& operator = (const File& file); - DirectoryIterator& operator = (const Path& path); - DirectoryIterator& operator = (const std::string& path); - - DirectoryIterator& operator ++ (); // prefix - DirectoryIterator operator ++ (int); // postfix - const File& operator * () const; - File& operator * (); - const File* operator -> () const; - File* operator -> (); - bool operator == (const DirectoryIterator& iterator) const; - bool operator != (const DirectoryIterator& iterator) const; - -private: - Path _path; - File _file; - DirectoryIteratorImpl* _pImpl; -}; - - -// -// inlines -// -inline const std::string& DirectoryIterator::name() const -{ - return _path.getFileName(); -} - - -inline const Path& DirectoryIterator::path() const -{ - return _path; -} - - -inline const File& DirectoryIterator::operator * () const -{ - return _file; -} - - -inline File& DirectoryIterator::operator * () -{ - return _file; -} - - -inline const File* DirectoryIterator::operator -> () const -{ - return &_file; -} - - -inline File* DirectoryIterator::operator -> () -{ - return &_file; -} - - -inline bool DirectoryIterator::operator == (const DirectoryIterator& iterator) const -{ - return name() == iterator.name(); -} - - -inline bool DirectoryIterator::operator != (const DirectoryIterator& iterator) const -{ - return name() != iterator.name(); -} - - -} // namespace Poco - - -#endif // Foundation_DirectoryIterator_INCLUDED +// +// DirectoryIterator.h +// +// $Id: //poco/1.2/Foundation/include/Poco/DirectoryIterator.h#1 $ +// +// Library: Foundation +// Package: Filesystem +// Module: DirectoryIterator +// +// Definition of the DirectoryIterator class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_DirectoryIterator_INCLUDED +#define Foundation_DirectoryIterator_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/File.h" +#include "Poco/Path.h" + + +namespace Poco { + + +class DirectoryIteratorImpl; + + +class Foundation_API DirectoryIterator + /// The DirectoryIterator class is used to enumerate + /// all files in a directory. +{ +public: + DirectoryIterator(); + /// Creates the end iterator. + + DirectoryIterator(const std::string& path); + /// Creates a directory iterator for the given path. + + DirectoryIterator(const DirectoryIterator& iterator); + /// Creates a directory iterator for the given path. + + DirectoryIterator(const File& file); + /// Creates a directory iterator for the given file. + + DirectoryIterator(const Path& path); + /// Creates a directory iterator for the given path. + + ~DirectoryIterator(); + /// Destroys the DirectoryIterator. + + const std::string& name() const; + /// Returns the current filename. + + const Path& path() const; + /// Returns the current path. + + DirectoryIterator& operator = (const DirectoryIterator& it); + DirectoryIterator& operator = (const File& file); + DirectoryIterator& operator = (const Path& path); + DirectoryIterator& operator = (const std::string& path); + + DirectoryIterator& operator ++ (); // prefix + DirectoryIterator operator ++ (int); // postfix + const File& operator * () const; + File& operator * (); + const File* operator -> () const; + File* operator -> (); + bool operator == (const DirectoryIterator& iterator) const; + bool operator != (const DirectoryIterator& iterator) const; + +private: + Path _path; + File _file; + DirectoryIteratorImpl* _pImpl; +}; + + +// +// inlines +// +inline const std::string& DirectoryIterator::name() const +{ + return _path.getFileName(); +} + + +inline const Path& DirectoryIterator::path() const +{ + return _path; +} + + +inline const File& DirectoryIterator::operator * () const +{ + return _file; +} + + +inline File& DirectoryIterator::operator * () +{ + return _file; +} + + +inline const File* DirectoryIterator::operator -> () const +{ + return &_file; +} + + +inline File* DirectoryIterator::operator -> () +{ + return &_file; +} + + +inline bool DirectoryIterator::operator == (const DirectoryIterator& iterator) const +{ + return name() == iterator.name(); +} + + +inline bool DirectoryIterator::operator != (const DirectoryIterator& iterator) const +{ + return name() != iterator.name(); +} + + +} // namespace Poco + + +#endif // Foundation_DirectoryIterator_INCLUDED diff --git a/Foundation/include/Poco/DirectoryIterator_UNIX.h b/Foundation/include/Poco/DirectoryIterator_UNIX.h index 656877ee7..9ed8dc51a 100644 --- a/Foundation/include/Poco/DirectoryIterator_UNIX.h +++ b/Foundation/include/Poco/DirectoryIterator_UNIX.h @@ -1,94 +1,94 @@ -// -// DirectoryIterator_UNIX.h -// -// $Id: //poco/1.2/Foundation/include/Poco/DirectoryIterator_UNIX.h#1 $ -// -// Library: Foundation -// Package: Filesystem -// Module: DirectoryIterator -// -// Definition of the DirectoryIteratorImpl class for UNIX. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_DirectoryIterator_UNIX_INCLUDED -#define Foundation_DirectoryIterator_UNIX_INCLUDED - - -#include "Poco/Foundation.h" -#include - - -namespace Poco { - - -class Foundation_API DirectoryIteratorImpl -{ -public: - DirectoryIteratorImpl(const std::string& path); - ~DirectoryIteratorImpl(); - - void duplicate(); - void release(); - - const std::string& get() const; - const std::string& next(); - -private: - DIR* _pDir; - std::string _current; - int _rc; -}; - - -// -// inlines -// -const std::string& DirectoryIteratorImpl::get() const -{ - return _current; -} - - -inline void DirectoryIteratorImpl::duplicate() -{ - ++_rc; -} - - -inline void DirectoryIteratorImpl::release() -{ - if (--_rc == 0) - delete this; -} - - -} // namespace Poco - - -#endif // Foundation_DirectoryIterator_UNIX_INCLUDED +// +// DirectoryIterator_UNIX.h +// +// $Id: //poco/1.2/Foundation/include/Poco/DirectoryIterator_UNIX.h#1 $ +// +// Library: Foundation +// Package: Filesystem +// Module: DirectoryIterator +// +// Definition of the DirectoryIteratorImpl class for UNIX. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_DirectoryIterator_UNIX_INCLUDED +#define Foundation_DirectoryIterator_UNIX_INCLUDED + + +#include "Poco/Foundation.h" +#include + + +namespace Poco { + + +class Foundation_API DirectoryIteratorImpl +{ +public: + DirectoryIteratorImpl(const std::string& path); + ~DirectoryIteratorImpl(); + + void duplicate(); + void release(); + + const std::string& get() const; + const std::string& next(); + +private: + DIR* _pDir; + std::string _current; + int _rc; +}; + + +// +// inlines +// +const std::string& DirectoryIteratorImpl::get() const +{ + return _current; +} + + +inline void DirectoryIteratorImpl::duplicate() +{ + ++_rc; +} + + +inline void DirectoryIteratorImpl::release() +{ + if (--_rc == 0) + delete this; +} + + +} // namespace Poco + + +#endif // Foundation_DirectoryIterator_UNIX_INCLUDED diff --git a/Foundation/include/Poco/DirectoryIterator_VMS.h b/Foundation/include/Poco/DirectoryIterator_VMS.h index 553108d4f..01460d6b9 100644 --- a/Foundation/include/Poco/DirectoryIterator_VMS.h +++ b/Foundation/include/Poco/DirectoryIterator_VMS.h @@ -1,97 +1,97 @@ -// -// DirectoryIterator_VMS.h -// -// $Id: //poco/1.2/Foundation/include/Poco/DirectoryIterator_VMS.h#1 $ -// -// Library: Foundation -// Package: Filesystem -// Module: DirectoryIterator -// -// Definition of the DirectoryIteratorImpl class for OpenVMS. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_DirectoryIterator_VMS_INCLUDED -#define Foundation_DirectoryIterator_VMS_INCLUDED - - -#include "Poco/Foundation.h" -#include - - -namespace Poco { - - -class Foundation_API DirectoryIteratorImpl -{ -public: - DirectoryIteratorImpl(const std::string& path); - ~DirectoryIteratorImpl(); - - void duplicate(); - void release(); - - const std::string& get() const; - const std::string& next(); - -private: - struct FAB _fab; - struct NAM _nam; - std::string _search; - char _spec[255]; - std::string _current; - int _rc; -}; - - -// -// inlines -// -const std::string& DirectoryIteratorImpl::get() const -{ - return _current; -} - - -inline void DirectoryIteratorImpl::duplicate() -{ - ++_rc; -} - - -inline void DirectoryIteratorImpl::release() -{ - if (--_rc == 0) - delete this; -} - - -} // namespace Poco - - -#endif // Foundation_DirectoryIterator_VMS_INCLUDED +// +// DirectoryIterator_VMS.h +// +// $Id: //poco/1.2/Foundation/include/Poco/DirectoryIterator_VMS.h#1 $ +// +// Library: Foundation +// Package: Filesystem +// Module: DirectoryIterator +// +// Definition of the DirectoryIteratorImpl class for OpenVMS. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_DirectoryIterator_VMS_INCLUDED +#define Foundation_DirectoryIterator_VMS_INCLUDED + + +#include "Poco/Foundation.h" +#include + + +namespace Poco { + + +class Foundation_API DirectoryIteratorImpl +{ +public: + DirectoryIteratorImpl(const std::string& path); + ~DirectoryIteratorImpl(); + + void duplicate(); + void release(); + + const std::string& get() const; + const std::string& next(); + +private: + struct FAB _fab; + struct NAM _nam; + std::string _search; + char _spec[255]; + std::string _current; + int _rc; +}; + + +// +// inlines +// +const std::string& DirectoryIteratorImpl::get() const +{ + return _current; +} + + +inline void DirectoryIteratorImpl::duplicate() +{ + ++_rc; +} + + +inline void DirectoryIteratorImpl::release() +{ + if (--_rc == 0) + delete this; +} + + +} // namespace Poco + + +#endif // Foundation_DirectoryIterator_VMS_INCLUDED diff --git a/Foundation/include/Poco/DirectoryIterator_WIN32.h b/Foundation/include/Poco/DirectoryIterator_WIN32.h index 9cfd70308..eecc60e3e 100644 --- a/Foundation/include/Poco/DirectoryIterator_WIN32.h +++ b/Foundation/include/Poco/DirectoryIterator_WIN32.h @@ -1,95 +1,95 @@ -// -// DirectoryIterator_WIN32.h -// -// $Id: //poco/1.2/Foundation/include/Poco/DirectoryIterator_WIN32.h#1 $ -// -// Library: Foundation -// Package: Filesystem -// Module: DirectoryIterator -// -// Definition of the DirectoryIteratorImpl class for WIN32. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_DirectoryIterator_WIN32_INCLUDED -#define Foundation_DirectoryIterator_WIN32_INCLUDED - - -#include "Poco/Foundation.h" -#include - - -namespace Poco { - - -class Foundation_API DirectoryIteratorImpl -{ -public: - DirectoryIteratorImpl(const std::string& path); - ~DirectoryIteratorImpl(); - - void duplicate(); - void release(); - - const std::string& get() const; - const std::string& next(); - -private: - HANDLE _fh; - WIN32_FIND_DATA _fd; - std::string _current; - int _rc; -}; - - -// -// inlines -// -const std::string& DirectoryIteratorImpl::get() const -{ - return _current; -} - - -inline void DirectoryIteratorImpl::duplicate() -{ - ++_rc; -} - - -inline void DirectoryIteratorImpl::release() -{ - if (--_rc == 0) - delete this; -} - - -} // namespace Poco - - -#endif // Foundation_DirectoryIterator_WIN32_INCLUDED +// +// DirectoryIterator_WIN32.h +// +// $Id: //poco/1.2/Foundation/include/Poco/DirectoryIterator_WIN32.h#1 $ +// +// Library: Foundation +// Package: Filesystem +// Module: DirectoryIterator +// +// Definition of the DirectoryIteratorImpl class for WIN32. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_DirectoryIterator_WIN32_INCLUDED +#define Foundation_DirectoryIterator_WIN32_INCLUDED + + +#include "Poco/Foundation.h" +#include + + +namespace Poco { + + +class Foundation_API DirectoryIteratorImpl +{ +public: + DirectoryIteratorImpl(const std::string& path); + ~DirectoryIteratorImpl(); + + void duplicate(); + void release(); + + const std::string& get() const; + const std::string& next(); + +private: + HANDLE _fh; + WIN32_FIND_DATA _fd; + std::string _current; + int _rc; +}; + + +// +// inlines +// +const std::string& DirectoryIteratorImpl::get() const +{ + return _current; +} + + +inline void DirectoryIteratorImpl::duplicate() +{ + ++_rc; +} + + +inline void DirectoryIteratorImpl::release() +{ + if (--_rc == 0) + delete this; +} + + +} // namespace Poco + + +#endif // Foundation_DirectoryIterator_WIN32_INCLUDED diff --git a/Foundation/include/Poco/DirectoryIterator_WIN32U.h b/Foundation/include/Poco/DirectoryIterator_WIN32U.h index 2fa57bd0e..5f5dc93a4 100644 --- a/Foundation/include/Poco/DirectoryIterator_WIN32U.h +++ b/Foundation/include/Poco/DirectoryIterator_WIN32U.h @@ -1,95 +1,95 @@ -// -// DirectoryIterator_WIN32U.h -// -// $Id: //poco/1.2/Foundation/include/Poco/DirectoryIterator_WIN32U.h#1 $ -// -// Library: Foundation -// Package: Filesystem -// Module: DirectoryIterator -// -// Definition of the DirectoryIteratorImpl class for WIN32. -// -// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_DirectoryIterator_WIN32U_INCLUDED -#define Foundation_DirectoryIterator_WIN32U_INCLUDED - - -#include "Poco/Foundation.h" -#include - - -namespace Poco { - - -class Foundation_API DirectoryIteratorImpl -{ -public: - DirectoryIteratorImpl(const std::string& path); - ~DirectoryIteratorImpl(); - - void duplicate(); - void release(); - - const std::string& get() const; - const std::string& next(); - -private: - HANDLE _fh; - WIN32_FIND_DATAW _fd; - std::string _current; - int _rc; -}; - - -// -// inlines -// -const std::string& DirectoryIteratorImpl::get() const -{ - return _current; -} - - -inline void DirectoryIteratorImpl::duplicate() -{ - ++_rc; -} - - -inline void DirectoryIteratorImpl::release() -{ - if (--_rc == 0) - delete this; -} - - -} // namespace Poco - - -#endif // Foundation_DirectoryIterator_WIN32U_INCLUDED +// +// DirectoryIterator_WIN32U.h +// +// $Id: //poco/1.2/Foundation/include/Poco/DirectoryIterator_WIN32U.h#1 $ +// +// Library: Foundation +// Package: Filesystem +// Module: DirectoryIterator +// +// Definition of the DirectoryIteratorImpl class for WIN32. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_DirectoryIterator_WIN32U_INCLUDED +#define Foundation_DirectoryIterator_WIN32U_INCLUDED + + +#include "Poco/Foundation.h" +#include + + +namespace Poco { + + +class Foundation_API DirectoryIteratorImpl +{ +public: + DirectoryIteratorImpl(const std::string& path); + ~DirectoryIteratorImpl(); + + void duplicate(); + void release(); + + const std::string& get() const; + const std::string& next(); + +private: + HANDLE _fh; + WIN32_FIND_DATAW _fd; + std::string _current; + int _rc; +}; + + +// +// inlines +// +const std::string& DirectoryIteratorImpl::get() const +{ + return _current; +} + + +inline void DirectoryIteratorImpl::duplicate() +{ + ++_rc; +} + + +inline void DirectoryIteratorImpl::release() +{ + if (--_rc == 0) + delete this; +} + + +} // namespace Poco + + +#endif // Foundation_DirectoryIterator_WIN32U_INCLUDED diff --git a/Foundation/include/Poco/DynamicFactory.h b/Foundation/include/Poco/DynamicFactory.h index 016a88533..9bee03220 100644 --- a/Foundation/include/Poco/DynamicFactory.h +++ b/Foundation/include/Poco/DynamicFactory.h @@ -1,158 +1,158 @@ -// -// DynamicFactory.h -// -// $Id: //poco/1.2/Foundation/include/Poco/DynamicFactory.h#1 $ -// -// Library: Foundation -// Package: Core -// Module: DynamicFactory -// -// Definition of the DynamicFactory class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_DynamicFactory_INCLUDED -#define Foundation_DynamicFactory_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/Instantiator.h" -#include "Poco/Exception.h" -#include "Poco/Mutex.h" -#include -#include - - -namespace Poco { - - -template -class DynamicFactory - /// A factory that creates objects by class name. -{ -public: - typedef AbstractInstantiator AbstractFactory; - - DynamicFactory() - /// Creates the DynamicFactory. - { - } - - ~DynamicFactory() - /// Destroys the DynamicFactory and deletes the instantiators for - /// all registered classes. - { - for (typename FactoryMap::iterator it = _map.begin(); it != _map.end(); ++it) - { - delete it->second; - } - } - - Base* createInstance(const std::string& className) const - /// Creates a new instance of the class with the given name. - /// The class must have been registered with registerClass. - /// If the class name is unknown, a NotFoundException is thrown. - { - FastMutex::ScopedLock lock(_mutex); - - typename FactoryMap::const_iterator it = _map.find(className); - if (it != _map.end()) - return it->second->createInstance(); - else - throw NotFoundException(className); - } - - template - void registerClass(const std::string& className) - /// Registers the instantiator for the given class with the DynamicFactory. - /// The DynamicFactory takes ownership of the instantiator and deletes - /// it when it's no longer used. - /// If the class has already been registered, an ExistsException is thrown - /// and the instantiator is deleted. - { - registerClass(className, new Instantiator); - } - - void registerClass(const std::string& className, AbstractFactory* pAbstractFactory) - /// Registers the instantiator for the given class with the DynamicFactory. - /// The DynamicFactory takes ownership of the instantiator and deletes - /// it when it's no longer used. - /// If the class has already been registered, an ExistsException is thrown - /// and the instantiator is deleted. - { - poco_check_ptr (pAbstractFactory); - - FastMutex::ScopedLock lock(_mutex); - - std::auto_ptr ptr(pAbstractFactory); - typename FactoryMap::iterator it = _map.find(className); - if (it == _map.end()) - _map[className] = ptr.release(); - else - throw ExistsException(className); - } - - void unregisterClass(const std::string& className) - /// Unregisters the given class and deletes the instantiator - /// for the class. - /// Throws a NotFoundException if the class has not been registered. - { - FastMutex::ScopedLock lock(_mutex); - - typename FactoryMap::iterator it = _map.find(className); - if (it != _map.end()) - { - delete it->second; - _map.erase(it); - } - else throw NotFoundException(className); - } - - bool isClass(const std::string& className) const - /// Returns true iff the given class has been registered. - { - FastMutex::ScopedLock lock(_mutex); - - return _map.find(className) != _map.end(); - } - -private: - DynamicFactory(const DynamicFactory&); - DynamicFactory& operator = (const DynamicFactory&); - - typedef std::map FactoryMap; - - FactoryMap _map; - mutable FastMutex _mutex; -}; - - -} // namespace Poco - - -#endif // Foundation_DynamicFactory_INCLUDED +// +// DynamicFactory.h +// +// $Id: //poco/1.2/Foundation/include/Poco/DynamicFactory.h#1 $ +// +// Library: Foundation +// Package: Core +// Module: DynamicFactory +// +// Definition of the DynamicFactory class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_DynamicFactory_INCLUDED +#define Foundation_DynamicFactory_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Instantiator.h" +#include "Poco/Exception.h" +#include "Poco/Mutex.h" +#include +#include + + +namespace Poco { + + +template +class DynamicFactory + /// A factory that creates objects by class name. +{ +public: + typedef AbstractInstantiator AbstractFactory; + + DynamicFactory() + /// Creates the DynamicFactory. + { + } + + ~DynamicFactory() + /// Destroys the DynamicFactory and deletes the instantiators for + /// all registered classes. + { + for (typename FactoryMap::iterator it = _map.begin(); it != _map.end(); ++it) + { + delete it->second; + } + } + + Base* createInstance(const std::string& className) const + /// Creates a new instance of the class with the given name. + /// The class must have been registered with registerClass. + /// If the class name is unknown, a NotFoundException is thrown. + { + FastMutex::ScopedLock lock(_mutex); + + typename FactoryMap::const_iterator it = _map.find(className); + if (it != _map.end()) + return it->second->createInstance(); + else + throw NotFoundException(className); + } + + template + void registerClass(const std::string& className) + /// Registers the instantiator for the given class with the DynamicFactory. + /// The DynamicFactory takes ownership of the instantiator and deletes + /// it when it's no longer used. + /// If the class has already been registered, an ExistsException is thrown + /// and the instantiator is deleted. + { + registerClass(className, new Instantiator); + } + + void registerClass(const std::string& className, AbstractFactory* pAbstractFactory) + /// Registers the instantiator for the given class with the DynamicFactory. + /// The DynamicFactory takes ownership of the instantiator and deletes + /// it when it's no longer used. + /// If the class has already been registered, an ExistsException is thrown + /// and the instantiator is deleted. + { + poco_check_ptr (pAbstractFactory); + + FastMutex::ScopedLock lock(_mutex); + + std::auto_ptr ptr(pAbstractFactory); + typename FactoryMap::iterator it = _map.find(className); + if (it == _map.end()) + _map[className] = ptr.release(); + else + throw ExistsException(className); + } + + void unregisterClass(const std::string& className) + /// Unregisters the given class and deletes the instantiator + /// for the class. + /// Throws a NotFoundException if the class has not been registered. + { + FastMutex::ScopedLock lock(_mutex); + + typename FactoryMap::iterator it = _map.find(className); + if (it != _map.end()) + { + delete it->second; + _map.erase(it); + } + else throw NotFoundException(className); + } + + bool isClass(const std::string& className) const + /// Returns true iff the given class has been registered. + { + FastMutex::ScopedLock lock(_mutex); + + return _map.find(className) != _map.end(); + } + +private: + DynamicFactory(const DynamicFactory&); + DynamicFactory& operator = (const DynamicFactory&); + + typedef std::map FactoryMap; + + FactoryMap _map; + mutable FastMutex _mutex; +}; + + +} // namespace Poco + + +#endif // Foundation_DynamicFactory_INCLUDED diff --git a/Foundation/include/Poco/Environment.h b/Foundation/include/Poco/Environment.h index 05b47d9ad..05774085e 100644 --- a/Foundation/include/Poco/Environment.h +++ b/Foundation/include/Poco/Environment.h @@ -1,84 +1,84 @@ -// -// Environment.h -// -// $Id: //poco/1.2/Foundation/include/Poco/Environment.h#1 $ -// -// Library: Foundation -// Package: Core -// Module: Environment -// -// Definition of the Environment class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_Environment_INCLUDED -#define Foundation_Environment_INCLUDED - - -#include "Poco/Foundation.h" - - -namespace Poco { - - -class Foundation_API Environment - /// This class provides access to environment variables - /// and some general system information. -{ -public: - static std::string get(const std::string& name); - /// Returns the value of the environment variable - /// with the given name. Throws a NotFoundException - /// if the variable does not exist. - - static bool has(const std::string& name); - /// Returns true iff an environment variable - /// with the given name is defined. - - static void set(const std::string& name, const std::string& value); - /// Sets the environment variable with the given name - /// to the given value. - - static std::string osName(); - /// Returns the operating system name. - - static std::string osVersion(); - /// Returns the operating system version. - - static std::string osArchitecture(); - /// Returns the operating system architecture. - - static std::string nodeName(); - /// Returns the node (or host) name. -}; - - -} // namespace Poco - - -#endif // Foundation_Environment_INCLUDED +// +// Environment.h +// +// $Id: //poco/1.2/Foundation/include/Poco/Environment.h#1 $ +// +// Library: Foundation +// Package: Core +// Module: Environment +// +// Definition of the Environment class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_Environment_INCLUDED +#define Foundation_Environment_INCLUDED + + +#include "Poco/Foundation.h" + + +namespace Poco { + + +class Foundation_API Environment + /// This class provides access to environment variables + /// and some general system information. +{ +public: + static std::string get(const std::string& name); + /// Returns the value of the environment variable + /// with the given name. Throws a NotFoundException + /// if the variable does not exist. + + static bool has(const std::string& name); + /// Returns true iff an environment variable + /// with the given name is defined. + + static void set(const std::string& name, const std::string& value); + /// Sets the environment variable with the given name + /// to the given value. + + static std::string osName(); + /// Returns the operating system name. + + static std::string osVersion(); + /// Returns the operating system version. + + static std::string osArchitecture(); + /// Returns the operating system architecture. + + static std::string nodeName(); + /// Returns the node (or host) name. +}; + + +} // namespace Poco + + +#endif // Foundation_Environment_INCLUDED diff --git a/Foundation/include/Poco/Environment_UNIX.h b/Foundation/include/Poco/Environment_UNIX.h index 3f47cab78..2cfd38eec 100644 --- a/Foundation/include/Poco/Environment_UNIX.h +++ b/Foundation/include/Poco/Environment_UNIX.h @@ -1,73 +1,73 @@ -// -// Environment_UNIX.h -// -// $Id: //poco/1.2/Foundation/include/Poco/Environment_UNIX.h#1 $ -// -// Library: Foundation -// Package: Core -// Module: Environment -// -// Definition of the EnvironmentImpl class for Unix. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_Environment_UNIX_INCLUDED -#define Foundation_Environment_UNIX_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/Mutex.h" -#include - - -namespace Poco { - - -class Foundation_API EnvironmentImpl -{ -public: - static std::string getImpl(const std::string& name); - static bool hasImpl(const std::string& name); - static void setImpl(const std::string& name, const std::string& value); - static std::string osNameImpl(); - static std::string osVersionImpl(); - static std::string osArchitectureImpl(); - static std::string nodeNameImpl(); - -private: - typedef std::map StringMap; - - static StringMap _map; - static FastMutex _mutex; -}; - - -} // namespace Poco - - -#endif // Foundation_Environment_UNIX_INCLUDED +// +// Environment_UNIX.h +// +// $Id: //poco/1.2/Foundation/include/Poco/Environment_UNIX.h#1 $ +// +// Library: Foundation +// Package: Core +// Module: Environment +// +// Definition of the EnvironmentImpl class for Unix. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_Environment_UNIX_INCLUDED +#define Foundation_Environment_UNIX_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Mutex.h" +#include + + +namespace Poco { + + +class Foundation_API EnvironmentImpl +{ +public: + static std::string getImpl(const std::string& name); + static bool hasImpl(const std::string& name); + static void setImpl(const std::string& name, const std::string& value); + static std::string osNameImpl(); + static std::string osVersionImpl(); + static std::string osArchitectureImpl(); + static std::string nodeNameImpl(); + +private: + typedef std::map StringMap; + + static StringMap _map; + static FastMutex _mutex; +}; + + +} // namespace Poco + + +#endif // Foundation_Environment_UNIX_INCLUDED diff --git a/Foundation/include/Poco/Environment_VMS.h b/Foundation/include/Poco/Environment_VMS.h index 5bb20c484..e56aadec5 100644 --- a/Foundation/include/Poco/Environment_VMS.h +++ b/Foundation/include/Poco/Environment_VMS.h @@ -1,74 +1,74 @@ -// -// Environment_VMS.h -// -// $Id: //poco/1.2/Foundation/include/Poco/Environment_VMS.h#1 $ -// -// Library: Foundation -// Package: Core -// Module: Environment -// -// Definition of the EnvironmentImpl class for OpenVMS. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_Environment_VMS_INCLUDED -#define Foundation_Environment_VMS_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/Mutex.h" - - -namespace Poco { - - -class Foundation_API EnvironmentImpl -{ -public: - static std::string getImpl(const std::string& name); - static bool hasImpl(const std::string& name); - static void setImpl(const std::string& name, const std::string& value); - static std::string osNameImpl(); - static std::string osVersionImpl(); - static std::string osArchitectureImpl(); - static std::string nodeNameImpl(); - - static std::string getsyi(unsigned short code); - /// a wrapper for $GETSYIW - - static std::string trnlnm(const std::string& name); - -private: - static FastMutex _mutex; -}; - - -} // namespace Poco - - -#endif // Foundation_Environment_VMS_INCLUDED +// +// Environment_VMS.h +// +// $Id: //poco/1.2/Foundation/include/Poco/Environment_VMS.h#1 $ +// +// Library: Foundation +// Package: Core +// Module: Environment +// +// Definition of the EnvironmentImpl class for OpenVMS. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_Environment_VMS_INCLUDED +#define Foundation_Environment_VMS_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Mutex.h" + + +namespace Poco { + + +class Foundation_API EnvironmentImpl +{ +public: + static std::string getImpl(const std::string& name); + static bool hasImpl(const std::string& name); + static void setImpl(const std::string& name, const std::string& value); + static std::string osNameImpl(); + static std::string osVersionImpl(); + static std::string osArchitectureImpl(); + static std::string nodeNameImpl(); + + static std::string getsyi(unsigned short code); + /// a wrapper for $GETSYIW + + static std::string trnlnm(const std::string& name); + +private: + static FastMutex _mutex; +}; + + +} // namespace Poco + + +#endif // Foundation_Environment_VMS_INCLUDED diff --git a/Foundation/include/Poco/Environment_WIN32.h b/Foundation/include/Poco/Environment_WIN32.h index 3677f21bb..91b7af214 100644 --- a/Foundation/include/Poco/Environment_WIN32.h +++ b/Foundation/include/Poco/Environment_WIN32.h @@ -1,65 +1,65 @@ -// -// Environment_WIN32.h -// -// $Id: //poco/1.2/Foundation/include/Poco/Environment_WIN32.h#1 $ -// -// Library: Foundation -// Package: Core -// Module: Environment -// -// Definition of the EnvironmentImpl class for WIN32. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_Environment_WIN32_INCLUDED -#define Foundation_Environment_WIN32_INCLUDED - - -#include "Poco/Foundation.h" - - -namespace Poco { - - -class Foundation_API EnvironmentImpl -{ -public: - static std::string getImpl(const std::string& name); - static bool hasImpl(const std::string& name); - static void setImpl(const std::string& name, const std::string& value); - static std::string osNameImpl(); - static std::string osVersionImpl(); - static std::string osArchitectureImpl(); - static std::string nodeNameImpl(); -}; - - -} // namespace Poco - - -#endif // Foundation_Environment_WIN32_INCLUDED +// +// Environment_WIN32.h +// +// $Id: //poco/1.2/Foundation/include/Poco/Environment_WIN32.h#1 $ +// +// Library: Foundation +// Package: Core +// Module: Environment +// +// Definition of the EnvironmentImpl class for WIN32. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_Environment_WIN32_INCLUDED +#define Foundation_Environment_WIN32_INCLUDED + + +#include "Poco/Foundation.h" + + +namespace Poco { + + +class Foundation_API EnvironmentImpl +{ +public: + static std::string getImpl(const std::string& name); + static bool hasImpl(const std::string& name); + static void setImpl(const std::string& name, const std::string& value); + static std::string osNameImpl(); + static std::string osVersionImpl(); + static std::string osArchitectureImpl(); + static std::string nodeNameImpl(); +}; + + +} // namespace Poco + + +#endif // Foundation_Environment_WIN32_INCLUDED diff --git a/Foundation/include/Poco/Environment_WIN32U.h b/Foundation/include/Poco/Environment_WIN32U.h index ea7c98240..a2fad72dc 100644 --- a/Foundation/include/Poco/Environment_WIN32U.h +++ b/Foundation/include/Poco/Environment_WIN32U.h @@ -1,65 +1,65 @@ -// -// Environment_WIN32U.h -// -// $Id: //poco/1.2/Foundation/include/Poco/Environment_WIN32U.h#1 $ -// -// Library: Foundation -// Package: Core -// Module: Environment -// -// Definition of the EnvironmentImpl class for WIN32. -// -// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_Environment_WIN32U_INCLUDED -#define Foundation_Environment_WIN32U_INCLUDED - - -#include "Poco/Foundation.h" - - -namespace Poco { - - -class Foundation_API EnvironmentImpl -{ -public: - static std::string getImpl(const std::string& name); - static bool hasImpl(const std::string& name); - static void setImpl(const std::string& name, const std::string& value); - static std::string osNameImpl(); - static std::string osVersionImpl(); - static std::string osArchitectureImpl(); - static std::string nodeNameImpl(); -}; - - -} // namespace Poco - - -#endif // Foundation_Environment_WIN32U_INCLUDED +// +// Environment_WIN32U.h +// +// $Id: //poco/1.2/Foundation/include/Poco/Environment_WIN32U.h#1 $ +// +// Library: Foundation +// Package: Core +// Module: Environment +// +// Definition of the EnvironmentImpl class for WIN32. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_Environment_WIN32U_INCLUDED +#define Foundation_Environment_WIN32U_INCLUDED + + +#include "Poco/Foundation.h" + + +namespace Poco { + + +class Foundation_API EnvironmentImpl +{ +public: + static std::string getImpl(const std::string& name); + static bool hasImpl(const std::string& name); + static void setImpl(const std::string& name, const std::string& value); + static std::string osNameImpl(); + static std::string osVersionImpl(); + static std::string osArchitectureImpl(); + static std::string nodeNameImpl(); +}; + + +} // namespace Poco + + +#endif // Foundation_Environment_WIN32U_INCLUDED diff --git a/Foundation/include/Poco/ErrorHandler.h b/Foundation/include/Poco/ErrorHandler.h index 4cd749510..41559a20e 100644 --- a/Foundation/include/Poco/ErrorHandler.h +++ b/Foundation/include/Poco/ErrorHandler.h @@ -1,142 +1,142 @@ -// -// ErrorHandler.h -// -// $Id: //poco/1.2/Foundation/include/Poco/ErrorHandler.h#1 $ -// -// Library: Foundation -// Package: Threading -// Module: ErrorHandler -// -// Definition of the ErrorHandler class. -// -// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_ErrorHandler_INCLUDED -#define Foundation_ErrorHandler_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/Exception.h" -#include "Poco/Mutex.h" - - -namespace Poco { - - -class Foundation_API ErrorHandler - /// This is the base class for thread error handlers. - /// - /// An unhandled exception that causes a thread to terminate is usually - /// silently ignored, since the class library cannot do anything meaningful - /// about it. - /// - /// The Thread class provides the possibility to register a - /// global ErrorHandler that is invoked whenever a thread has - /// been terminated by an unhandled exception. - /// The ErrorHandler must be derived from this class and can - /// provide implementations of all three handleException() overloads. - /// - /// The ErrorHandler is always invoked within the context of - /// the offending thread. -{ -public: - ErrorHandler(); - /// Creates the ErrorHandler. - - virtual ~ErrorHandler(); - /// Destroys the ErrorHandler. - - virtual void exception(const Exception& exc); - /// Called when a Poco::Exception (or a subclass) - /// caused the thread to terminate. - /// - /// This method should not throw any exception - it would - /// be silently ignored. - /// - /// The default implementation just breaks into the debugger. - - virtual void exception(const std::exception& exc); - /// Called when a std::exception (or a subclass) - /// caused the thread to terminate. - /// - /// This method should not throw any exception - it would - /// be silently ignored. - /// - /// The default implementation just breaks into the debugger. - - virtual void exception(); - /// Called when an exception that is neither a - /// Poco::Exception nor a std::exception caused - /// the thread to terminate. - /// - /// This method should not throw any exception - it would - /// be silently ignored. - /// - /// The default implementation just breaks into the debugger. - - static void handle(const Exception& exc); - /// Invokes the currently registered ErrorHandler. - - static void handle(const std::exception& exc); - /// Invokes the currently registered ErrorHandler. - - static void handle(); - /// Invokes the currently registered ErrorHandler. - - static ErrorHandler* set(ErrorHandler* pHandler); - /// Registers the given handler as the current error handler. - /// - /// Returns the previously registered handler. - - static ErrorHandler* get(); - /// Returns a pointer to the currently registered - /// ErrorHandler. - -protected: - static ErrorHandler* defaultHandler(); - /// Returns the default ErrorHandler. - -private: - static ErrorHandler* _pHandler; - static FastMutex _mutex; -}; - - -// -// inlines -// -inline ErrorHandler* ErrorHandler::get() -{ - return _pHandler; -} - - -} // namespace Poco - - -#endif // Foundation_ErrorHandler_INCLUDED +// +// ErrorHandler.h +// +// $Id: //poco/1.2/Foundation/include/Poco/ErrorHandler.h#1 $ +// +// Library: Foundation +// Package: Threading +// Module: ErrorHandler +// +// Definition of the ErrorHandler class. +// +// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_ErrorHandler_INCLUDED +#define Foundation_ErrorHandler_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Exception.h" +#include "Poco/Mutex.h" + + +namespace Poco { + + +class Foundation_API ErrorHandler + /// This is the base class for thread error handlers. + /// + /// An unhandled exception that causes a thread to terminate is usually + /// silently ignored, since the class library cannot do anything meaningful + /// about it. + /// + /// The Thread class provides the possibility to register a + /// global ErrorHandler that is invoked whenever a thread has + /// been terminated by an unhandled exception. + /// The ErrorHandler must be derived from this class and can + /// provide implementations of all three handleException() overloads. + /// + /// The ErrorHandler is always invoked within the context of + /// the offending thread. +{ +public: + ErrorHandler(); + /// Creates the ErrorHandler. + + virtual ~ErrorHandler(); + /// Destroys the ErrorHandler. + + virtual void exception(const Exception& exc); + /// Called when a Poco::Exception (or a subclass) + /// caused the thread to terminate. + /// + /// This method should not throw any exception - it would + /// be silently ignored. + /// + /// The default implementation just breaks into the debugger. + + virtual void exception(const std::exception& exc); + /// Called when a std::exception (or a subclass) + /// caused the thread to terminate. + /// + /// This method should not throw any exception - it would + /// be silently ignored. + /// + /// The default implementation just breaks into the debugger. + + virtual void exception(); + /// Called when an exception that is neither a + /// Poco::Exception nor a std::exception caused + /// the thread to terminate. + /// + /// This method should not throw any exception - it would + /// be silently ignored. + /// + /// The default implementation just breaks into the debugger. + + static void handle(const Exception& exc); + /// Invokes the currently registered ErrorHandler. + + static void handle(const std::exception& exc); + /// Invokes the currently registered ErrorHandler. + + static void handle(); + /// Invokes the currently registered ErrorHandler. + + static ErrorHandler* set(ErrorHandler* pHandler); + /// Registers the given handler as the current error handler. + /// + /// Returns the previously registered handler. + + static ErrorHandler* get(); + /// Returns a pointer to the currently registered + /// ErrorHandler. + +protected: + static ErrorHandler* defaultHandler(); + /// Returns the default ErrorHandler. + +private: + static ErrorHandler* _pHandler; + static FastMutex _mutex; +}; + + +// +// inlines +// +inline ErrorHandler* ErrorHandler::get() +{ + return _pHandler; +} + + +} // namespace Poco + + +#endif // Foundation_ErrorHandler_INCLUDED diff --git a/Foundation/include/Poco/Event.h b/Foundation/include/Poco/Event.h index 77786d222..fdcb0ed86 100644 --- a/Foundation/include/Poco/Event.h +++ b/Foundation/include/Poco/Event.h @@ -1,143 +1,143 @@ -// -// Event.h -// -// $Id: //poco/1.2/Foundation/include/Poco/Event.h#1 $ -// -// Library: Foundation -// Package: Threading -// Module: Event -// -// Definition of the Event class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_Event_INCLUDED -#define Foundation_Event_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/Exception.h" - - -#if defined(POCO_OS_FAMILY_WINDOWS) -#include "Poco/Event_WIN32.h" -#else -#include "Poco/Event_POSIX.h" -#endif - - -namespace Poco { - - -class Foundation_API Event: private EventImpl - /// An Event is a synchronization object that - /// allows one thread to signal one or more - /// other threads that a certain event - /// has happened. - /// Usually, one thread signals an event, - /// while one or more other threads wait - /// for an event to become signalled. -{ -public: - Event(bool autoReset = true); - /// Creates the event. If autoReset is true, - /// the event is automatically reset after - /// a wait() successfully returns. - - ~Event(); - /// Destroys the event. - - void set(); - /// Signals the event. If autoReset is true, - /// only one thread waiting for the event - /// can resume execution. - /// If autoReset is false, all waiting threads - /// can resume execution. - - void wait(); - /// Waits for the event to become signalled. - - void wait(long milliseconds); - /// Waits for the event to become signalled. - /// Throws a TimeOutException if the event - /// does not become signalled within the specified - /// time interval. - - bool tryWait(long milliseconds); - /// Waits for the event to become signalled. - /// Returns true if the event - /// became signalled within the specified - /// time interval, false otherwise. - - void reset(); - /// Resets the event to unsignalled state. - -private: - Event(const Event&); - Event& operator = (const Event&); -}; - - -// -// inlines -// -inline void Event::set() -{ - setImpl(); -} - - -inline void Event::wait() -{ - waitImpl(); -} - - -inline void Event::wait(long milliseconds) -{ - if (!waitImpl(milliseconds)) - throw TimeoutException(); -} - - -inline bool Event::tryWait(long milliseconds) -{ - return waitImpl(milliseconds); -} - - -inline void Event::reset() -{ - resetImpl(); -} - - -} // namespace Poco - - -#endif // Foundation_Event_INCLUDED +// +// Event.h +// +// $Id: //poco/1.2/Foundation/include/Poco/Event.h#1 $ +// +// Library: Foundation +// Package: Threading +// Module: Event +// +// Definition of the Event class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_Event_INCLUDED +#define Foundation_Event_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Exception.h" + + +#if defined(POCO_OS_FAMILY_WINDOWS) +#include "Poco/Event_WIN32.h" +#else +#include "Poco/Event_POSIX.h" +#endif + + +namespace Poco { + + +class Foundation_API Event: private EventImpl + /// An Event is a synchronization object that + /// allows one thread to signal one or more + /// other threads that a certain event + /// has happened. + /// Usually, one thread signals an event, + /// while one or more other threads wait + /// for an event to become signalled. +{ +public: + Event(bool autoReset = true); + /// Creates the event. If autoReset is true, + /// the event is automatically reset after + /// a wait() successfully returns. + + ~Event(); + /// Destroys the event. + + void set(); + /// Signals the event. If autoReset is true, + /// only one thread waiting for the event + /// can resume execution. + /// If autoReset is false, all waiting threads + /// can resume execution. + + void wait(); + /// Waits for the event to become signalled. + + void wait(long milliseconds); + /// Waits for the event to become signalled. + /// Throws a TimeOutException if the event + /// does not become signalled within the specified + /// time interval. + + bool tryWait(long milliseconds); + /// Waits for the event to become signalled. + /// Returns true if the event + /// became signalled within the specified + /// time interval, false otherwise. + + void reset(); + /// Resets the event to unsignalled state. + +private: + Event(const Event&); + Event& operator = (const Event&); +}; + + +// +// inlines +// +inline void Event::set() +{ + setImpl(); +} + + +inline void Event::wait() +{ + waitImpl(); +} + + +inline void Event::wait(long milliseconds) +{ + if (!waitImpl(milliseconds)) + throw TimeoutException(); +} + + +inline bool Event::tryWait(long milliseconds) +{ + return waitImpl(milliseconds); +} + + +inline void Event::reset() +{ + resetImpl(); +} + + +} // namespace Poco + + +#endif // Foundation_Event_INCLUDED diff --git a/Foundation/include/Poco/EventArgs.h b/Foundation/include/Poco/EventArgs.h index 9acc68b5c..3b7dd0fdb 100644 --- a/Foundation/include/Poco/EventArgs.h +++ b/Foundation/include/Poco/EventArgs.h @@ -1,66 +1,66 @@ -// -// EventArgs.h -// -// $Id: //poco/1.2/Foundation/include/Poco/EventArgs.h#1 $ -// -// Library: Foundation -// Package: Events -// Module: EventArgs -// -// Definition of EventArgs. -// -// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_EventArgs_INCLUDED -#define Foundation_EventArgs_INCLUDED - - -#include "Poco/Foundation.h" - - -namespace Poco { - - -class Foundation_API EventArgs - /// The purpose of the EventArgs class is to be used as parameter - /// when one doesn't want to send any data. - /// One can use EventArgs as a super-class for one's own event arguments - /// but with the arguments being a template parameter this is not - /// necessary. -{ -public: - EventArgs(); - - virtual ~EventArgs(); -}; - - -} // namespace Poco - - -#endif +// +// EventArgs.h +// +// $Id: //poco/1.2/Foundation/include/Poco/EventArgs.h#1 $ +// +// Library: Foundation +// Package: Events +// Module: EventArgs +// +// Definition of EventArgs. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_EventArgs_INCLUDED +#define Foundation_EventArgs_INCLUDED + + +#include "Poco/Foundation.h" + + +namespace Poco { + + +class Foundation_API EventArgs + /// The purpose of the EventArgs class is to be used as parameter + /// when one doesn't want to send any data. + /// One can use EventArgs as a super-class for one's own event arguments + /// but with the arguments being a template parameter this is not + /// necessary. +{ +public: + EventArgs(); + + virtual ~EventArgs(); +}; + + +} // namespace Poco + + +#endif diff --git a/Foundation/include/Poco/EventLogChannel.h b/Foundation/include/Poco/EventLogChannel.h index 90f51b428..c0c47aedd 100644 --- a/Foundation/include/Poco/EventLogChannel.h +++ b/Foundation/include/Poco/EventLogChannel.h @@ -1,127 +1,127 @@ -// -// EventLogChannel.h -// -// $Id: //poco/1.2/Foundation/include/Poco/EventLogChannel.h#2 $ -// -// Library: Foundation -// Package: Logging -// Module: EventLogChannel -// -// Definition of the EventLogChannel class specific to WIN32. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_EventLogChannel_INCLUDED -#define Foundation_EventLogChannel_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/Channel.h" -#include - - -namespace Poco { - - -class Foundation_API EventLogChannel: public Channel - /// This Windows-only channel works with the Windows NT Event Log - /// service. - /// - /// To work properly, the EventLogChannel class requires that either - /// the PocoFoundation.dll or the PocoMsg.dll Dynamic Link Library - /// containing the message definition resources can be found in $PATH. -{ -public: - EventLogChannel(); - /// Creates the EventLogChannel. - /// The name of the current application (or more correctly, - /// the name of its executable) is taken as event source name. - - EventLogChannel(const std::string& name); - /// Creates the EventLogChannel with the given event source name. - - EventLogChannel(const std::string& name, const std::string& host); - /// Creates an EventLogChannel with the given event source - /// name that routes messages to the given host. - - void open(); - /// Opens the EventLogChannel. If necessary, the - /// required registry entries to register a - /// message resource DLL are made. - - void close(); - /// Closes the EventLogChannel. - - void log(const Message& msg); - /// Logs the given message to the Windows Event Log. - /// - /// The message type and priority are mapped to - /// appropriate values for Event Log type and category. - - void setProperty(const std::string& name, const std::string& value); - /// Sets or changes a configuration property. - /// - /// The following properties are supported: - /// - /// * name: The name of the event source. - /// * loghost: The name of the host where the Event Log service is running. - /// The default is "localhost". - /// * host: same as host. - /// * logfile: The name of the log file. The default is "Application". - - std::string getProperty(const std::string& name) const; - /// Returns the value of the given property. - - static const std::string PROP_NAME; - static const std::string PROP_HOST; - static const std::string PROP_LOGHOST; - static const std::string PROP_LOGFILE; - -protected: - ~EventLogChannel(); - static int getType(const Message& msg); - static int getCategory(const Message& msg); - void setUpRegistry() const; -#if defined(POCO_WIN32_UTF8) - static std::wstring findLibrary(const wchar_t* name); -#else - static std::string findLibrary(const char* name); -#endif - -private: - std::string _name; - std::string _host; - std::string _logFile; - HANDLE _h; -}; - - -} // namespace Poco - - -#endif // Foundation_EventLogChannel_INCLUDED +// +// EventLogChannel.h +// +// $Id: //poco/1.2/Foundation/include/Poco/EventLogChannel.h#2 $ +// +// Library: Foundation +// Package: Logging +// Module: EventLogChannel +// +// Definition of the EventLogChannel class specific to WIN32. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_EventLogChannel_INCLUDED +#define Foundation_EventLogChannel_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Channel.h" +#include + + +namespace Poco { + + +class Foundation_API EventLogChannel: public Channel + /// This Windows-only channel works with the Windows NT Event Log + /// service. + /// + /// To work properly, the EventLogChannel class requires that either + /// the PocoFoundation.dll or the PocoMsg.dll Dynamic Link Library + /// containing the message definition resources can be found in $PATH. +{ +public: + EventLogChannel(); + /// Creates the EventLogChannel. + /// The name of the current application (or more correctly, + /// the name of its executable) is taken as event source name. + + EventLogChannel(const std::string& name); + /// Creates the EventLogChannel with the given event source name. + + EventLogChannel(const std::string& name, const std::string& host); + /// Creates an EventLogChannel with the given event source + /// name that routes messages to the given host. + + void open(); + /// Opens the EventLogChannel. If necessary, the + /// required registry entries to register a + /// message resource DLL are made. + + void close(); + /// Closes the EventLogChannel. + + void log(const Message& msg); + /// Logs the given message to the Windows Event Log. + /// + /// The message type and priority are mapped to + /// appropriate values for Event Log type and category. + + void setProperty(const std::string& name, const std::string& value); + /// Sets or changes a configuration property. + /// + /// The following properties are supported: + /// + /// * name: The name of the event source. + /// * loghost: The name of the host where the Event Log service is running. + /// The default is "localhost". + /// * host: same as host. + /// * logfile: The name of the log file. The default is "Application". + + std::string getProperty(const std::string& name) const; + /// Returns the value of the given property. + + static const std::string PROP_NAME; + static const std::string PROP_HOST; + static const std::string PROP_LOGHOST; + static const std::string PROP_LOGFILE; + +protected: + ~EventLogChannel(); + static int getType(const Message& msg); + static int getCategory(const Message& msg); + void setUpRegistry() const; +#if defined(POCO_WIN32_UTF8) + static std::wstring findLibrary(const wchar_t* name); +#else + static std::string findLibrary(const char* name); +#endif + +private: + std::string _name; + std::string _host; + std::string _logFile; + HANDLE _h; +}; + + +} // namespace Poco + + +#endif // Foundation_EventLogChannel_INCLUDED diff --git a/Foundation/include/Poco/Event_POSIX.h b/Foundation/include/Poco/Event_POSIX.h index 875b37aa3..f3fcd7eb7 100644 --- a/Foundation/include/Poco/Event_POSIX.h +++ b/Foundation/include/Poco/Event_POSIX.h @@ -1,99 +1,99 @@ -// -// Event_POSIX.h -// -// $Id: //poco/1.2/Foundation/include/Poco/Event_POSIX.h#1 $ -// -// Library: Foundation -// Package: Threading -// Module: Event -// -// Definition of the EventImpl class for POSIX Threads. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_Event_POSIX_INCLUDED -#define Foundation_Event_POSIX_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/Exception.h" -#include -#include - - -namespace Poco { - - -class Foundation_API EventImpl -{ -protected: - EventImpl(bool autoReset); - ~EventImpl(); - void setImpl(); - void waitImpl(); - bool waitImpl(long milliseconds); - void resetImpl(); - -private: - bool _auto; - volatile bool _state; - pthread_mutex_t _mutex; - pthread_cond_t _cond; -}; - - -// -// inlines -// -inline void EventImpl::setImpl() -{ - if (pthread_mutex_lock(&_mutex)) - throw SystemException("cannot signal event (lock)"); - _state = true; - if (pthread_cond_broadcast(&_cond)) - { - pthread_mutex_unlock(&_mutex); - throw SystemException("cannot signal event"); - } - pthread_mutex_unlock(&_mutex); -} - - -inline void EventImpl::resetImpl() -{ - if (pthread_mutex_lock(&_mutex)) - throw SystemException("cannot reset event"); - _state = false; - pthread_mutex_unlock(&_mutex); -} - - -} // namespace Poco - - -#endif // Foundation_Event_POSIX_INCLUDED +// +// Event_POSIX.h +// +// $Id: //poco/1.2/Foundation/include/Poco/Event_POSIX.h#1 $ +// +// Library: Foundation +// Package: Threading +// Module: Event +// +// Definition of the EventImpl class for POSIX Threads. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_Event_POSIX_INCLUDED +#define Foundation_Event_POSIX_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Exception.h" +#include +#include + + +namespace Poco { + + +class Foundation_API EventImpl +{ +protected: + EventImpl(bool autoReset); + ~EventImpl(); + void setImpl(); + void waitImpl(); + bool waitImpl(long milliseconds); + void resetImpl(); + +private: + bool _auto; + volatile bool _state; + pthread_mutex_t _mutex; + pthread_cond_t _cond; +}; + + +// +// inlines +// +inline void EventImpl::setImpl() +{ + if (pthread_mutex_lock(&_mutex)) + throw SystemException("cannot signal event (lock)"); + _state = true; + if (pthread_cond_broadcast(&_cond)) + { + pthread_mutex_unlock(&_mutex); + throw SystemException("cannot signal event"); + } + pthread_mutex_unlock(&_mutex); +} + + +inline void EventImpl::resetImpl() +{ + if (pthread_mutex_lock(&_mutex)) + throw SystemException("cannot reset event"); + _state = false; + pthread_mutex_unlock(&_mutex); +} + + +} // namespace Poco + + +#endif // Foundation_Event_POSIX_INCLUDED diff --git a/Foundation/include/Poco/Event_WIN32.h b/Foundation/include/Poco/Event_WIN32.h index 753782988..064fe6a08 100644 --- a/Foundation/include/Poco/Event_WIN32.h +++ b/Foundation/include/Poco/Event_WIN32.h @@ -1,90 +1,90 @@ -// -// Event_WIN32.h -// -// $Id: //poco/1.2/Foundation/include/Poco/Event_WIN32.h#1 $ -// -// Library: Foundation -// Package: Threading -// Module: Event -// -// Definition of the EventImpl class for WIN32. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_Event_WIN32_INCLUDED -#define Foundation_Event_WIN32_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/Exception.h" -#include - - -namespace Poco { - - -class Foundation_API EventImpl -{ -protected: - EventImpl(bool autoReset = false); - ~EventImpl(); - void setImpl(); - void waitImpl(); - bool waitImpl(long milliseconds); - void resetImpl(); - -private: - HANDLE _event; -}; - - -// -// inlines -// -inline void EventImpl::setImpl() -{ - if (!SetEvent(_event)) - { - throw SystemException("cannot signal event"); - } -} - - -inline void EventImpl::resetImpl() -{ - if (!ResetEvent(_event)) - { - throw SystemException("cannot reset event"); - } -} - - -} // namespace Poco - - -#endif // Foundation_Event_WIN32_INCLUDED +// +// Event_WIN32.h +// +// $Id: //poco/1.2/Foundation/include/Poco/Event_WIN32.h#1 $ +// +// Library: Foundation +// Package: Threading +// Module: Event +// +// Definition of the EventImpl class for WIN32. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_Event_WIN32_INCLUDED +#define Foundation_Event_WIN32_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Exception.h" +#include + + +namespace Poco { + + +class Foundation_API EventImpl +{ +protected: + EventImpl(bool autoReset = false); + ~EventImpl(); + void setImpl(); + void waitImpl(); + bool waitImpl(long milliseconds); + void resetImpl(); + +private: + HANDLE _event; +}; + + +// +// inlines +// +inline void EventImpl::setImpl() +{ + if (!SetEvent(_event)) + { + throw SystemException("cannot signal event"); + } +} + + +inline void EventImpl::resetImpl() +{ + if (!ResetEvent(_event)) + { + throw SystemException("cannot reset event"); + } +} + + +} // namespace Poco + + +#endif // Foundation_Event_WIN32_INCLUDED diff --git a/Foundation/include/Poco/Exception.h b/Foundation/include/Poco/Exception.h index 05718e3b0..a28228791 100644 --- a/Foundation/include/Poco/Exception.h +++ b/Foundation/include/Poco/Exception.h @@ -1,252 +1,252 @@ -// -// Exception.h -// -// $Id: //poco/1.2/Foundation/include/Poco/Exception.h#1 $ -// -// Library: Foundation -// Package: Core -// Module: Exception -// -// Definition of various Poco exception classes. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_Exception_INCLUDED -#define Foundation_Exception_INCLUDED - - -#include "Poco/Foundation.h" -#include - - -namespace Poco { - - -class Foundation_API Exception: public std::exception - /// This is the base class for all exceptions defined - /// in the Poco class library. -{ -public: - Exception(const std::string& msg); - /// Creates an exception. - - Exception(const std::string& msg, const std::string& arg); - /// Creates an exception. - - Exception(const std::string& msg, const Exception& nested); - /// Creates an exception and stores a clone - /// of the nested exception. - - Exception(const Exception& exc); - /// Copy constructor. - - ~Exception() throw(); - /// Destroys the exception and deletes the nested exception. - - Exception& operator = (const Exception& exc); - /// Assignment operator. - - virtual const char* name() const throw(); - /// Returns a static string describing the exception. - - virtual const char* className() const throw(); - /// Returns the name of the exception class. - - virtual const char* what() const throw(); - /// Returns the message text as a C string. - - const Exception* nested() const; - /// Returns a pointer to the nested exception, or - /// null if no nested exception exists. - - const std::string& message() const; - /// Returns the message text. - - std::string displayText() const; - /// Returns a string consisting of the - /// message name and the message text. - - virtual Exception* clone() const; - /// Creates an exact copy of the exception. - /// - /// The copy can later be thrown again by - /// invoking rethrow() on it. - - virtual void rethrow() const; - /// (Re)Throws the exception. - /// - /// This is useful for temporarily storing a - /// copy of an exception (see clone()), then - /// throwing it again. - -protected: - Exception(); - /// Standard constructor. - -private: - std::string _msg; - Exception* _pNested; -}; - - -// -// inlines -// -inline const Exception* Exception::nested() const -{ - return _pNested; -} - - -inline const std::string& Exception::message() const -{ - return _msg; -} - - -// -// Macros for quickly declaring and implementing exception classes. -// Unfortunately, we cannot use a template here because character -// pointers (which we need for specifying the exception name) -// are not allowed as template arguments. -// -#define POCO_DECLARE_EXCEPTION(API, CLS, BASE) \ - class API CLS: public BASE \ - { \ - public: \ - CLS(); \ - CLS(const std::string& msg); \ - CLS(const std::string& msg, const std::string& arg); \ - CLS(const std::string& msg, const Poco::Exception& exc); \ - CLS(const CLS& exc); \ - ~CLS() throw(); \ - CLS& operator = (const CLS& exc); \ - const char* name() const throw(); \ - const char* className() const throw(); \ - Poco::Exception* clone() const; \ - void rethrow() const; \ - }; - - -#define POCO_IMPLEMENT_EXCEPTION(CLS, BASE, NAME) \ - CLS::CLS() \ - { \ - } \ - CLS::CLS(const std::string& msg): BASE(msg) \ - { \ - } \ - CLS::CLS(const std::string& msg, const std::string& arg): BASE(msg, arg) \ - { \ - } \ - CLS::CLS(const std::string& msg, const Poco::Exception& exc): BASE(msg, exc) \ - { \ - } \ - CLS::CLS(const CLS& exc): BASE(exc) \ - { \ - } \ - CLS::~CLS() throw() \ - { \ - } \ - CLS& CLS::operator = (const CLS& exc) \ - { \ - BASE::operator = (exc); \ - return *this; \ - } \ - const char* CLS::name() const throw() \ - { \ - return NAME; \ - } \ - const char* CLS::className() const throw() \ - { \ - return typeid(*this).name(); \ - } \ - Poco::Exception* CLS::clone() const \ - { \ - return new CLS(*this); \ - } \ - void CLS::rethrow() const \ - { \ - throw *this; \ - } - - -// -// Standard exception classes -// -POCO_DECLARE_EXCEPTION(Foundation_API, LogicException, Exception) -POCO_DECLARE_EXCEPTION(Foundation_API, AssertionViolationException, LogicException) -POCO_DECLARE_EXCEPTION(Foundation_API, NullPointerException, LogicException) -POCO_DECLARE_EXCEPTION(Foundation_API, BugcheckException, LogicException) -POCO_DECLARE_EXCEPTION(Foundation_API, InvalidArgumentException, LogicException) -POCO_DECLARE_EXCEPTION(Foundation_API, NotImplementedException, LogicException) -POCO_DECLARE_EXCEPTION(Foundation_API, RangeException, LogicException) -POCO_DECLARE_EXCEPTION(Foundation_API, IllegalStateException, LogicException) -POCO_DECLARE_EXCEPTION(Foundation_API, InvalidAccessException, LogicException) -POCO_DECLARE_EXCEPTION(Foundation_API, SignalException, LogicException) -POCO_DECLARE_EXCEPTION(Foundation_API, UnhandledException, LogicException) - -POCO_DECLARE_EXCEPTION(Foundation_API, RuntimeException, Exception) -POCO_DECLARE_EXCEPTION(Foundation_API, NotFoundException, RuntimeException) -POCO_DECLARE_EXCEPTION(Foundation_API, ExistsException, RuntimeException) -POCO_DECLARE_EXCEPTION(Foundation_API, TimeoutException, RuntimeException) -POCO_DECLARE_EXCEPTION(Foundation_API, SystemException, RuntimeException) -POCO_DECLARE_EXCEPTION(Foundation_API, RegularExpressionException, RuntimeException) -POCO_DECLARE_EXCEPTION(Foundation_API, LibraryLoadException, RuntimeException) -POCO_DECLARE_EXCEPTION(Foundation_API, LibraryAlreadyLoadedException, RuntimeException) -POCO_DECLARE_EXCEPTION(Foundation_API, NoThreadAvailableException, RuntimeException) -POCO_DECLARE_EXCEPTION(Foundation_API, PropertyNotSupportedException, RuntimeException) -POCO_DECLARE_EXCEPTION(Foundation_API, PoolOverflowException, RuntimeException) -POCO_DECLARE_EXCEPTION(Foundation_API, NoPermissionException, RuntimeException) -POCO_DECLARE_EXCEPTION(Foundation_API, OutOfMemoryException, RuntimeException) -POCO_DECLARE_EXCEPTION(Foundation_API, DataException, RuntimeException) - -POCO_DECLARE_EXCEPTION(Foundation_API, DataFormatException, DataException) -POCO_DECLARE_EXCEPTION(Foundation_API, SyntaxException, DataException) -POCO_DECLARE_EXCEPTION(Foundation_API, CircularReferenceException, DataException) -POCO_DECLARE_EXCEPTION(Foundation_API, PathSyntaxException, SyntaxException) -POCO_DECLARE_EXCEPTION(Foundation_API, IOException, RuntimeException) -POCO_DECLARE_EXCEPTION(Foundation_API, FileException, IOException) -POCO_DECLARE_EXCEPTION(Foundation_API, FileExistsException, FileException) -POCO_DECLARE_EXCEPTION(Foundation_API, FileNotFoundException, FileException) -POCO_DECLARE_EXCEPTION(Foundation_API, PathNotFoundException, FileException) -POCO_DECLARE_EXCEPTION(Foundation_API, FileReadOnlyException, FileException) -POCO_DECLARE_EXCEPTION(Foundation_API, FileAccessDeniedException, FileException) -POCO_DECLARE_EXCEPTION(Foundation_API, CreateFileException, FileException) -POCO_DECLARE_EXCEPTION(Foundation_API, OpenFileException, FileException) -POCO_DECLARE_EXCEPTION(Foundation_API, WriteFileException, FileException) -POCO_DECLARE_EXCEPTION(Foundation_API, ReadFileException, FileException) -POCO_DECLARE_EXCEPTION(Foundation_API, UnknownURISchemeException, RuntimeException) - -POCO_DECLARE_EXCEPTION(Foundation_API, ApplicationException, Exception) -POCO_DECLARE_EXCEPTION(Foundation_API, BadCastException, RuntimeException) - - -} // namespace Poco - - -#endif // Foundation_Exception_INCLUDED +// +// Exception.h +// +// $Id: //poco/1.2/Foundation/include/Poco/Exception.h#1 $ +// +// Library: Foundation +// Package: Core +// Module: Exception +// +// Definition of various Poco exception classes. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_Exception_INCLUDED +#define Foundation_Exception_INCLUDED + + +#include "Poco/Foundation.h" +#include + + +namespace Poco { + + +class Foundation_API Exception: public std::exception + /// This is the base class for all exceptions defined + /// in the Poco class library. +{ +public: + Exception(const std::string& msg); + /// Creates an exception. + + Exception(const std::string& msg, const std::string& arg); + /// Creates an exception. + + Exception(const std::string& msg, const Exception& nested); + /// Creates an exception and stores a clone + /// of the nested exception. + + Exception(const Exception& exc); + /// Copy constructor. + + ~Exception() throw(); + /// Destroys the exception and deletes the nested exception. + + Exception& operator = (const Exception& exc); + /// Assignment operator. + + virtual const char* name() const throw(); + /// Returns a static string describing the exception. + + virtual const char* className() const throw(); + /// Returns the name of the exception class. + + virtual const char* what() const throw(); + /// Returns the message text as a C string. + + const Exception* nested() const; + /// Returns a pointer to the nested exception, or + /// null if no nested exception exists. + + const std::string& message() const; + /// Returns the message text. + + std::string displayText() const; + /// Returns a string consisting of the + /// message name and the message text. + + virtual Exception* clone() const; + /// Creates an exact copy of the exception. + /// + /// The copy can later be thrown again by + /// invoking rethrow() on it. + + virtual void rethrow() const; + /// (Re)Throws the exception. + /// + /// This is useful for temporarily storing a + /// copy of an exception (see clone()), then + /// throwing it again. + +protected: + Exception(); + /// Standard constructor. + +private: + std::string _msg; + Exception* _pNested; +}; + + +// +// inlines +// +inline const Exception* Exception::nested() const +{ + return _pNested; +} + + +inline const std::string& Exception::message() const +{ + return _msg; +} + + +// +// Macros for quickly declaring and implementing exception classes. +// Unfortunately, we cannot use a template here because character +// pointers (which we need for specifying the exception name) +// are not allowed as template arguments. +// +#define POCO_DECLARE_EXCEPTION(API, CLS, BASE) \ + class API CLS: public BASE \ + { \ + public: \ + CLS(); \ + CLS(const std::string& msg); \ + CLS(const std::string& msg, const std::string& arg); \ + CLS(const std::string& msg, const Poco::Exception& exc); \ + CLS(const CLS& exc); \ + ~CLS() throw(); \ + CLS& operator = (const CLS& exc); \ + const char* name() const throw(); \ + const char* className() const throw(); \ + Poco::Exception* clone() const; \ + void rethrow() const; \ + }; + + +#define POCO_IMPLEMENT_EXCEPTION(CLS, BASE, NAME) \ + CLS::CLS() \ + { \ + } \ + CLS::CLS(const std::string& msg): BASE(msg) \ + { \ + } \ + CLS::CLS(const std::string& msg, const std::string& arg): BASE(msg, arg) \ + { \ + } \ + CLS::CLS(const std::string& msg, const Poco::Exception& exc): BASE(msg, exc) \ + { \ + } \ + CLS::CLS(const CLS& exc): BASE(exc) \ + { \ + } \ + CLS::~CLS() throw() \ + { \ + } \ + CLS& CLS::operator = (const CLS& exc) \ + { \ + BASE::operator = (exc); \ + return *this; \ + } \ + const char* CLS::name() const throw() \ + { \ + return NAME; \ + } \ + const char* CLS::className() const throw() \ + { \ + return typeid(*this).name(); \ + } \ + Poco::Exception* CLS::clone() const \ + { \ + return new CLS(*this); \ + } \ + void CLS::rethrow() const \ + { \ + throw *this; \ + } + + +// +// Standard exception classes +// +POCO_DECLARE_EXCEPTION(Foundation_API, LogicException, Exception) +POCO_DECLARE_EXCEPTION(Foundation_API, AssertionViolationException, LogicException) +POCO_DECLARE_EXCEPTION(Foundation_API, NullPointerException, LogicException) +POCO_DECLARE_EXCEPTION(Foundation_API, BugcheckException, LogicException) +POCO_DECLARE_EXCEPTION(Foundation_API, InvalidArgumentException, LogicException) +POCO_DECLARE_EXCEPTION(Foundation_API, NotImplementedException, LogicException) +POCO_DECLARE_EXCEPTION(Foundation_API, RangeException, LogicException) +POCO_DECLARE_EXCEPTION(Foundation_API, IllegalStateException, LogicException) +POCO_DECLARE_EXCEPTION(Foundation_API, InvalidAccessException, LogicException) +POCO_DECLARE_EXCEPTION(Foundation_API, SignalException, LogicException) +POCO_DECLARE_EXCEPTION(Foundation_API, UnhandledException, LogicException) + +POCO_DECLARE_EXCEPTION(Foundation_API, RuntimeException, Exception) +POCO_DECLARE_EXCEPTION(Foundation_API, NotFoundException, RuntimeException) +POCO_DECLARE_EXCEPTION(Foundation_API, ExistsException, RuntimeException) +POCO_DECLARE_EXCEPTION(Foundation_API, TimeoutException, RuntimeException) +POCO_DECLARE_EXCEPTION(Foundation_API, SystemException, RuntimeException) +POCO_DECLARE_EXCEPTION(Foundation_API, RegularExpressionException, RuntimeException) +POCO_DECLARE_EXCEPTION(Foundation_API, LibraryLoadException, RuntimeException) +POCO_DECLARE_EXCEPTION(Foundation_API, LibraryAlreadyLoadedException, RuntimeException) +POCO_DECLARE_EXCEPTION(Foundation_API, NoThreadAvailableException, RuntimeException) +POCO_DECLARE_EXCEPTION(Foundation_API, PropertyNotSupportedException, RuntimeException) +POCO_DECLARE_EXCEPTION(Foundation_API, PoolOverflowException, RuntimeException) +POCO_DECLARE_EXCEPTION(Foundation_API, NoPermissionException, RuntimeException) +POCO_DECLARE_EXCEPTION(Foundation_API, OutOfMemoryException, RuntimeException) +POCO_DECLARE_EXCEPTION(Foundation_API, DataException, RuntimeException) + +POCO_DECLARE_EXCEPTION(Foundation_API, DataFormatException, DataException) +POCO_DECLARE_EXCEPTION(Foundation_API, SyntaxException, DataException) +POCO_DECLARE_EXCEPTION(Foundation_API, CircularReferenceException, DataException) +POCO_DECLARE_EXCEPTION(Foundation_API, PathSyntaxException, SyntaxException) +POCO_DECLARE_EXCEPTION(Foundation_API, IOException, RuntimeException) +POCO_DECLARE_EXCEPTION(Foundation_API, FileException, IOException) +POCO_DECLARE_EXCEPTION(Foundation_API, FileExistsException, FileException) +POCO_DECLARE_EXCEPTION(Foundation_API, FileNotFoundException, FileException) +POCO_DECLARE_EXCEPTION(Foundation_API, PathNotFoundException, FileException) +POCO_DECLARE_EXCEPTION(Foundation_API, FileReadOnlyException, FileException) +POCO_DECLARE_EXCEPTION(Foundation_API, FileAccessDeniedException, FileException) +POCO_DECLARE_EXCEPTION(Foundation_API, CreateFileException, FileException) +POCO_DECLARE_EXCEPTION(Foundation_API, OpenFileException, FileException) +POCO_DECLARE_EXCEPTION(Foundation_API, WriteFileException, FileException) +POCO_DECLARE_EXCEPTION(Foundation_API, ReadFileException, FileException) +POCO_DECLARE_EXCEPTION(Foundation_API, UnknownURISchemeException, RuntimeException) + +POCO_DECLARE_EXCEPTION(Foundation_API, ApplicationException, Exception) +POCO_DECLARE_EXCEPTION(Foundation_API, BadCastException, RuntimeException) + + +} // namespace Poco + + +#endif // Foundation_Exception_INCLUDED diff --git a/Foundation/include/Poco/Expire.h b/Foundation/include/Poco/Expire.h index 4700b6919..7b45e9e07 100644 --- a/Foundation/include/Poco/Expire.h +++ b/Foundation/include/Poco/Expire.h @@ -1,132 +1,132 @@ -// -// Expire.h -// -// $Id: //poco/1.2/Foundation/include/Poco/Expire.h#2 $ -// -// Library: Foundation -// Package: Events -// Module: Expire -// -// Implementation of the Expire template. -// -// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_Expire_INCLUDED -#define Foundation_Expire_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/AbstractDelegate.h" -#include "Poco/Timestamp.h" - - -namespace Poco { - - -template -class Expire: public AbstractDelegate - /// Decorator for AbstractDelegate adding automatic - /// expiring of registrations to AbstractDelegates. -{ -public: - Expire(const AbstractDelegate& p, Timestamp::TimeDiff expireMillisecs): - AbstractDelegate(p), - _pDelegate(p.clone()), - _expire(expireMillisecs*1000) - { - } - - Expire(const Expire& expire): - AbstractDelegate(expire), - _pDelegate(expire._pDelegate->clone()), - _expire(expire._expire), - _creationTime(expire._creationTime) - { - } - - ~Expire() - { - destroy(); - } - - Expire& operator = (const Expire& expire) - { - if (&expire != this) - { - delete this->_pDelegate; - this->_pDelegate = expire._pDelegate->clone(); - this->_expire = expire._expire; - this->_creationTime = expire._creationTime; - this->_pTarget = expire._pTarget; - } - return *this; - } - - bool notify(const void* sender, TArgs& arguments) - { - if (!expired()) - return this->_pDelegate->notify(sender, arguments); - else - return false; - } - - AbstractDelegate* clone() const - { - return new Expire(*this); - } - - void destroy() - { - delete this->_pDelegate; - this->_pDelegate = 0; - } - - const AbstractDelegate& getDelegate() const - { - return *this->_pDelegate; - } - -protected: - bool expired() const - { - return _creationTime.isElapsed(_expire); - } - - AbstractDelegate* _pDelegate; - Timestamp::TimeDiff _expire; - Timestamp _creationTime; - -private: - Expire(); -}; - - -} // namespace Poco - - -#endif +// +// Expire.h +// +// $Id: //poco/1.2/Foundation/include/Poco/Expire.h#2 $ +// +// Library: Foundation +// Package: Events +// Module: Expire +// +// Implementation of the Expire template. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_Expire_INCLUDED +#define Foundation_Expire_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/AbstractDelegate.h" +#include "Poco/Timestamp.h" + + +namespace Poco { + + +template +class Expire: public AbstractDelegate + /// Decorator for AbstractDelegate adding automatic + /// expiring of registrations to AbstractDelegates. +{ +public: + Expire(const AbstractDelegate& p, Timestamp::TimeDiff expireMillisecs): + AbstractDelegate(p), + _pDelegate(p.clone()), + _expire(expireMillisecs*1000) + { + } + + Expire(const Expire& expire): + AbstractDelegate(expire), + _pDelegate(expire._pDelegate->clone()), + _expire(expire._expire), + _creationTime(expire._creationTime) + { + } + + ~Expire() + { + destroy(); + } + + Expire& operator = (const Expire& expire) + { + if (&expire != this) + { + delete this->_pDelegate; + this->_pDelegate = expire._pDelegate->clone(); + this->_expire = expire._expire; + this->_creationTime = expire._creationTime; + this->_pTarget = expire._pTarget; + } + return *this; + } + + bool notify(const void* sender, TArgs& arguments) + { + if (!expired()) + return this->_pDelegate->notify(sender, arguments); + else + return false; + } + + AbstractDelegate* clone() const + { + return new Expire(*this); + } + + void destroy() + { + delete this->_pDelegate; + this->_pDelegate = 0; + } + + const AbstractDelegate& getDelegate() const + { + return *this->_pDelegate; + } + +protected: + bool expired() const + { + return _creationTime.isElapsed(_expire); + } + + AbstractDelegate* _pDelegate; + Timestamp::TimeDiff _expire; + Timestamp _creationTime; + +private: + Expire(); +}; + + +} // namespace Poco + + +#endif diff --git a/Foundation/include/Poco/ExpireCache.h b/Foundation/include/Poco/ExpireCache.h index 2eb63a603..2d418bdb0 100644 --- a/Foundation/include/Poco/ExpireCache.h +++ b/Foundation/include/Poco/ExpireCache.h @@ -1,78 +1,78 @@ -// -// ExpireCache.h -// -// $Id: //poco/1.2/Foundation/include/Poco/ExpireCache.h#3 $ -// -// Library: Foundation -// Package: Cache -// Module: ExpireCache -// -// Definition of the ExpireCache class. -// -// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_ExpireCache_INCLUDED -#define Foundation_ExpireCache_INCLUDED - - -#include "Poco/AbstractCache.h" -#include "Poco/ExpireStrategy.h" - - -namespace Poco { - - -template -class ExpireCache: public AbstractCache > - /// An ExpireCache caches entries for a fixed time period (per default 10 minutes) - /// Be careful when using an ExpireCache. A cache is often used - /// like cache.has(x) followed by cache.get x). Note that it could happen - /// that the "has" call works, then the current execution thread gets descheduled, time passes, - /// the entry gets invalid, thus leading to an empty SharedPtr being returned - /// when "get" is invoked. -{ -public: - ExpireCache(Timestamp::TimeDiff expire = 600000): - AbstractCache >(ExpireStrategy(expire)) - { - } - - ~ExpireCache() - { - } - -private: - ExpireCache(const ExpireCache& aCache); - ExpireCache& operator = (const ExpireCache& aCache); -}; - - -} // namespace Poco - - -#endif +// +// ExpireCache.h +// +// $Id: //poco/1.2/Foundation/include/Poco/ExpireCache.h#3 $ +// +// Library: Foundation +// Package: Cache +// Module: ExpireCache +// +// Definition of the ExpireCache class. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_ExpireCache_INCLUDED +#define Foundation_ExpireCache_INCLUDED + + +#include "Poco/AbstractCache.h" +#include "Poco/ExpireStrategy.h" + + +namespace Poco { + + +template +class ExpireCache: public AbstractCache > + /// An ExpireCache caches entries for a fixed time period (per default 10 minutes) + /// Be careful when using an ExpireCache. A cache is often used + /// like cache.has(x) followed by cache.get x). Note that it could happen + /// that the "has" call works, then the current execution thread gets descheduled, time passes, + /// the entry gets invalid, thus leading to an empty SharedPtr being returned + /// when "get" is invoked. +{ +public: + ExpireCache(Timestamp::TimeDiff expire = 600000): + AbstractCache >(ExpireStrategy(expire)) + { + } + + ~ExpireCache() + { + } + +private: + ExpireCache(const ExpireCache& aCache); + ExpireCache& operator = (const ExpireCache& aCache); +}; + + +} // namespace Poco + + +#endif diff --git a/Foundation/include/Poco/ExpireLRUCache.h b/Foundation/include/Poco/ExpireLRUCache.h index 77960a978..62cc5deaa 100644 --- a/Foundation/include/Poco/ExpireLRUCache.h +++ b/Foundation/include/Poco/ExpireLRUCache.h @@ -1,82 +1,82 @@ -// -// ExpireLRUCache.h -// -// $Id: //poco/1.2/Foundation/include/Poco/ExpireLRUCache.h#4 $ -// -// Library: Foundation -// Package: Cache -// Module: ExpireLRUCache -// -// Definition of the ExpireLRUCache class. -// -// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_ExpireLRUCache_INCLUDED -#define Foundation_ExpireLRUCache_INCLUDED - - -#include "Poco/AbstractCache.h" -#include "Poco/StrategyCollection.h" -#include "Poco/ExpireStrategy.h" -#include "Poco/LRUStrategy.h" - - -namespace Poco { - - -template < - class TKey, - class TValue -> -class ExpireLRUCache: public AbstractCache > - /// An ExpireLRUCache combines LRU caching and time based expire caching. - /// It cache entries for a fixed time period (per default 10 minutes) - /// but also limits the size of the cache (per default: 1024). -{ -public: - ExpireLRUCache(long cacheSize = 1024, Timestamp::TimeDiff expire = 600000): - AbstractCache >(StrategyCollection()) - { - this->_strategy.pushBack(new LRUStrategy(cacheSize)); - this->_strategy.pushBack(new ExpireStrategy(expire)); - } - - ~ExpireLRUCache() - { - } - -private: - ExpireLRUCache(const ExpireLRUCache& aCache); - ExpireLRUCache& operator = (const ExpireLRUCache& aCache); -}; - - -} // namespace Poco - - -#endif +// +// ExpireLRUCache.h +// +// $Id: //poco/1.2/Foundation/include/Poco/ExpireLRUCache.h#4 $ +// +// Library: Foundation +// Package: Cache +// Module: ExpireLRUCache +// +// Definition of the ExpireLRUCache class. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_ExpireLRUCache_INCLUDED +#define Foundation_ExpireLRUCache_INCLUDED + + +#include "Poco/AbstractCache.h" +#include "Poco/StrategyCollection.h" +#include "Poco/ExpireStrategy.h" +#include "Poco/LRUStrategy.h" + + +namespace Poco { + + +template < + class TKey, + class TValue +> +class ExpireLRUCache: public AbstractCache > + /// An ExpireLRUCache combines LRU caching and time based expire caching. + /// It cache entries for a fixed time period (per default 10 minutes) + /// but also limits the size of the cache (per default: 1024). +{ +public: + ExpireLRUCache(long cacheSize = 1024, Timestamp::TimeDiff expire = 600000): + AbstractCache >(StrategyCollection()) + { + this->_strategy.pushBack(new LRUStrategy(cacheSize)); + this->_strategy.pushBack(new ExpireStrategy(expire)); + } + + ~ExpireLRUCache() + { + } + +private: + ExpireLRUCache(const ExpireLRUCache& aCache); + ExpireLRUCache& operator = (const ExpireLRUCache& aCache); +}; + + +} // namespace Poco + + +#endif diff --git a/Foundation/include/Poco/ExpireStrategy.h b/Foundation/include/Poco/ExpireStrategy.h index 325cf210c..8cddf116b 100644 --- a/Foundation/include/Poco/ExpireStrategy.h +++ b/Foundation/include/Poco/ExpireStrategy.h @@ -1,150 +1,150 @@ -// -// ExpireStrategy.h -// -// $Id: //poco/1.2/Foundation/include/Poco/ExpireStrategy.h#2 $ -// -// Library: Foundation -// Package: Cache -// Module: ExpireStrategy -// -// Definition of the ExpireStrategy class. -// -// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_ExpireStrategy_INCLUDED -#define Foundation_ExpireStrategy_INCLUDED - - -#include "Poco/KeyValueArgs.h" -#include "Poco/ValidArgs.h" -#include "Poco/AbstractStrategy.h" -#include "Poco/Bugcheck.h" -#include "Poco/Timestamp.h" -#include "Poco/EventArgs.h" -#include -#include - - -namespace Poco { - - -template < - class TKey, - class TValue -> -class ExpireStrategy: public AbstractStrategy - /// An ExpireStrategy implements time based expiration of cache entries -{ -public: - typedef std::multimap TimeIndex; - typedef typename TimeIndex::iterator IndexIterator; - typedef typename TimeIndex::const_iterator ConstIndexIterator; - typedef std::map Keys; - typedef typename Keys::iterator Iterator; - -public: - ExpireStrategy(Timestamp::TimeDiff expireTimeInMilliSec): _expireTime(expireTimeInMilliSec * 1000) - /// Create an expire strategy. Note that the smallest allowed caching time is 25ms. - /// Anything lower than that is not useful with current operating systems. - { - if (_expireTime < 25000) throw InvalidArgumentException("expireTime must be at least 25 ms"); - } - - ~ExpireStrategy() - { - } - - void onAdd(const void*, const KeyValueArgs & args) - { - Timestamp now; - IndexIterator it = _keyIndex.insert(std::make_pair(now, args.key())); - std::pair stat = _keys.insert(std::make_pair(args.key(), it)); - if (!stat.second) - { - _keyIndex.erase(stat.first->second); - stat.first->second = it; - } - } - - void onRemove(const void*, const TKey& key) - { - Iterator it = _keys.find(key); - if (it != _keys.end()) - { - _keyIndex.erase(it->second); - _keys.erase(it); - } - } - - void onGet(const void*, const TKey& key) - { - // get triggers no changes in an expire - } - - void onClear(const void*, const EventArgs& args) - { - _keys.clear(); - _keyIndex.clear(); - } - - void onIsValid(const void*, ValidArgs& args) - { - Iterator it = _keys.find(args.key()); - if (it != _keys.end()) - { - if (it->second->first.isElapsed(_expireTime)) - { - args.invalidate(); - } - } - } - - void onReplace(const void*, std::set& elemsToRemove) - { - // Note: replace only informs the cache which elements - // it would like to remove! - // it does not remove them on its own! - IndexIterator it = _keyIndex.begin(); - while (it != _keyIndex.end() && it->first.isElapsed(_expireTime)) - { - elemsToRemove.insert(it->second); - ++it; - } - } - -protected: - Timestamp::TimeDiff _expireTime; - Keys _keys; /// For faster replacement of keys, the iterator points to the _keyIndex map - TimeIndex _keyIndex; /// Maps time to key value -}; - - -} // namespace Poco - - -#endif +// +// ExpireStrategy.h +// +// $Id: //poco/1.2/Foundation/include/Poco/ExpireStrategy.h#2 $ +// +// Library: Foundation +// Package: Cache +// Module: ExpireStrategy +// +// Definition of the ExpireStrategy class. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_ExpireStrategy_INCLUDED +#define Foundation_ExpireStrategy_INCLUDED + + +#include "Poco/KeyValueArgs.h" +#include "Poco/ValidArgs.h" +#include "Poco/AbstractStrategy.h" +#include "Poco/Bugcheck.h" +#include "Poco/Timestamp.h" +#include "Poco/EventArgs.h" +#include +#include + + +namespace Poco { + + +template < + class TKey, + class TValue +> +class ExpireStrategy: public AbstractStrategy + /// An ExpireStrategy implements time based expiration of cache entries +{ +public: + typedef std::multimap TimeIndex; + typedef typename TimeIndex::iterator IndexIterator; + typedef typename TimeIndex::const_iterator ConstIndexIterator; + typedef std::map Keys; + typedef typename Keys::iterator Iterator; + +public: + ExpireStrategy(Timestamp::TimeDiff expireTimeInMilliSec): _expireTime(expireTimeInMilliSec * 1000) + /// Create an expire strategy. Note that the smallest allowed caching time is 25ms. + /// Anything lower than that is not useful with current operating systems. + { + if (_expireTime < 25000) throw InvalidArgumentException("expireTime must be at least 25 ms"); + } + + ~ExpireStrategy() + { + } + + void onAdd(const void*, const KeyValueArgs & args) + { + Timestamp now; + IndexIterator it = _keyIndex.insert(std::make_pair(now, args.key())); + std::pair stat = _keys.insert(std::make_pair(args.key(), it)); + if (!stat.second) + { + _keyIndex.erase(stat.first->second); + stat.first->second = it; + } + } + + void onRemove(const void*, const TKey& key) + { + Iterator it = _keys.find(key); + if (it != _keys.end()) + { + _keyIndex.erase(it->second); + _keys.erase(it); + } + } + + void onGet(const void*, const TKey& key) + { + // get triggers no changes in an expire + } + + void onClear(const void*, const EventArgs& args) + { + _keys.clear(); + _keyIndex.clear(); + } + + void onIsValid(const void*, ValidArgs& args) + { + Iterator it = _keys.find(args.key()); + if (it != _keys.end()) + { + if (it->second->first.isElapsed(_expireTime)) + { + args.invalidate(); + } + } + } + + void onReplace(const void*, std::set& elemsToRemove) + { + // Note: replace only informs the cache which elements + // it would like to remove! + // it does not remove them on its own! + IndexIterator it = _keyIndex.begin(); + while (it != _keyIndex.end() && it->first.isElapsed(_expireTime)) + { + elemsToRemove.insert(it->second); + ++it; + } + } + +protected: + Timestamp::TimeDiff _expireTime; + Keys _keys; /// For faster replacement of keys, the iterator points to the _keyIndex map + TimeIndex _keyIndex; /// Maps time to key value +}; + + +} // namespace Poco + + +#endif diff --git a/Foundation/include/Poco/FIFOEvent.h b/Foundation/include/Poco/FIFOEvent.h index d78cab1f5..f0b0ec0a1 100644 --- a/Foundation/include/Poco/FIFOEvent.h +++ b/Foundation/include/Poco/FIFOEvent.h @@ -1,90 +1,90 @@ -// -// FIFOEvent.h -// -// $Id: //poco/1.2/Foundation/include/Poco/FIFOEvent.h#1 $ -// -// Library: Foundation -// Package: Events -// Module: FIFOEvent -// -// Implementation of the FIFOEvent template. -// -// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_FIFOEvent_INCLUDED -#define Foundation_FIFOEvent_INCLUDED - - -#include "Poco/AbstractEvent.h" -#include "Poco/FIFOStrategy.h" -#include "Poco/AbstractDelegate.h" -#include "Poco/CompareFunctions.h" - - -namespace Poco { - - -template -class FIFOEvent: public AbstractEvent < - TArgs, - FIFOStrategy, p_less > >, - AbstractDelegate -> - /// A FIFOEvent uses internally a FIFOStrategy which guarantees - /// that delegates are invoked in the order they were added to - /// the event. - /// - /// Note that one object can only register one method to a FIFOEvent. - /// Subsequent registrations will overwrite the existing delegate. - /// For example: - /// FIFOEvent tmp; - /// MyClass myObject; - /// tmp += Delegate(&myObject, &MyClass::myMethod1); - /// tmp += Delegate(&myObject, &MyClass::myMethod2); - /// - /// The second registration will overwrite the first one. -{ -public: - FIFOEvent() - { - } - - ~FIFOEvent() - { - } - -private: - FIFOEvent(const FIFOEvent& e); - FIFOEvent& operator = (const FIFOEvent& e); -}; - - -} // namespace Poco - - -#endif +// +// FIFOEvent.h +// +// $Id: //poco/1.2/Foundation/include/Poco/FIFOEvent.h#1 $ +// +// Library: Foundation +// Package: Events +// Module: FIFOEvent +// +// Implementation of the FIFOEvent template. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_FIFOEvent_INCLUDED +#define Foundation_FIFOEvent_INCLUDED + + +#include "Poco/AbstractEvent.h" +#include "Poco/FIFOStrategy.h" +#include "Poco/AbstractDelegate.h" +#include "Poco/CompareFunctions.h" + + +namespace Poco { + + +template +class FIFOEvent: public AbstractEvent < + TArgs, + FIFOStrategy, p_less > >, + AbstractDelegate +> + /// A FIFOEvent uses internally a FIFOStrategy which guarantees + /// that delegates are invoked in the order they were added to + /// the event. + /// + /// Note that one object can only register one method to a FIFOEvent. + /// Subsequent registrations will overwrite the existing delegate. + /// For example: + /// FIFOEvent tmp; + /// MyClass myObject; + /// tmp += Delegate(&myObject, &MyClass::myMethod1); + /// tmp += Delegate(&myObject, &MyClass::myMethod2); + /// + /// The second registration will overwrite the first one. +{ +public: + FIFOEvent() + { + } + + ~FIFOEvent() + { + } + +private: + FIFOEvent(const FIFOEvent& e); + FIFOEvent& operator = (const FIFOEvent& e); +}; + + +} // namespace Poco + + +#endif diff --git a/Foundation/include/Poco/FIFOStrategy.h b/Foundation/include/Poco/FIFOStrategy.h index 642073049..917291112 100644 --- a/Foundation/include/Poco/FIFOStrategy.h +++ b/Foundation/include/Poco/FIFOStrategy.h @@ -1,160 +1,160 @@ -// -// FIFOStrategy.h -// -// $Id: //poco/1.2/Foundation/include/Poco/FIFOStrategy.h#1 $ -// -// Library: Foundation -// Package: Events -// Module: FIFOStragegy -// -// Implementation of the FIFOStrategy template. -// -// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_FIFOStrategy_INCLUDED -#define Foundation_FIFOStrategy_INCLUDED - - -#include "Poco/NotificationStrategy.h" -#include -#include - - -namespace Poco { - - -template -class FIFOStrategy: public NotificationStrategy -{ -public: - typedef std::list Delegates; - typedef typename Delegates::iterator Iterator; - typedef typename Delegates::const_iterator ConstIterator; - typedef std::map DelegateIndex; - typedef typename DelegateIndex::iterator IndexIterator; - typedef typename DelegateIndex::const_iterator ConstIndexIterator; - - FIFOStrategy() - { - } - - FIFOStrategy(const FIFOStrategy& s) - { - operator = (s); - } - - ~FIFOStrategy() - { - clear(); - } - - void notify(const void* sender, TArgs& arguments) - { - std::vector delMe; - Iterator it = _observers.begin(); - Iterator itEnd = _observers.end(); - - for (; it != itEnd; ++it) - { - if (!(*it)->notify(sender, arguments)) - { - // schedule for deletion - delMe.push_back(it); - } - } - - while (!delMe.empty()) - { - typename std::vector::iterator vit = delMe.end(); - --vit; - delete **vit; - _observers.erase(*vit); - delMe.pop_back(); - } - } - - void add(const TDelegate& delegate) - { - IndexIterator it = _observerIndex.find(const_cast(&delegate)); - if (it != _observerIndex.end()) - { - delete *it->second; - _observers.erase(it->second); - _observerIndex.erase(it); - } - std::auto_ptr pDelegate(delegate.clone()); - _observers.push_back(pDelegate.get()); - bool tmp = _observerIndex.insert(make_pair(pDelegate.get(), --_observers.end())).second; - poco_assert (tmp); - pDelegate.release(); - } - - void remove(const TDelegate& delegate) - { - IndexIterator it = _observerIndex.find(const_cast(&delegate)); - - if (it != _observerIndex.end()) - { - delete *it->second; - _observers.erase(it->second); - _observerIndex.erase(it); - } - } - - FIFOStrategy& operator = (const FIFOStrategy& s) - { - if (this != &s) - { - for (ConstIterator it = s._observers.begin(); it != s._observers.end(); ++it) - { - add(**it); - } - } - return *this; - } - - void clear() - { - for (Iterator it = _observers.begin(); it != _observers.end(); ++it) - { - delete *it; - } - - _observers.clear(); - _observerIndex.clear(); - } - -protected: - Delegates _observers; /// Stores the delegates in the order they were added. - DelegateIndex _observerIndex; /// For faster lookup when add/remove is used. -}; - - -} // namespace Poco - - -#endif +// +// FIFOStrategy.h +// +// $Id: //poco/1.2/Foundation/include/Poco/FIFOStrategy.h#1 $ +// +// Library: Foundation +// Package: Events +// Module: FIFOStragegy +// +// Implementation of the FIFOStrategy template. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_FIFOStrategy_INCLUDED +#define Foundation_FIFOStrategy_INCLUDED + + +#include "Poco/NotificationStrategy.h" +#include +#include + + +namespace Poco { + + +template +class FIFOStrategy: public NotificationStrategy +{ +public: + typedef std::list Delegates; + typedef typename Delegates::iterator Iterator; + typedef typename Delegates::const_iterator ConstIterator; + typedef std::map DelegateIndex; + typedef typename DelegateIndex::iterator IndexIterator; + typedef typename DelegateIndex::const_iterator ConstIndexIterator; + + FIFOStrategy() + { + } + + FIFOStrategy(const FIFOStrategy& s) + { + operator = (s); + } + + ~FIFOStrategy() + { + clear(); + } + + void notify(const void* sender, TArgs& arguments) + { + std::vector delMe; + Iterator it = _observers.begin(); + Iterator itEnd = _observers.end(); + + for (; it != itEnd; ++it) + { + if (!(*it)->notify(sender, arguments)) + { + // schedule for deletion + delMe.push_back(it); + } + } + + while (!delMe.empty()) + { + typename std::vector::iterator vit = delMe.end(); + --vit; + delete **vit; + _observers.erase(*vit); + delMe.pop_back(); + } + } + + void add(const TDelegate& delegate) + { + IndexIterator it = _observerIndex.find(const_cast(&delegate)); + if (it != _observerIndex.end()) + { + delete *it->second; + _observers.erase(it->second); + _observerIndex.erase(it); + } + std::auto_ptr pDelegate(delegate.clone()); + _observers.push_back(pDelegate.get()); + bool tmp = _observerIndex.insert(make_pair(pDelegate.get(), --_observers.end())).second; + poco_assert (tmp); + pDelegate.release(); + } + + void remove(const TDelegate& delegate) + { + IndexIterator it = _observerIndex.find(const_cast(&delegate)); + + if (it != _observerIndex.end()) + { + delete *it->second; + _observers.erase(it->second); + _observerIndex.erase(it); + } + } + + FIFOStrategy& operator = (const FIFOStrategy& s) + { + if (this != &s) + { + for (ConstIterator it = s._observers.begin(); it != s._observers.end(); ++it) + { + add(**it); + } + } + return *this; + } + + void clear() + { + for (Iterator it = _observers.begin(); it != _observers.end(); ++it) + { + delete *it; + } + + _observers.clear(); + _observerIndex.clear(); + } + +protected: + Delegates _observers; /// Stores the delegates in the order they were added. + DelegateIndex _observerIndex; /// For faster lookup when add/remove is used. +}; + + +} // namespace Poco + + +#endif diff --git a/Foundation/include/Poco/FPEnvironment.h b/Foundation/include/Poco/FPEnvironment.h index 327409ebc..e2e3255b1 100644 --- a/Foundation/include/Poco/FPEnvironment.h +++ b/Foundation/include/Poco/FPEnvironment.h @@ -1,227 +1,227 @@ -// -// FPEnvironment.h -// -// $Id: //poco/1.2/Foundation/include/Poco/FPEnvironment.h#1 $ -// -// Library: Foundation -// Package: Core -// Module: FPEnvironment -// -// Definitions of class FPEnvironment. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_FPEnvironment_INCLUDED -#define Foundation_FPEnvironment_INCLUDED - - -#include "Poco/Foundation.h" - - -#if defined(POCO_NO_FPENVIRONMENT) -#include "Poco/FPEnvironment_DUMMY.h" -#elif defined(__osf__) || defined(__VMS) -#include "Poco/FPEnvironment_DEC.h" -#elif defined(sun) || defined(__sun) -#include "Poco/FPEnvironment_SUN.h" -#elif defined(POCO_OS_FAMILY_UNIX) -#include "Poco/FPEnvironment_C99.h" -#elif defined(POCO_OS_FAMILY_WINDOWS) -#include "Poco/FPEnvironment_WIN32.h" -#else -#include "Poco/FPEnvironment_DUMMY.h" -#endif - - -namespace Poco { - - -class Foundation_API FPEnvironment: private FPEnvironmentImpl - /// Instances of this class can be used to save - /// and later restore the current floating - /// point environment (consisting of rounding - /// mode and floating-point flags). - /// The class also provides various static - /// methods to query certain properties - /// of a floating-point number. -{ -public: - enum RoundingMode - { - FP_ROUND_DOWNWARD = FP_ROUND_DOWNWARD_IMPL, - FP_ROUND_UPWARD = FP_ROUND_UPWARD_IMPL, - FP_ROUND_TONEAREST = FP_ROUND_TONEAREST_IMPL, - FP_ROUND_TOWARDZERO = FP_ROUND_TOWARDZERO_IMPL - }; - - enum Flag - { - FP_DIVIDE_BY_ZERO = FP_DIVIDE_BY_ZERO_IMPL, - FP_INEXACT = FP_INEXACT_IMPL, - FP_OVERFLOW = FP_OVERFLOW_IMPL, - FP_UNDERFLOW = FP_UNDERFLOW_IMPL, - FP_INVALID = FP_INVALID_IMPL - }; - - FPEnvironment(); - /// Standard constructor. - /// Remembers the current environment. - - FPEnvironment(RoundingMode mode); - /// Remembers the current environment and - /// sets the given rounding mode. - - FPEnvironment(const FPEnvironment& env); - /// Copy constructor. - - ~FPEnvironment(); - /// Restores the previous environment (unless - /// keepCurrent() has been called previously) - - FPEnvironment& operator = (const FPEnvironment& env); - /// Assignment operator - - void keepCurrent(); - /// Keep the current environment even after - /// destroying the FPEnvironment object. - - static void clearFlags(); - /// Resets all flags. - - static bool isFlag(Flag flag); - /// Returns true iff the given flag is set. - - static void setRoundingMode(RoundingMode mode); - /// Sets the rounding mode. - - static RoundingMode getRoundingMode(); - /// Returns the current rounding mode. - - static bool isInfinite(float value); - static bool isInfinite(double value); - static bool isInfinite(long double value); - /// Returns true iff the given number is infinite. - - static bool isNaN(float value); - static bool isNaN(double value); - static bool isNaN(long double value); - /// Returns true iff the given number is NaN. - - static float copySign(float target, float source); - static double copySign(double target, double source); - static long double copySign(long double target, long double source); - /// Copies the sign from source to target. -}; - - -// -// For convenience, we provide a shorter name for -// the FPEnvironment class. -// -typedef FPEnvironment FPE; - - -// -// inline's -// -inline bool FPEnvironment::isFlag(Flag flag) -{ - return isFlagImpl(FlagImpl(flag)); -} - - -inline void FPEnvironment::setRoundingMode(RoundingMode mode) -{ - setRoundingModeImpl(RoundingModeImpl(mode)); -} - - -inline FPEnvironment::RoundingMode FPEnvironment::getRoundingMode() -{ - return RoundingMode(getRoundingModeImpl()); -} - - -inline bool FPEnvironment::isInfinite(float value) -{ - return isInfiniteImpl(value); -} - - -inline bool FPEnvironment::isInfinite(double value) -{ - return isInfiniteImpl(value); -} - - -inline bool FPEnvironment::isInfinite(long double value) -{ - return isInfiniteImpl(value); -} - - -inline bool FPEnvironment::isNaN(float value) -{ - return isNaNImpl(value); -} - - -inline bool FPEnvironment::isNaN(double value) -{ - return isNaNImpl(value); -} - - -inline bool FPEnvironment::isNaN(long double value) -{ - return isNaNImpl(value); -} - - -inline float FPEnvironment::copySign(float target, float source) -{ - return copySignImpl(target, source); -} - - -inline double FPEnvironment::copySign(double target, double source) -{ - return copySignImpl(target, source); -} - - -inline long double FPEnvironment::copySign(long double target, long double source) -{ - return copySignImpl(target, source); -} - - -} // namespace Poco - - -#endif // Foundation_FPEnvironment_INCLUDED +// +// FPEnvironment.h +// +// $Id: //poco/1.2/Foundation/include/Poco/FPEnvironment.h#1 $ +// +// Library: Foundation +// Package: Core +// Module: FPEnvironment +// +// Definitions of class FPEnvironment. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_FPEnvironment_INCLUDED +#define Foundation_FPEnvironment_INCLUDED + + +#include "Poco/Foundation.h" + + +#if defined(POCO_NO_FPENVIRONMENT) +#include "Poco/FPEnvironment_DUMMY.h" +#elif defined(__osf__) || defined(__VMS) +#include "Poco/FPEnvironment_DEC.h" +#elif defined(sun) || defined(__sun) +#include "Poco/FPEnvironment_SUN.h" +#elif defined(POCO_OS_FAMILY_UNIX) +#include "Poco/FPEnvironment_C99.h" +#elif defined(POCO_OS_FAMILY_WINDOWS) +#include "Poco/FPEnvironment_WIN32.h" +#else +#include "Poco/FPEnvironment_DUMMY.h" +#endif + + +namespace Poco { + + +class Foundation_API FPEnvironment: private FPEnvironmentImpl + /// Instances of this class can be used to save + /// and later restore the current floating + /// point environment (consisting of rounding + /// mode and floating-point flags). + /// The class also provides various static + /// methods to query certain properties + /// of a floating-point number. +{ +public: + enum RoundingMode + { + FP_ROUND_DOWNWARD = FP_ROUND_DOWNWARD_IMPL, + FP_ROUND_UPWARD = FP_ROUND_UPWARD_IMPL, + FP_ROUND_TONEAREST = FP_ROUND_TONEAREST_IMPL, + FP_ROUND_TOWARDZERO = FP_ROUND_TOWARDZERO_IMPL + }; + + enum Flag + { + FP_DIVIDE_BY_ZERO = FP_DIVIDE_BY_ZERO_IMPL, + FP_INEXACT = FP_INEXACT_IMPL, + FP_OVERFLOW = FP_OVERFLOW_IMPL, + FP_UNDERFLOW = FP_UNDERFLOW_IMPL, + FP_INVALID = FP_INVALID_IMPL + }; + + FPEnvironment(); + /// Standard constructor. + /// Remembers the current environment. + + FPEnvironment(RoundingMode mode); + /// Remembers the current environment and + /// sets the given rounding mode. + + FPEnvironment(const FPEnvironment& env); + /// Copy constructor. + + ~FPEnvironment(); + /// Restores the previous environment (unless + /// keepCurrent() has been called previously) + + FPEnvironment& operator = (const FPEnvironment& env); + /// Assignment operator + + void keepCurrent(); + /// Keep the current environment even after + /// destroying the FPEnvironment object. + + static void clearFlags(); + /// Resets all flags. + + static bool isFlag(Flag flag); + /// Returns true iff the given flag is set. + + static void setRoundingMode(RoundingMode mode); + /// Sets the rounding mode. + + static RoundingMode getRoundingMode(); + /// Returns the current rounding mode. + + static bool isInfinite(float value); + static bool isInfinite(double value); + static bool isInfinite(long double value); + /// Returns true iff the given number is infinite. + + static bool isNaN(float value); + static bool isNaN(double value); + static bool isNaN(long double value); + /// Returns true iff the given number is NaN. + + static float copySign(float target, float source); + static double copySign(double target, double source); + static long double copySign(long double target, long double source); + /// Copies the sign from source to target. +}; + + +// +// For convenience, we provide a shorter name for +// the FPEnvironment class. +// +typedef FPEnvironment FPE; + + +// +// inline's +// +inline bool FPEnvironment::isFlag(Flag flag) +{ + return isFlagImpl(FlagImpl(flag)); +} + + +inline void FPEnvironment::setRoundingMode(RoundingMode mode) +{ + setRoundingModeImpl(RoundingModeImpl(mode)); +} + + +inline FPEnvironment::RoundingMode FPEnvironment::getRoundingMode() +{ + return RoundingMode(getRoundingModeImpl()); +} + + +inline bool FPEnvironment::isInfinite(float value) +{ + return isInfiniteImpl(value); +} + + +inline bool FPEnvironment::isInfinite(double value) +{ + return isInfiniteImpl(value); +} + + +inline bool FPEnvironment::isInfinite(long double value) +{ + return isInfiniteImpl(value); +} + + +inline bool FPEnvironment::isNaN(float value) +{ + return isNaNImpl(value); +} + + +inline bool FPEnvironment::isNaN(double value) +{ + return isNaNImpl(value); +} + + +inline bool FPEnvironment::isNaN(long double value) +{ + return isNaNImpl(value); +} + + +inline float FPEnvironment::copySign(float target, float source) +{ + return copySignImpl(target, source); +} + + +inline double FPEnvironment::copySign(double target, double source) +{ + return copySignImpl(target, source); +} + + +inline long double FPEnvironment::copySign(long double target, long double source) +{ + return copySignImpl(target, source); +} + + +} // namespace Poco + + +#endif // Foundation_FPEnvironment_INCLUDED diff --git a/Foundation/include/Poco/FPEnvironment_C99.h b/Foundation/include/Poco/FPEnvironment_C99.h index fbdf74640..13ca09dc3 100644 --- a/Foundation/include/Poco/FPEnvironment_C99.h +++ b/Foundation/include/Poco/FPEnvironment_C99.h @@ -1,147 +1,147 @@ -// -// FPEnvironment_C99.h -// -// $Id: //poco/1.2/Foundation/include/Poco/FPEnvironment_C99.h#1 $ -// -// Library: Foundation -// Package: Core -// Module: FPEnvironment -// -// Definitions of class FPEnvironmentImpl for C99. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_FPEnvironment_C99_INCLUDED -#define Foundation_FPEnvironment_C99_INCLUDED - - -#include "Poco/Foundation.h" -#include -#include - - -namespace Poco { - - -class FPEnvironmentImpl -{ -protected: - enum RoundingModeImpl - { - FP_ROUND_DOWNWARD_IMPL = FE_DOWNWARD, - FP_ROUND_UPWARD_IMPL = FE_UPWARD, - FP_ROUND_TONEAREST_IMPL = FE_TONEAREST, - FP_ROUND_TOWARDZERO_IMPL = FE_TOWARDZERO - }; - enum FlagImpl - { - FP_DIVIDE_BY_ZERO_IMPL = FE_DIVBYZERO, - FP_INEXACT_IMPL = FE_INEXACT, - FP_OVERFLOW_IMPL = FE_OVERFLOW, - FP_UNDERFLOW_IMPL = FE_UNDERFLOW, - FP_INVALID_IMPL = FE_INVALID - }; - FPEnvironmentImpl(); - FPEnvironmentImpl(const FPEnvironmentImpl& env); - ~FPEnvironmentImpl(); - FPEnvironmentImpl& operator = (const FPEnvironmentImpl& env); - void keepCurrentImpl(); - static void clearFlagsImpl(); - static bool isFlagImpl(FlagImpl flag); - static void setRoundingModeImpl(RoundingModeImpl mode); - static RoundingModeImpl getRoundingModeImpl(); - static bool isInfiniteImpl(float value); - static bool isInfiniteImpl(double value); - static bool isInfiniteImpl(long double value); - static bool isNaNImpl(float value); - static bool isNaNImpl(double value); - static bool isNaNImpl(long double value); - static float copySignImpl(float target, float source); - static double copySignImpl(double target, double source); - static long double copySignImpl(long double target, long double source); - -private: - fenv_t _env; -}; - - -// -// inlines -// -inline bool FPEnvironmentImpl::isInfiniteImpl(float value) -{ - return isinf(value) != 0; -} - - -inline bool FPEnvironmentImpl::isInfiniteImpl(double value) -{ - return isinf(value) != 0; -} - - -inline bool FPEnvironmentImpl::isInfiniteImpl(long double value) -{ - return isinf((double) value) != 0; -} - - -inline bool FPEnvironmentImpl::isNaNImpl(float value) -{ - return isnan(value) != 0; -} - - -inline bool FPEnvironmentImpl::isNaNImpl(double value) -{ - return isnan(value) != 0; -} - - -inline bool FPEnvironmentImpl::isNaNImpl(long double value) -{ - return isnan((double) value) != 0; -} - - -inline float FPEnvironmentImpl::copySignImpl(float target, float source) -{ - return copysignf(target, source); -} - - -inline double FPEnvironmentImpl::copySignImpl(double target, double source) -{ - return copysign(target, source); -} - - -} // namespace Poco - - -#endif // Foundation_FPEnvironment_C99_INCLUDED +// +// FPEnvironment_C99.h +// +// $Id: //poco/1.2/Foundation/include/Poco/FPEnvironment_C99.h#1 $ +// +// Library: Foundation +// Package: Core +// Module: FPEnvironment +// +// Definitions of class FPEnvironmentImpl for C99. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_FPEnvironment_C99_INCLUDED +#define Foundation_FPEnvironment_C99_INCLUDED + + +#include "Poco/Foundation.h" +#include +#include + + +namespace Poco { + + +class FPEnvironmentImpl +{ +protected: + enum RoundingModeImpl + { + FP_ROUND_DOWNWARD_IMPL = FE_DOWNWARD, + FP_ROUND_UPWARD_IMPL = FE_UPWARD, + FP_ROUND_TONEAREST_IMPL = FE_TONEAREST, + FP_ROUND_TOWARDZERO_IMPL = FE_TOWARDZERO + }; + enum FlagImpl + { + FP_DIVIDE_BY_ZERO_IMPL = FE_DIVBYZERO, + FP_INEXACT_IMPL = FE_INEXACT, + FP_OVERFLOW_IMPL = FE_OVERFLOW, + FP_UNDERFLOW_IMPL = FE_UNDERFLOW, + FP_INVALID_IMPL = FE_INVALID + }; + FPEnvironmentImpl(); + FPEnvironmentImpl(const FPEnvironmentImpl& env); + ~FPEnvironmentImpl(); + FPEnvironmentImpl& operator = (const FPEnvironmentImpl& env); + void keepCurrentImpl(); + static void clearFlagsImpl(); + static bool isFlagImpl(FlagImpl flag); + static void setRoundingModeImpl(RoundingModeImpl mode); + static RoundingModeImpl getRoundingModeImpl(); + static bool isInfiniteImpl(float value); + static bool isInfiniteImpl(double value); + static bool isInfiniteImpl(long double value); + static bool isNaNImpl(float value); + static bool isNaNImpl(double value); + static bool isNaNImpl(long double value); + static float copySignImpl(float target, float source); + static double copySignImpl(double target, double source); + static long double copySignImpl(long double target, long double source); + +private: + fenv_t _env; +}; + + +// +// inlines +// +inline bool FPEnvironmentImpl::isInfiniteImpl(float value) +{ + return isinf(value) != 0; +} + + +inline bool FPEnvironmentImpl::isInfiniteImpl(double value) +{ + return isinf(value) != 0; +} + + +inline bool FPEnvironmentImpl::isInfiniteImpl(long double value) +{ + return isinf((double) value) != 0; +} + + +inline bool FPEnvironmentImpl::isNaNImpl(float value) +{ + return isnan(value) != 0; +} + + +inline bool FPEnvironmentImpl::isNaNImpl(double value) +{ + return isnan(value) != 0; +} + + +inline bool FPEnvironmentImpl::isNaNImpl(long double value) +{ + return isnan((double) value) != 0; +} + + +inline float FPEnvironmentImpl::copySignImpl(float target, float source) +{ + return copysignf(target, source); +} + + +inline double FPEnvironmentImpl::copySignImpl(double target, double source) +{ + return copysign(target, source); +} + + +} // namespace Poco + + +#endif // Foundation_FPEnvironment_C99_INCLUDED diff --git a/Foundation/include/Poco/FPEnvironment_DEC.h b/Foundation/include/Poco/FPEnvironment_DEC.h index 3adf1b3b8..ed73b91ed 100644 --- a/Foundation/include/Poco/FPEnvironment_DEC.h +++ b/Foundation/include/Poco/FPEnvironment_DEC.h @@ -1,111 +1,111 @@ -// -// FPEnvironment_DEC.h -// -// $Id: //poco/1.2/Foundation/include/Poco/FPEnvironment_DEC.h#1 $ -// -// Library: Foundation -// Package: Core -// Module: FPEnvironment -// -// Definitions of class FPEnvironmentImpl for Tru64 and OpenVMS Alpha. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_FPEnvironment_DEC_INCLUDED -#define Foundation_FPEnvironment_DEC_INCLUDED - - -#include "Poco/Foundation.h" -#if defined(__VMS) -#include -#else -#include -#endif - - -namespace Poco { - - -class FPEnvironmentImpl -{ -protected: - enum RoundingModeImpl - { - FP_ROUND_DOWNWARD_IMPL = 0, - FP_ROUND_UPWARD_IMPL = 0, - FP_ROUND_TONEAREST_IMPL = 0, - FP_ROUND_TOWARDZERO_IMPL = 0 - }; - enum FlagImpl - { -#if defined(__VMS) - FP_DIVIDE_BY_ZERO_IMPL = IEEE$M_STATUS_DZE, - FP_INEXACT_IMPL = IEEE$M_STATUS_INE, - FP_OVERFLOW_IMPL = IEEE$M_STATUS_OVF, - FP_UNDERFLOW_IMPL = IEEE$M_STATUS_UNF, - FP_INVALID_IMPL = IEEE$M_STATUS_INV -#else - FP_DIVIDE_BY_ZERO_IMPL = IEEE_STATUS_DZE, - FP_INEXACT_IMPL = IEEE_STATUS_INE, - FP_OVERFLOW_IMPL = IEEE_STATUS_OVF, - FP_UNDERFLOW_IMPL = IEEE_STATUS_UNF, - FP_INVALID_IMPL = IEEE_STATUS_INV -#endif - }; - FPEnvironmentImpl(); - FPEnvironmentImpl(const FPEnvironmentImpl& env); - ~FPEnvironmentImpl(); - FPEnvironmentImpl& operator = (const FPEnvironmentImpl& env); - void keepCurrentImpl(); - static void clearFlagsImpl(); - static bool isFlagImpl(FlagImpl flag); - static void setRoundingModeImpl(RoundingModeImpl mode); - static RoundingModeImpl getRoundingModeImpl(); - static bool isInfiniteImpl(float value); - static bool isInfiniteImpl(double value); - static bool isInfiniteImpl(long double value); - static bool isNaNImpl(float value); - static bool isNaNImpl(double value); - static bool isNaNImpl(long double value); - static float copySignImpl(float target, float source); - static double copySignImpl(double target, double source); - static long double copySignImpl(long double target, long double source); - -private: -#if defined(__VMS) - struct _ieee _env; -#else - unsigned long _env; -#endif -}; - - -} // namespace Poco - - -#endif // Foundation_FPEnvironment_DEC_INCLUDED +// +// FPEnvironment_DEC.h +// +// $Id: //poco/1.2/Foundation/include/Poco/FPEnvironment_DEC.h#1 $ +// +// Library: Foundation +// Package: Core +// Module: FPEnvironment +// +// Definitions of class FPEnvironmentImpl for Tru64 and OpenVMS Alpha. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_FPEnvironment_DEC_INCLUDED +#define Foundation_FPEnvironment_DEC_INCLUDED + + +#include "Poco/Foundation.h" +#if defined(__VMS) +#include +#else +#include +#endif + + +namespace Poco { + + +class FPEnvironmentImpl +{ +protected: + enum RoundingModeImpl + { + FP_ROUND_DOWNWARD_IMPL = 0, + FP_ROUND_UPWARD_IMPL = 0, + FP_ROUND_TONEAREST_IMPL = 0, + FP_ROUND_TOWARDZERO_IMPL = 0 + }; + enum FlagImpl + { +#if defined(__VMS) + FP_DIVIDE_BY_ZERO_IMPL = IEEE$M_STATUS_DZE, + FP_INEXACT_IMPL = IEEE$M_STATUS_INE, + FP_OVERFLOW_IMPL = IEEE$M_STATUS_OVF, + FP_UNDERFLOW_IMPL = IEEE$M_STATUS_UNF, + FP_INVALID_IMPL = IEEE$M_STATUS_INV +#else + FP_DIVIDE_BY_ZERO_IMPL = IEEE_STATUS_DZE, + FP_INEXACT_IMPL = IEEE_STATUS_INE, + FP_OVERFLOW_IMPL = IEEE_STATUS_OVF, + FP_UNDERFLOW_IMPL = IEEE_STATUS_UNF, + FP_INVALID_IMPL = IEEE_STATUS_INV +#endif + }; + FPEnvironmentImpl(); + FPEnvironmentImpl(const FPEnvironmentImpl& env); + ~FPEnvironmentImpl(); + FPEnvironmentImpl& operator = (const FPEnvironmentImpl& env); + void keepCurrentImpl(); + static void clearFlagsImpl(); + static bool isFlagImpl(FlagImpl flag); + static void setRoundingModeImpl(RoundingModeImpl mode); + static RoundingModeImpl getRoundingModeImpl(); + static bool isInfiniteImpl(float value); + static bool isInfiniteImpl(double value); + static bool isInfiniteImpl(long double value); + static bool isNaNImpl(float value); + static bool isNaNImpl(double value); + static bool isNaNImpl(long double value); + static float copySignImpl(float target, float source); + static double copySignImpl(double target, double source); + static long double copySignImpl(long double target, long double source); + +private: +#if defined(__VMS) + struct _ieee _env; +#else + unsigned long _env; +#endif +}; + + +} // namespace Poco + + +#endif // Foundation_FPEnvironment_DEC_INCLUDED diff --git a/Foundation/include/Poco/FPEnvironment_DUMMY.h b/Foundation/include/Poco/FPEnvironment_DUMMY.h index e6d13831d..3764c37a9 100644 --- a/Foundation/include/Poco/FPEnvironment_DUMMY.h +++ b/Foundation/include/Poco/FPEnvironment_DUMMY.h @@ -1,147 +1,147 @@ -// -// FPEnvironment_DUMMY.h -// -// $Id: //poco/1.2/Foundation/include/Poco/FPEnvironment_DUMMY.h#1 $ -// -// Library: Foundation -// Package: Core -// Module: FPEnvironment -// -// Definition of class FPEnvironmentImpl for platforms that do not -// support IEEE 754 extensions. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_FPEnvironment_DUMMY_INCLUDED -#define Foundation_FPEnvironment_DUMMY_INCLUDED - - -#include "Poco/Foundation.h" -#include - - -namespace Poco { - - -class Foundation_API FPEnvironmentImpl -{ -protected: - enum RoundingModeImpl - { - FP_ROUND_DOWNWARD_IMPL, - FP_ROUND_UPWARD_IMPL, - FP_ROUND_TONEAREST_IMPL, - FP_ROUND_TOWARDZERO_IMPL - }; - enum FlagImpl - { - FP_DIVIDE_BY_ZERO_IMPL, - FP_INEXACT_IMPL, - FP_OVERFLOW_IMPL, - FP_UNDERFLOW_IMPL, - FP_INVALID_IMPL - }; - FPEnvironmentImpl(); - FPEnvironmentImpl(const FPEnvironmentImpl& env); - ~FPEnvironmentImpl(); - FPEnvironmentImpl& operator = (const FPEnvironmentImpl& env); - void keepCurrentImpl(); - static void clearFlagsImpl(); - static bool isFlagImpl(FlagImpl flag); - static void setRoundingModeImpl(RoundingModeImpl mode); - static RoundingModeImpl getRoundingModeImpl(); - static bool isInfiniteImpl(float value); - static bool isInfiniteImpl(double value); - static bool isInfiniteImpl(long double value); - static bool isNaNImpl(float value); - static bool isNaNImpl(double value); - static bool isNaNImpl(long double value); - static float copySignImpl(float target, float source); - static double copySignImpl(double target, double source); - static long double copySignImpl(long double target, long double source); - -private: - static RoundingModeImpl _roundingMode; -}; - - -// -// inlines -// -inline bool FPEnvironmentImpl::isInfiniteImpl(float value) -{ - return isinf(value) != 0; -} - - -inline bool FPEnvironmentImpl::isInfiniteImpl(double value) -{ - return isinf(value) != 0; -} - - -inline bool FPEnvironmentImpl::isInfiniteImpl(long double value) -{ - return isinf((double) value) != 0; -} - - -inline bool FPEnvironmentImpl::isNaNImpl(float value) -{ - return isnan(value) != 0; -} - - -inline bool FPEnvironmentImpl::isNaNImpl(double value) -{ - return isnan(value) != 0; -} - - -inline bool FPEnvironmentImpl::isNaNImpl(long double value) -{ - return isnan((double) value) != 0; -} - - -inline float FPEnvironmentImpl::copySignImpl(float target, float source) -{ - return copysignf(target, source); -} - - -inline double FPEnvironmentImpl::copySignImpl(double target, double source) -{ - return copysign(target, source); -} - - -} // namespace Poco - - -#endif // Foundation_FPEnvironment_DUMMY_INCLUDED +// +// FPEnvironment_DUMMY.h +// +// $Id: //poco/1.2/Foundation/include/Poco/FPEnvironment_DUMMY.h#1 $ +// +// Library: Foundation +// Package: Core +// Module: FPEnvironment +// +// Definition of class FPEnvironmentImpl for platforms that do not +// support IEEE 754 extensions. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_FPEnvironment_DUMMY_INCLUDED +#define Foundation_FPEnvironment_DUMMY_INCLUDED + + +#include "Poco/Foundation.h" +#include + + +namespace Poco { + + +class Foundation_API FPEnvironmentImpl +{ +protected: + enum RoundingModeImpl + { + FP_ROUND_DOWNWARD_IMPL, + FP_ROUND_UPWARD_IMPL, + FP_ROUND_TONEAREST_IMPL, + FP_ROUND_TOWARDZERO_IMPL + }; + enum FlagImpl + { + FP_DIVIDE_BY_ZERO_IMPL, + FP_INEXACT_IMPL, + FP_OVERFLOW_IMPL, + FP_UNDERFLOW_IMPL, + FP_INVALID_IMPL + }; + FPEnvironmentImpl(); + FPEnvironmentImpl(const FPEnvironmentImpl& env); + ~FPEnvironmentImpl(); + FPEnvironmentImpl& operator = (const FPEnvironmentImpl& env); + void keepCurrentImpl(); + static void clearFlagsImpl(); + static bool isFlagImpl(FlagImpl flag); + static void setRoundingModeImpl(RoundingModeImpl mode); + static RoundingModeImpl getRoundingModeImpl(); + static bool isInfiniteImpl(float value); + static bool isInfiniteImpl(double value); + static bool isInfiniteImpl(long double value); + static bool isNaNImpl(float value); + static bool isNaNImpl(double value); + static bool isNaNImpl(long double value); + static float copySignImpl(float target, float source); + static double copySignImpl(double target, double source); + static long double copySignImpl(long double target, long double source); + +private: + static RoundingModeImpl _roundingMode; +}; + + +// +// inlines +// +inline bool FPEnvironmentImpl::isInfiniteImpl(float value) +{ + return isinf(value) != 0; +} + + +inline bool FPEnvironmentImpl::isInfiniteImpl(double value) +{ + return isinf(value) != 0; +} + + +inline bool FPEnvironmentImpl::isInfiniteImpl(long double value) +{ + return isinf((double) value) != 0; +} + + +inline bool FPEnvironmentImpl::isNaNImpl(float value) +{ + return isnan(value) != 0; +} + + +inline bool FPEnvironmentImpl::isNaNImpl(double value) +{ + return isnan(value) != 0; +} + + +inline bool FPEnvironmentImpl::isNaNImpl(long double value) +{ + return isnan((double) value) != 0; +} + + +inline float FPEnvironmentImpl::copySignImpl(float target, float source) +{ + return copysignf(target, source); +} + + +inline double FPEnvironmentImpl::copySignImpl(double target, double source) +{ + return copysign(target, source); +} + + +} // namespace Poco + + +#endif // Foundation_FPEnvironment_DUMMY_INCLUDED diff --git a/Foundation/include/Poco/FPEnvironment_SUN.h b/Foundation/include/Poco/FPEnvironment_SUN.h index 9479475d4..28200d1b2 100644 --- a/Foundation/include/Poco/FPEnvironment_SUN.h +++ b/Foundation/include/Poco/FPEnvironment_SUN.h @@ -1,96 +1,96 @@ -// -// FPEnvironment_SUN.h -// -// $Id: //poco/1.2/Foundation/include/Poco/FPEnvironment_SUN.h#1 $ -// -// Library: Foundation -// Package: Core -// Module: FPEnvironment -// -// Definitions of class FPEnvironmentImpl for Solaris. -// -// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_FPEnvironment_SUN_INCLUDED -#define Foundation_FPEnvironment_SUN_INCLUDED - - -#include "Poco/Foundation.h" -#include - - -namespace Poco { - - -class FPEnvironmentImpl -{ -protected: - enum RoundingModeImpl - { - FP_ROUND_DOWNWARD_IMPL = FP_RM, - FP_ROUND_UPWARD_IMPL = FP_RP, - FP_ROUND_TONEAREST_IMPL = FP_RN, - FP_ROUND_TOWARDZERO_IMPL = FP_RZ - }; - enum FlagImpl - { - FP_DIVIDE_BY_ZERO_IMPL = FP_X_DZ, - FP_INEXACT_IMPL = FP_X_IMP, - FP_OVERFLOW_IMPL = FP_X_OFL, - FP_UNDERFLOW_IMPL = FP_X_UFL, - FP_INVALID_IMPL = FP_X_INV - }; - FPEnvironmentImpl(); - FPEnvironmentImpl(const FPEnvironmentImpl& env); - ~FPEnvironmentImpl(); - FPEnvironmentImpl& operator = (const FPEnvironmentImpl& env); - void keepCurrentImpl(); - static void clearFlagsImpl(); - static bool isFlagImpl(FlagImpl flag); - static void setRoundingModeImpl(RoundingModeImpl mode); - static RoundingModeImpl getRoundingModeImpl(); - static bool isInfiniteImpl(float value); - static bool isInfiniteImpl(double value); - static bool isInfiniteImpl(long double value); - static bool isNaNImpl(float value); - static bool isNaNImpl(double value); - static bool isNaNImpl(long double value); - static float copySignImpl(float target, float source); - static double copySignImpl(double target, double source); - static long double copySignImpl(long double target, long double source); - -private: - fp_rnd _rnd; - fp_except _exc; -}; - - -} // namespace Poco - - -#endif // Foundation_FPEnvironment_SUN_INCLUDED +// +// FPEnvironment_SUN.h +// +// $Id: //poco/1.2/Foundation/include/Poco/FPEnvironment_SUN.h#1 $ +// +// Library: Foundation +// Package: Core +// Module: FPEnvironment +// +// Definitions of class FPEnvironmentImpl for Solaris. +// +// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_FPEnvironment_SUN_INCLUDED +#define Foundation_FPEnvironment_SUN_INCLUDED + + +#include "Poco/Foundation.h" +#include + + +namespace Poco { + + +class FPEnvironmentImpl +{ +protected: + enum RoundingModeImpl + { + FP_ROUND_DOWNWARD_IMPL = FP_RM, + FP_ROUND_UPWARD_IMPL = FP_RP, + FP_ROUND_TONEAREST_IMPL = FP_RN, + FP_ROUND_TOWARDZERO_IMPL = FP_RZ + }; + enum FlagImpl + { + FP_DIVIDE_BY_ZERO_IMPL = FP_X_DZ, + FP_INEXACT_IMPL = FP_X_IMP, + FP_OVERFLOW_IMPL = FP_X_OFL, + FP_UNDERFLOW_IMPL = FP_X_UFL, + FP_INVALID_IMPL = FP_X_INV + }; + FPEnvironmentImpl(); + FPEnvironmentImpl(const FPEnvironmentImpl& env); + ~FPEnvironmentImpl(); + FPEnvironmentImpl& operator = (const FPEnvironmentImpl& env); + void keepCurrentImpl(); + static void clearFlagsImpl(); + static bool isFlagImpl(FlagImpl flag); + static void setRoundingModeImpl(RoundingModeImpl mode); + static RoundingModeImpl getRoundingModeImpl(); + static bool isInfiniteImpl(float value); + static bool isInfiniteImpl(double value); + static bool isInfiniteImpl(long double value); + static bool isNaNImpl(float value); + static bool isNaNImpl(double value); + static bool isNaNImpl(long double value); + static float copySignImpl(float target, float source); + static double copySignImpl(double target, double source); + static long double copySignImpl(long double target, long double source); + +private: + fp_rnd _rnd; + fp_except _exc; +}; + + +} // namespace Poco + + +#endif // Foundation_FPEnvironment_SUN_INCLUDED diff --git a/Foundation/include/Poco/FPEnvironment_WIN32.h b/Foundation/include/Poco/FPEnvironment_WIN32.h index 640f38859..c0b9ea0e0 100644 --- a/Foundation/include/Poco/FPEnvironment_WIN32.h +++ b/Foundation/include/Poco/FPEnvironment_WIN32.h @@ -1,153 +1,153 @@ -// -// FPEnvironment_WIN32.h -// -// $Id: //poco/1.2/Foundation/include/Poco/FPEnvironment_WIN32.h#1 $ -// -// Library: Foundation -// Package: Core -// Module: FPEnvironment -// -// Definitions of class FPEnvironmentImpl for WIN32. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_FPEnvironment_WIN32_INCLUDED -#define Foundation_FPEnvironment_WIN32_INCLUDED - - -#include "Poco/Foundation.h" -#include -#include - - -namespace Poco { - - -class Foundation_API FPEnvironmentImpl -{ -protected: - enum RoundingModeImpl - { - FP_ROUND_DOWNWARD_IMPL = RC_DOWN, - FP_ROUND_UPWARD_IMPL = RC_UP, - FP_ROUND_TONEAREST_IMPL = RC_NEAR, - FP_ROUND_TOWARDZERO_IMPL = RC_CHOP - }; - enum FlagImpl - { - FP_DIVIDE_BY_ZERO_IMPL = SW_ZERODIVIDE, - FP_INEXACT_IMPL = SW_INEXACT, - FP_OVERFLOW_IMPL = SW_OVERFLOW, - FP_UNDERFLOW_IMPL = SW_UNDERFLOW, - FP_INVALID_IMPL = SW_INVALID - }; - FPEnvironmentImpl(); - FPEnvironmentImpl(const FPEnvironmentImpl& env); - ~FPEnvironmentImpl(); - FPEnvironmentImpl& operator = (const FPEnvironmentImpl& env); - void keepCurrentImpl(); - static void clearFlagsImpl(); - static bool isFlagImpl(FlagImpl flag); - static void setRoundingModeImpl(RoundingModeImpl mode); - static RoundingModeImpl getRoundingModeImpl(); - static bool isInfiniteImpl(float value); - static bool isInfiniteImpl(double value); - static bool isInfiniteImpl(long double value); - static bool isNaNImpl(float value); - static bool isNaNImpl(double value); - static bool isNaNImpl(long double value); - static float copySignImpl(float target, float source); - static double copySignImpl(double target, double source); - static long double copySignImpl(long double target, long double source); - -private: - unsigned _env; -}; - - -// -// inlines -// -inline bool FPEnvironmentImpl::isInfiniteImpl(float value) -{ - return _finite(value) == 0; -} - - -inline bool FPEnvironmentImpl::isInfiniteImpl(double value) -{ - return _finite(value) == 0; -} - - -inline bool FPEnvironmentImpl::isInfiniteImpl(long double value) -{ - return _finite(value) == 0; -} - - -inline bool FPEnvironmentImpl::isNaNImpl(float value) -{ - return _isnan(value) != 0; -} - - -inline bool FPEnvironmentImpl::isNaNImpl(double value) -{ - return _isnan(value) != 0; -} - - -inline bool FPEnvironmentImpl::isNaNImpl(long double value) -{ - return _isnan(value) != 0; -} - - -inline float FPEnvironmentImpl::copySignImpl(float target, float source) -{ - return float(_copysign(target, source)); -} - - -inline double FPEnvironmentImpl::copySignImpl(double target, double source) -{ - return _copysign(target, source); -} - - -inline long double FPEnvironmentImpl::copySignImpl(long double target, long double source) -{ - return (source > 0 && target > 0) || (source < 0 && target < 0) ? target : -target; -} - - -} // namespace Poco - - -#endif // Foundation_FPEnvironment_WIN32_INCLUDED +// +// FPEnvironment_WIN32.h +// +// $Id: //poco/1.2/Foundation/include/Poco/FPEnvironment_WIN32.h#1 $ +// +// Library: Foundation +// Package: Core +// Module: FPEnvironment +// +// Definitions of class FPEnvironmentImpl for WIN32. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_FPEnvironment_WIN32_INCLUDED +#define Foundation_FPEnvironment_WIN32_INCLUDED + + +#include "Poco/Foundation.h" +#include +#include + + +namespace Poco { + + +class Foundation_API FPEnvironmentImpl +{ +protected: + enum RoundingModeImpl + { + FP_ROUND_DOWNWARD_IMPL = RC_DOWN, + FP_ROUND_UPWARD_IMPL = RC_UP, + FP_ROUND_TONEAREST_IMPL = RC_NEAR, + FP_ROUND_TOWARDZERO_IMPL = RC_CHOP + }; + enum FlagImpl + { + FP_DIVIDE_BY_ZERO_IMPL = SW_ZERODIVIDE, + FP_INEXACT_IMPL = SW_INEXACT, + FP_OVERFLOW_IMPL = SW_OVERFLOW, + FP_UNDERFLOW_IMPL = SW_UNDERFLOW, + FP_INVALID_IMPL = SW_INVALID + }; + FPEnvironmentImpl(); + FPEnvironmentImpl(const FPEnvironmentImpl& env); + ~FPEnvironmentImpl(); + FPEnvironmentImpl& operator = (const FPEnvironmentImpl& env); + void keepCurrentImpl(); + static void clearFlagsImpl(); + static bool isFlagImpl(FlagImpl flag); + static void setRoundingModeImpl(RoundingModeImpl mode); + static RoundingModeImpl getRoundingModeImpl(); + static bool isInfiniteImpl(float value); + static bool isInfiniteImpl(double value); + static bool isInfiniteImpl(long double value); + static bool isNaNImpl(float value); + static bool isNaNImpl(double value); + static bool isNaNImpl(long double value); + static float copySignImpl(float target, float source); + static double copySignImpl(double target, double source); + static long double copySignImpl(long double target, long double source); + +private: + unsigned _env; +}; + + +// +// inlines +// +inline bool FPEnvironmentImpl::isInfiniteImpl(float value) +{ + return _finite(value) == 0; +} + + +inline bool FPEnvironmentImpl::isInfiniteImpl(double value) +{ + return _finite(value) == 0; +} + + +inline bool FPEnvironmentImpl::isInfiniteImpl(long double value) +{ + return _finite(value) == 0; +} + + +inline bool FPEnvironmentImpl::isNaNImpl(float value) +{ + return _isnan(value) != 0; +} + + +inline bool FPEnvironmentImpl::isNaNImpl(double value) +{ + return _isnan(value) != 0; +} + + +inline bool FPEnvironmentImpl::isNaNImpl(long double value) +{ + return _isnan(value) != 0; +} + + +inline float FPEnvironmentImpl::copySignImpl(float target, float source) +{ + return float(_copysign(target, source)); +} + + +inline double FPEnvironmentImpl::copySignImpl(double target, double source) +{ + return _copysign(target, source); +} + + +inline long double FPEnvironmentImpl::copySignImpl(long double target, long double source) +{ + return (source > 0 && target > 0) || (source < 0 && target < 0) ? target : -target; +} + + +} // namespace Poco + + +#endif // Foundation_FPEnvironment_WIN32_INCLUDED diff --git a/Foundation/include/Poco/File.h b/Foundation/include/Poco/File.h index 9b0e532d7..b4fc8b368 100644 --- a/Foundation/include/Poco/File.h +++ b/Foundation/include/Poco/File.h @@ -1,253 +1,253 @@ -// -// File.h -// -// $Id: //poco/1.2/Foundation/include/Poco/File.h#1 $ -// -// Library: Foundation -// Package: Filesystem -// Module: File -// -// Definition of the File class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_File_INCLUDED -#define Foundation_File_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/Timestamp.h" -#include - - -#if defined(POCO_OS_FAMILY_WINDOWS) && defined(POCO_WIN32_UTF8) -#include "Poco/File_WIN32U.h" -#elif defined(POCO_OS_FAMILY_WINDOWS) -#include "Poco/File_WIN32.h" -#elif defined(POCO_OS_FAMILY_UNIX) -#include "Poco/File_UNIX.h" -#else -#include "Poco/File_VMS.h" -#endif - - -namespace Poco { - - -class Path; - - -class Foundation_API File: private FileImpl - /// The File class provides methods for working with a file. -{ -public: - typedef FileSizeImpl FileSize; - - File(); - /// Creates the file. - - File(const std::string& path); - /// Creates the file. - - File(const char* path); - /// Creates the file. - - File(const Path& path); - /// Creates the file. - - File(const File& file); - /// Copy constructor. - - virtual ~File(); - /// Destroys the file. - - File& operator = (const File& file); - /// Assignment operator. - - File& operator = (const std::string& path); - /// Assignment operator. - - File& operator = (const char* path); - /// Assignment operator. - - File& operator = (const Path& path); - /// Assignment operator. - - void swap(File& file); - /// Swaps the file with another one. - - const std::string& path() const; - /// Returns the path. - - bool exists() const; - /// Returns true iff the file exists. - - bool canRead() const; - /// Returns true iff the file is readable. - - bool canWrite() const; - /// Returns true iff the file is writeable. - - bool isFile() const; - /// Returns true iff the file is a regular file. - - bool isLink() const; - /// Returns true iff the file is a symbolic link. - - bool isDirectory() const; - /// Returns true iff the file is a directory. - - Timestamp created() const; - /// Returns the creation date of the file. - - Timestamp getLastModified() const; - /// Returns the modification date of the file. - - void setLastModified(const Timestamp& ts); - /// Sets the modification date of the file. - - FileSize getSize() const; - /// Returns the size of the file in bytes. - - void setSize(FileSize size); - /// Sets the size of the file in bytes. Can be used - /// to truncate a file. - - void setWriteable(bool flag = true); - /// Makes the file writeable (if flag is true), or - /// non-writeable (if flag is false) by setting the - /// file's flags in the filesystem accordingly. - - void setReadOnly(bool flag = true); - /// Makes the file non-writeable (if flag is true), or - /// writeable (if flag is false) by setting the - /// file's flags in the filesystem accordingly. - - void copyTo(const std::string& path) const; - /// Copies the file to the given path. The target path - /// can be a directory. - - void moveTo(const std::string& path); - /// Copies the file to the given path and removes the - /// original file. The target path can be a directory. - - void renameTo(const std::string& path); - /// Renames the file to the new name. - - void remove(bool recursive = false); - /// Deletes the file. If recursive is true and the - /// file is a directory, recursively deletes all - /// files in the directory. - - bool createFile(); - /// Creates a new, empty file in an atomic operation. - /// Returns true if the file has been created and false - /// if the file already exists. Throws an exception if - /// an error occurs. - - bool createDirectory(); - /// Creates a directory. Returns true if the directory - /// has been created and false if it already exists. - /// Throws an exception if an error occurs. - - void createDirectories(); - /// Creates a directory (and all parent directories - /// if necessary). - - void list(std::vector& files) const; - /// Fills the vector with the names of all - /// files in the directory. - - void list(std::vector& files) const; - /// Fills the vector with the names of all - /// files in the directory. - - bool operator == (const File& file) const; - bool operator != (const File& file) const; - bool operator < (const File& file) const; - bool operator <= (const File& file) const; - bool operator > (const File& file) const; - bool operator >= (const File& file) const; -}; - - -// -// inlines -// -inline const std::string& File::path() const -{ - return getPathImpl(); -} - - -inline bool File::operator == (const File& file) const -{ - return getPathImpl() == file.getPathImpl(); -} - - -inline bool File::operator != (const File& file) const -{ - return getPathImpl() != file.getPathImpl(); -} - - -inline bool File::operator < (const File& file) const -{ - return getPathImpl() < file.getPathImpl(); -} - - -inline bool File::operator <= (const File& file) const -{ - return getPathImpl() <= file.getPathImpl(); -} - - -inline bool File::operator > (const File& file) const -{ - return getPathImpl() > file.getPathImpl(); -} - - -inline bool File::operator >= (const File& file) const -{ - return getPathImpl() >= file.getPathImpl(); -} - - -inline void swap(File& f1, File& f2) -{ - f1.swap(f2); -} - - -} // namespace Poco - - -#endif // Foundation_File_INCLUDED +// +// File.h +// +// $Id: //poco/1.2/Foundation/include/Poco/File.h#1 $ +// +// Library: Foundation +// Package: Filesystem +// Module: File +// +// Definition of the File class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_File_INCLUDED +#define Foundation_File_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Timestamp.h" +#include + + +#if defined(POCO_OS_FAMILY_WINDOWS) && defined(POCO_WIN32_UTF8) +#include "Poco/File_WIN32U.h" +#elif defined(POCO_OS_FAMILY_WINDOWS) +#include "Poco/File_WIN32.h" +#elif defined(POCO_OS_FAMILY_UNIX) +#include "Poco/File_UNIX.h" +#else +#include "Poco/File_VMS.h" +#endif + + +namespace Poco { + + +class Path; + + +class Foundation_API File: private FileImpl + /// The File class provides methods for working with a file. +{ +public: + typedef FileSizeImpl FileSize; + + File(); + /// Creates the file. + + File(const std::string& path); + /// Creates the file. + + File(const char* path); + /// Creates the file. + + File(const Path& path); + /// Creates the file. + + File(const File& file); + /// Copy constructor. + + virtual ~File(); + /// Destroys the file. + + File& operator = (const File& file); + /// Assignment operator. + + File& operator = (const std::string& path); + /// Assignment operator. + + File& operator = (const char* path); + /// Assignment operator. + + File& operator = (const Path& path); + /// Assignment operator. + + void swap(File& file); + /// Swaps the file with another one. + + const std::string& path() const; + /// Returns the path. + + bool exists() const; + /// Returns true iff the file exists. + + bool canRead() const; + /// Returns true iff the file is readable. + + bool canWrite() const; + /// Returns true iff the file is writeable. + + bool isFile() const; + /// Returns true iff the file is a regular file. + + bool isLink() const; + /// Returns true iff the file is a symbolic link. + + bool isDirectory() const; + /// Returns true iff the file is a directory. + + Timestamp created() const; + /// Returns the creation date of the file. + + Timestamp getLastModified() const; + /// Returns the modification date of the file. + + void setLastModified(const Timestamp& ts); + /// Sets the modification date of the file. + + FileSize getSize() const; + /// Returns the size of the file in bytes. + + void setSize(FileSize size); + /// Sets the size of the file in bytes. Can be used + /// to truncate a file. + + void setWriteable(bool flag = true); + /// Makes the file writeable (if flag is true), or + /// non-writeable (if flag is false) by setting the + /// file's flags in the filesystem accordingly. + + void setReadOnly(bool flag = true); + /// Makes the file non-writeable (if flag is true), or + /// writeable (if flag is false) by setting the + /// file's flags in the filesystem accordingly. + + void copyTo(const std::string& path) const; + /// Copies the file to the given path. The target path + /// can be a directory. + + void moveTo(const std::string& path); + /// Copies the file to the given path and removes the + /// original file. The target path can be a directory. + + void renameTo(const std::string& path); + /// Renames the file to the new name. + + void remove(bool recursive = false); + /// Deletes the file. If recursive is true and the + /// file is a directory, recursively deletes all + /// files in the directory. + + bool createFile(); + /// Creates a new, empty file in an atomic operation. + /// Returns true if the file has been created and false + /// if the file already exists. Throws an exception if + /// an error occurs. + + bool createDirectory(); + /// Creates a directory. Returns true if the directory + /// has been created and false if it already exists. + /// Throws an exception if an error occurs. + + void createDirectories(); + /// Creates a directory (and all parent directories + /// if necessary). + + void list(std::vector& files) const; + /// Fills the vector with the names of all + /// files in the directory. + + void list(std::vector& files) const; + /// Fills the vector with the names of all + /// files in the directory. + + bool operator == (const File& file) const; + bool operator != (const File& file) const; + bool operator < (const File& file) const; + bool operator <= (const File& file) const; + bool operator > (const File& file) const; + bool operator >= (const File& file) const; +}; + + +// +// inlines +// +inline const std::string& File::path() const +{ + return getPathImpl(); +} + + +inline bool File::operator == (const File& file) const +{ + return getPathImpl() == file.getPathImpl(); +} + + +inline bool File::operator != (const File& file) const +{ + return getPathImpl() != file.getPathImpl(); +} + + +inline bool File::operator < (const File& file) const +{ + return getPathImpl() < file.getPathImpl(); +} + + +inline bool File::operator <= (const File& file) const +{ + return getPathImpl() <= file.getPathImpl(); +} + + +inline bool File::operator > (const File& file) const +{ + return getPathImpl() > file.getPathImpl(); +} + + +inline bool File::operator >= (const File& file) const +{ + return getPathImpl() >= file.getPathImpl(); +} + + +inline void swap(File& f1, File& f2) +{ + f1.swap(f2); +} + + +} // namespace Poco + + +#endif // Foundation_File_INCLUDED diff --git a/Foundation/include/Poco/FileChannel.h b/Foundation/include/Poco/FileChannel.h index 7d5f0f0fa..3bc5f8db7 100644 --- a/Foundation/include/Poco/FileChannel.h +++ b/Foundation/include/Poco/FileChannel.h @@ -1,248 +1,248 @@ -// -// FileChannel.h -// -// $Id: //poco/1.2/Foundation/include/Poco/FileChannel.h#1 $ -// -// Library: Foundation -// Package: Logging -// Module: FileChannel -// -// Definition of the FileChannel class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_FileChannel_INCLUDED -#define Foundation_FileChannel_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/Channel.h" -#include "Poco/Timestamp.h" -#include "Poco/Mutex.h" - - -namespace Poco { - - -class LogFile; -class RotateStrategy; -class ArchiveStrategy; -class PurgeStrategy; - - -class Foundation_API FileChannel: public Channel - /// A Channel that writes to a file. This class supports - /// flexible log file rotation and archiving, as well - /// as automatic purging of archived log files. - /// - /// Only the message's text is written, followed - /// by a newline. - /// - /// Chain this channel to a FormattingChannel with an - /// appropriate Formatter to control what is in the text. - /// - /// The FileChannel support log file rotation based - /// on log file size or time intervals. - /// Archived log files can be compressed in gzip format. - /// Older archived files can be automatically deleted - /// (purged). - /// - /// The rotation strategy can be specified with the - /// "rotation" property, which can take one of the - /// follwing values: - /// - /// * never: no log rotation - /// * [day,][hh]:mm: the file is rotated on specified day/time - /// day - day is specified as long or short day name (Monday|Mon, Tuesday|Tue, ... ); - /// day can be omitted, in which case log is rotated every day - /// hh - valid hour range is 00-23; - /// hour can be omitted, in which case log is rotated every hour - /// mm - valid minute range is 00-59; - /// minute must be specified - /// * daily: the file is rotated daily - /// * weekly: the file is rotated every seven days - /// * monthly: the file is rotated every 30 days - /// * hours: the file is rotated every hours, where - /// is an integer greater than zero. - /// * days: the file is rotated every days, where - /// is an integer greater than zero. - /// * weeks: the file is rotated every weeks, where - /// is an integer greater than zero. - /// * months: the file is rotated every months, where - /// is an integer greater than zero and - /// a month has 30 days. - /// * : the file is rotated when its size exceeds - /// bytes. - /// * K: the file is rotated when its size exceeds - /// Kilobytes. - /// * M: the file is rotated when its size exceeds - /// Megabytes. - /// - /// Using the "archive" property it is possible to specify - /// how archived log files are named. The following values - /// for the "archive" property are supported: - /// - /// * number: A number, starting with 0, is appended to - /// the name of archived log files. The newest - /// archived log file always has the number 0. - /// For example, if the log file is named - /// "access.log", and it fulfils the criteria - /// for rotation, the file is renamed to - /// "access.log.0". If a file named "access.log.0" - /// already exists, it is renamed to "access.log.1", - /// and so on. - /// * timestamp: A timestamp is appended to the log file name. - /// For example, if the log file is named - /// "access.log", and it fulfils the criteria - /// for rotation, the file is renamed to - /// "access.log.20050802110300". - /// - /// Using the "times" property it is possible to specify - /// time mode for the day/time based rotation. The following values - /// for the "times" property are supported: - /// - /// * utc: Rotation strategy is based on UTC time (default). - /// * local: Rotation strategy is based on local time. - /// - /// Archived log files can be compressed using the gzip compression - /// method. Compressing can be controlled with the "compression" - /// property. The following values for the "compress" property - /// are supported: - /// - /// * true: Compress archived log files. - /// * false: Do not compress archived log files. - /// - /// Archived log files can be automatically purged, either if - /// they reach a certain age, or if the number of archived - /// log files reaches a given maximum number. This is - /// controlled by the purgeAge and purgeCount properties. - /// - /// The purgeAge property can have the following values: - /// - /// * [seconds] the maximum age is seconds. - /// * minutes: the maximum age is minutes. - /// * hours: the maximum age is hours. - /// * days: the maximum age is days. - /// * weeks: the maximum age is weeks. - /// * months: the maximum age is months, where a month has 30 days. - /// - /// The purgeCount property has an integer value that - /// specifies the maximum number of archived log files. - /// If the number is exceeded, archived log files are - /// deleted, starting with the oldest. - /// - /// For a more lightweight file channel class, see SimpleFileChannel. -{ -public: - FileChannel(); - /// Creates the FileChannel. - - FileChannel(const std::string& path); - /// Creates the FileChannel for a file with the given path. - - void open(); - /// Opens the FileChannel and creates the log file if necessary. - - void close(); - /// Closes the FileChannel. - - void log(const Message& msg); - /// Logs the given message to the file. - - void setProperty(const std::string& name, const std::string& value); - /// Sets the property with the given name. - /// - /// The following properties are supported: - /// * path: The log file's path. - /// * rotation: The log file's rotation mode. See the - /// FileChannel class for details. - /// * archive: The log file's archive mode. See the - /// FileChannel class for details. - /// * times: The log file's time mode. See the - /// FileChannel class for details. - /// * compress: Enable or disable compression of - /// archived files. See the FileChannel class - /// for details. - /// * purgeAge: Maximum age of an archived log file before - /// it is purged. See the FileChannel class for - /// details. - /// * purgeCount: Maximum number of archived log files before - /// files are purged. See the FileChannel class - /// for details. - - std::string getProperty(const std::string& name) const; - /// Returns the value of the property with the given name. - /// See setProperty() for a description of the supported - /// properties. - - Timestamp creationDate() const; - /// Returns the log file's creation date. - - UInt64 size() const; - /// Returns the log file's current size in bytes. - - const std::string& path() const; - /// Returns the log file's path. - - static const std::string PROP_PATH; - static const std::string PROP_ROTATION; - static const std::string PROP_ARCHIVE; - static const std::string PROP_TIMES; - static const std::string PROP_COMPRESS; - static const std::string PROP_PURGEAGE; - static const std::string PROP_PURGECOUNT; - -protected: - ~FileChannel(); - void setRotation(const std::string& rotation); - void setArchive(const std::string& archive); - void setCompress(const std::string& compress); - void setPurgeAge(const std::string& age); - void setPurgeCount(const std::string& count); - void purge(); - -private: - std::string _path; - std::string _times; - std::string _rotation; - std::string _archive; - bool _compress; - std::string _purgeAge; - std::string _purgeCount; - LogFile* _pFile; - RotateStrategy* _pRotateStrategy; - ArchiveStrategy* _pArchiveStrategy; - PurgeStrategy* _pPurgeStrategy; - FastMutex _mutex; -}; - - -} // namespace Poco - - -#endif // Foundation_FileChannel_INCLUDED +// +// FileChannel.h +// +// $Id: //poco/1.2/Foundation/include/Poco/FileChannel.h#1 $ +// +// Library: Foundation +// Package: Logging +// Module: FileChannel +// +// Definition of the FileChannel class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_FileChannel_INCLUDED +#define Foundation_FileChannel_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Channel.h" +#include "Poco/Timestamp.h" +#include "Poco/Mutex.h" + + +namespace Poco { + + +class LogFile; +class RotateStrategy; +class ArchiveStrategy; +class PurgeStrategy; + + +class Foundation_API FileChannel: public Channel + /// A Channel that writes to a file. This class supports + /// flexible log file rotation and archiving, as well + /// as automatic purging of archived log files. + /// + /// Only the message's text is written, followed + /// by a newline. + /// + /// Chain this channel to a FormattingChannel with an + /// appropriate Formatter to control what is in the text. + /// + /// The FileChannel support log file rotation based + /// on log file size or time intervals. + /// Archived log files can be compressed in gzip format. + /// Older archived files can be automatically deleted + /// (purged). + /// + /// The rotation strategy can be specified with the + /// "rotation" property, which can take one of the + /// follwing values: + /// + /// * never: no log rotation + /// * [day,][hh]:mm: the file is rotated on specified day/time + /// day - day is specified as long or short day name (Monday|Mon, Tuesday|Tue, ... ); + /// day can be omitted, in which case log is rotated every day + /// hh - valid hour range is 00-23; + /// hour can be omitted, in which case log is rotated every hour + /// mm - valid minute range is 00-59; + /// minute must be specified + /// * daily: the file is rotated daily + /// * weekly: the file is rotated every seven days + /// * monthly: the file is rotated every 30 days + /// * hours: the file is rotated every hours, where + /// is an integer greater than zero. + /// * days: the file is rotated every days, where + /// is an integer greater than zero. + /// * weeks: the file is rotated every weeks, where + /// is an integer greater than zero. + /// * months: the file is rotated every months, where + /// is an integer greater than zero and + /// a month has 30 days. + /// * : the file is rotated when its size exceeds + /// bytes. + /// * K: the file is rotated when its size exceeds + /// Kilobytes. + /// * M: the file is rotated when its size exceeds + /// Megabytes. + /// + /// Using the "archive" property it is possible to specify + /// how archived log files are named. The following values + /// for the "archive" property are supported: + /// + /// * number: A number, starting with 0, is appended to + /// the name of archived log files. The newest + /// archived log file always has the number 0. + /// For example, if the log file is named + /// "access.log", and it fulfils the criteria + /// for rotation, the file is renamed to + /// "access.log.0". If a file named "access.log.0" + /// already exists, it is renamed to "access.log.1", + /// and so on. + /// * timestamp: A timestamp is appended to the log file name. + /// For example, if the log file is named + /// "access.log", and it fulfils the criteria + /// for rotation, the file is renamed to + /// "access.log.20050802110300". + /// + /// Using the "times" property it is possible to specify + /// time mode for the day/time based rotation. The following values + /// for the "times" property are supported: + /// + /// * utc: Rotation strategy is based on UTC time (default). + /// * local: Rotation strategy is based on local time. + /// + /// Archived log files can be compressed using the gzip compression + /// method. Compressing can be controlled with the "compression" + /// property. The following values for the "compress" property + /// are supported: + /// + /// * true: Compress archived log files. + /// * false: Do not compress archived log files. + /// + /// Archived log files can be automatically purged, either if + /// they reach a certain age, or if the number of archived + /// log files reaches a given maximum number. This is + /// controlled by the purgeAge and purgeCount properties. + /// + /// The purgeAge property can have the following values: + /// + /// * [seconds] the maximum age is seconds. + /// * minutes: the maximum age is minutes. + /// * hours: the maximum age is hours. + /// * days: the maximum age is days. + /// * weeks: the maximum age is weeks. + /// * months: the maximum age is months, where a month has 30 days. + /// + /// The purgeCount property has an integer value that + /// specifies the maximum number of archived log files. + /// If the number is exceeded, archived log files are + /// deleted, starting with the oldest. + /// + /// For a more lightweight file channel class, see SimpleFileChannel. +{ +public: + FileChannel(); + /// Creates the FileChannel. + + FileChannel(const std::string& path); + /// Creates the FileChannel for a file with the given path. + + void open(); + /// Opens the FileChannel and creates the log file if necessary. + + void close(); + /// Closes the FileChannel. + + void log(const Message& msg); + /// Logs the given message to the file. + + void setProperty(const std::string& name, const std::string& value); + /// Sets the property with the given name. + /// + /// The following properties are supported: + /// * path: The log file's path. + /// * rotation: The log file's rotation mode. See the + /// FileChannel class for details. + /// * archive: The log file's archive mode. See the + /// FileChannel class for details. + /// * times: The log file's time mode. See the + /// FileChannel class for details. + /// * compress: Enable or disable compression of + /// archived files. See the FileChannel class + /// for details. + /// * purgeAge: Maximum age of an archived log file before + /// it is purged. See the FileChannel class for + /// details. + /// * purgeCount: Maximum number of archived log files before + /// files are purged. See the FileChannel class + /// for details. + + std::string getProperty(const std::string& name) const; + /// Returns the value of the property with the given name. + /// See setProperty() for a description of the supported + /// properties. + + Timestamp creationDate() const; + /// Returns the log file's creation date. + + UInt64 size() const; + /// Returns the log file's current size in bytes. + + const std::string& path() const; + /// Returns the log file's path. + + static const std::string PROP_PATH; + static const std::string PROP_ROTATION; + static const std::string PROP_ARCHIVE; + static const std::string PROP_TIMES; + static const std::string PROP_COMPRESS; + static const std::string PROP_PURGEAGE; + static const std::string PROP_PURGECOUNT; + +protected: + ~FileChannel(); + void setRotation(const std::string& rotation); + void setArchive(const std::string& archive); + void setCompress(const std::string& compress); + void setPurgeAge(const std::string& age); + void setPurgeCount(const std::string& count); + void purge(); + +private: + std::string _path; + std::string _times; + std::string _rotation; + std::string _archive; + bool _compress; + std::string _purgeAge; + std::string _purgeCount; + LogFile* _pFile; + RotateStrategy* _pRotateStrategy; + ArchiveStrategy* _pArchiveStrategy; + PurgeStrategy* _pPurgeStrategy; + FastMutex _mutex; +}; + + +} // namespace Poco + + +#endif // Foundation_FileChannel_INCLUDED diff --git a/Foundation/include/Poco/FileStreamFactory.h b/Foundation/include/Poco/FileStreamFactory.h index 728035069..22da91d0f 100644 --- a/Foundation/include/Poco/FileStreamFactory.h +++ b/Foundation/include/Poco/FileStreamFactory.h @@ -1,83 +1,83 @@ -// -// FileStreamFactory.h -// -// $Id: //poco/1.2/Foundation/include/Poco/FileStreamFactory.h#1 $ -// -// Library: Foundation -// Package: URI -// Module: FileStreamFactory -// -// Definition of the FileStreamFactory class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_FileStreamFactory_INCLUDED -#define Foundation_FileStreamFactory_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/URIStreamFactory.h" - - -namespace Poco { - - -class Path; - - -class Foundation_API FileStreamFactory: public URIStreamFactory - /// An implementation of the URIStreamFactory interface - /// that handles file URIs. -{ -public: - FileStreamFactory(); - /// Creates the FileStreamFactory. - - ~FileStreamFactory(); - /// Destroys the FileStreamFactory. - - std::istream* open(const URI& uri); - /// Creates and opens a file stream in binary mode for the given URI. - /// The URI must be either a file URI or a relative URI reference - /// containing a path to a local file. - /// - /// Throws an FileNotFound exception if the file cannot - /// be opened. - - std::istream* open(const Path& path); - /// Creates and opens a file stream in binary mode for the given path. - /// - /// Throws an FileNotFound exception if the file cannot - /// be opened. -}; - - -} // namespace Poco - - -#endif // Foundation_FileStreamFactory_INCLUDED +// +// FileStreamFactory.h +// +// $Id: //poco/1.2/Foundation/include/Poco/FileStreamFactory.h#1 $ +// +// Library: Foundation +// Package: URI +// Module: FileStreamFactory +// +// Definition of the FileStreamFactory class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_FileStreamFactory_INCLUDED +#define Foundation_FileStreamFactory_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/URIStreamFactory.h" + + +namespace Poco { + + +class Path; + + +class Foundation_API FileStreamFactory: public URIStreamFactory + /// An implementation of the URIStreamFactory interface + /// that handles file URIs. +{ +public: + FileStreamFactory(); + /// Creates the FileStreamFactory. + + ~FileStreamFactory(); + /// Destroys the FileStreamFactory. + + std::istream* open(const URI& uri); + /// Creates and opens a file stream in binary mode for the given URI. + /// The URI must be either a file URI or a relative URI reference + /// containing a path to a local file. + /// + /// Throws an FileNotFound exception if the file cannot + /// be opened. + + std::istream* open(const Path& path); + /// Creates and opens a file stream in binary mode for the given path. + /// + /// Throws an FileNotFound exception if the file cannot + /// be opened. +}; + + +} // namespace Poco + + +#endif // Foundation_FileStreamFactory_INCLUDED diff --git a/Foundation/include/Poco/File_UNIX.h b/Foundation/include/Poco/File_UNIX.h index d9fc0ced0..9dc240023 100644 --- a/Foundation/include/Poco/File_UNIX.h +++ b/Foundation/include/Poco/File_UNIX.h @@ -1,98 +1,98 @@ -// -// File_UNIX.h -// -// $Id: //poco/1.2/Foundation/include/Poco/File_UNIX.h#1 $ -// -// Library: Foundation -// Package: Filesystem -// Module: File -// -// Definition of the FileImpl class for Unix. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_File_UNIX_INCLUDED -#define Foundation_File_UNIX_INCLUDED - - -#include "Poco/Foundation.h" - - -namespace Poco { - - -class FileImpl -{ -protected: - typedef UInt64 FileSizeImpl; - - FileImpl(); - FileImpl(const std::string& path); - virtual ~FileImpl(); - void swapImpl(FileImpl& file); - void setPathImpl(const std::string& path); - const std::string& getPathImpl() const; - bool existsImpl() const; - bool canReadImpl() const; - bool canWriteImpl() const; - bool isFileImpl() const; - bool isDirectoryImpl() const; - bool isLinkImpl() const; - Timestamp createdImpl() const; - Timestamp getLastModifiedImpl() const; - void setLastModifiedImpl(const Timestamp& ts); - FileSizeImpl getSizeImpl() const; - void setSizeImpl(FileSizeImpl size); - void setWriteableImpl(bool flag = true); - void copyToImpl(const std::string& path) const; - void renameToImpl(const std::string& path); - void removeImpl(); - bool createFileImpl(); - bool createDirectoryImpl(); - static void handleError(const std::string& path); - -private: - std::string _path; - - friend class DirectoryIteratorImpl; -}; - - -// -// inlines -// -inline const std::string& FileImpl::getPathImpl() const -{ - return _path; -} - - -} // namespace Poco - - -#endif // Foundation_File_UNIX_INCLUDED +// +// File_UNIX.h +// +// $Id: //poco/1.2/Foundation/include/Poco/File_UNIX.h#1 $ +// +// Library: Foundation +// Package: Filesystem +// Module: File +// +// Definition of the FileImpl class for Unix. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_File_UNIX_INCLUDED +#define Foundation_File_UNIX_INCLUDED + + +#include "Poco/Foundation.h" + + +namespace Poco { + + +class FileImpl +{ +protected: + typedef UInt64 FileSizeImpl; + + FileImpl(); + FileImpl(const std::string& path); + virtual ~FileImpl(); + void swapImpl(FileImpl& file); + void setPathImpl(const std::string& path); + const std::string& getPathImpl() const; + bool existsImpl() const; + bool canReadImpl() const; + bool canWriteImpl() const; + bool isFileImpl() const; + bool isDirectoryImpl() const; + bool isLinkImpl() const; + Timestamp createdImpl() const; + Timestamp getLastModifiedImpl() const; + void setLastModifiedImpl(const Timestamp& ts); + FileSizeImpl getSizeImpl() const; + void setSizeImpl(FileSizeImpl size); + void setWriteableImpl(bool flag = true); + void copyToImpl(const std::string& path) const; + void renameToImpl(const std::string& path); + void removeImpl(); + bool createFileImpl(); + bool createDirectoryImpl(); + static void handleError(const std::string& path); + +private: + std::string _path; + + friend class DirectoryIteratorImpl; +}; + + +// +// inlines +// +inline const std::string& FileImpl::getPathImpl() const +{ + return _path; +} + + +} // namespace Poco + + +#endif // Foundation_File_UNIX_INCLUDED diff --git a/Foundation/include/Poco/File_VMS.h b/Foundation/include/Poco/File_VMS.h index 5cd67320b..e5a6cd157 100644 --- a/Foundation/include/Poco/File_VMS.h +++ b/Foundation/include/Poco/File_VMS.h @@ -1,97 +1,97 @@ -// -// File_VMS.h -// -// $Id: //poco/1.2/Foundation/include/Poco/File_VMS.h#1 $ -// -// Library: Foundation -// Package: Filesystem -// Module: File -// -// Definition of the FileImpl class for OpenVMS. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_File_VMS_INCLUDED -#define Foundation_File_VMS_INCLUDED - - -#include "Poco/Foundation.h" - - -namespace Poco { - - -class FileImpl -{ -protected: - typedef UInt64 FileSizeImpl; - - FileImpl(); - FileImpl(const std::string& path); - virtual ~FileImpl(); - void setPath(const std::string& path); - void swapImpl(FileImpl& file); - void setPathImpl(const std::string& path); - const std::string& getPathImpl() const; - bool existsImpl() const; - bool canReadImpl() const; - bool canWriteImpl() const; - bool isFileImpl() const; - bool isDirectoryImpl() const; - bool isLinkImpl() const; - Timestamp createdImpl() const; - Timestamp getLastModifiedImpl() const; - void setLastModifiedImpl(const Timestamp& ts); - FileSizeImpl getSizeImpl() const; - void setSizeImpl(FileSizeImpl size); - void setWriteableImpl(bool flag = true); - void copyToImpl(const std::string& path) const; - void renameToImpl(const std::string& path); - void removeImpl(); - bool createFileImpl(); - bool createDirectoryImpl(); - static void handleError(const std::string& path); - -private: - std::string _path; -}; - - -// -// inlines -// -inline const std::string& FileImpl::getPathImpl() const -{ - return _path; -} - - -} // namespace Poco - - -#endif // Foundation_File_VMS_INCLUDED +// +// File_VMS.h +// +// $Id: //poco/1.2/Foundation/include/Poco/File_VMS.h#1 $ +// +// Library: Foundation +// Package: Filesystem +// Module: File +// +// Definition of the FileImpl class for OpenVMS. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_File_VMS_INCLUDED +#define Foundation_File_VMS_INCLUDED + + +#include "Poco/Foundation.h" + + +namespace Poco { + + +class FileImpl +{ +protected: + typedef UInt64 FileSizeImpl; + + FileImpl(); + FileImpl(const std::string& path); + virtual ~FileImpl(); + void setPath(const std::string& path); + void swapImpl(FileImpl& file); + void setPathImpl(const std::string& path); + const std::string& getPathImpl() const; + bool existsImpl() const; + bool canReadImpl() const; + bool canWriteImpl() const; + bool isFileImpl() const; + bool isDirectoryImpl() const; + bool isLinkImpl() const; + Timestamp createdImpl() const; + Timestamp getLastModifiedImpl() const; + void setLastModifiedImpl(const Timestamp& ts); + FileSizeImpl getSizeImpl() const; + void setSizeImpl(FileSizeImpl size); + void setWriteableImpl(bool flag = true); + void copyToImpl(const std::string& path) const; + void renameToImpl(const std::string& path); + void removeImpl(); + bool createFileImpl(); + bool createDirectoryImpl(); + static void handleError(const std::string& path); + +private: + std::string _path; +}; + + +// +// inlines +// +inline const std::string& FileImpl::getPathImpl() const +{ + return _path; +} + + +} // namespace Poco + + +#endif // Foundation_File_VMS_INCLUDED diff --git a/Foundation/include/Poco/File_WIN32.h b/Foundation/include/Poco/File_WIN32.h index 0076d7896..84e4ee98a 100644 --- a/Foundation/include/Poco/File_WIN32.h +++ b/Foundation/include/Poco/File_WIN32.h @@ -1,100 +1,100 @@ -// -// File_WIN32.h -// -// $Id: //poco/1.2/Foundation/include/Poco/File_WIN32.h#1 $ -// -// Library: Foundation -// Package: Filesystem -// Module: File -// -// Definition of the FileImpl class for WIN32. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_File_WIN32_INCLUDED -#define Foundation_File_WIN32_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/Timestamp.h" - - -namespace Poco { - - -class Foundation_API FileImpl -{ -protected: - typedef UInt64 FileSizeImpl; - - FileImpl(); - FileImpl(const std::string& path); - virtual ~FileImpl(); - void swapImpl(FileImpl& file); - void setPathImpl(const std::string& path); - const std::string& getPathImpl() const; - bool existsImpl() const; - bool canReadImpl() const; - bool canWriteImpl() const; - bool isFileImpl() const; - bool isDirectoryImpl() const; - bool isLinkImpl() const; - Timestamp createdImpl() const; - Timestamp getLastModifiedImpl() const; - void setLastModifiedImpl(const Timestamp& ts); - FileSizeImpl getSizeImpl() const; - void setSizeImpl(FileSizeImpl size); - void setWriteableImpl(bool flag = true); - void copyToImpl(const std::string& path) const; - void renameToImpl(const std::string& path); - void removeImpl(); - bool createFileImpl(); - bool createDirectoryImpl(); - static void handleError(const std::string& path); - -private: - std::string _path; - - friend class FileHandle; - friend class DirectoryIteratorImpl; -}; - - -// -// inlines -// -inline const std::string& FileImpl::getPathImpl() const -{ - return _path; -} - - -} // namespace Poco - - -#endif // Foundation_File_WIN32_INCLUDED +// +// File_WIN32.h +// +// $Id: //poco/1.2/Foundation/include/Poco/File_WIN32.h#1 $ +// +// Library: Foundation +// Package: Filesystem +// Module: File +// +// Definition of the FileImpl class for WIN32. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_File_WIN32_INCLUDED +#define Foundation_File_WIN32_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Timestamp.h" + + +namespace Poco { + + +class Foundation_API FileImpl +{ +protected: + typedef UInt64 FileSizeImpl; + + FileImpl(); + FileImpl(const std::string& path); + virtual ~FileImpl(); + void swapImpl(FileImpl& file); + void setPathImpl(const std::string& path); + const std::string& getPathImpl() const; + bool existsImpl() const; + bool canReadImpl() const; + bool canWriteImpl() const; + bool isFileImpl() const; + bool isDirectoryImpl() const; + bool isLinkImpl() const; + Timestamp createdImpl() const; + Timestamp getLastModifiedImpl() const; + void setLastModifiedImpl(const Timestamp& ts); + FileSizeImpl getSizeImpl() const; + void setSizeImpl(FileSizeImpl size); + void setWriteableImpl(bool flag = true); + void copyToImpl(const std::string& path) const; + void renameToImpl(const std::string& path); + void removeImpl(); + bool createFileImpl(); + bool createDirectoryImpl(); + static void handleError(const std::string& path); + +private: + std::string _path; + + friend class FileHandle; + friend class DirectoryIteratorImpl; +}; + + +// +// inlines +// +inline const std::string& FileImpl::getPathImpl() const +{ + return _path; +} + + +} // namespace Poco + + +#endif // Foundation_File_WIN32_INCLUDED diff --git a/Foundation/include/Poco/File_WIN32U.h b/Foundation/include/Poco/File_WIN32U.h index 851a46435..69dcddcfc 100644 --- a/Foundation/include/Poco/File_WIN32U.h +++ b/Foundation/include/Poco/File_WIN32U.h @@ -1,101 +1,101 @@ -// -// File_WIN32U.h -// -// $Id: //poco/1.2/Foundation/include/Poco/File_WIN32U.h#1 $ -// -// Library: Foundation -// Package: Filesystem -// Module: File -// -// Definition of the Unicode FileImpl class for WIN32. -// -// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_File_WIN32U_INCLUDED -#define Foundation_File_WIN32U_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/Timestamp.h" - - -namespace Poco { - - -class Foundation_API FileImpl -{ -protected: - typedef UInt64 FileSizeImpl; - - FileImpl(); - FileImpl(const std::string& path); - virtual ~FileImpl(); - void swapImpl(FileImpl& file); - void setPathImpl(const std::string& path); - const std::string& getPathImpl() const; - bool existsImpl() const; - bool canReadImpl() const; - bool canWriteImpl() const; - bool isFileImpl() const; - bool isDirectoryImpl() const; - bool isLinkImpl() const; - Timestamp createdImpl() const; - Timestamp getLastModifiedImpl() const; - void setLastModifiedImpl(const Timestamp& ts); - FileSizeImpl getSizeImpl() const; - void setSizeImpl(FileSizeImpl size); - void setWriteableImpl(bool flag = true); - void copyToImpl(const std::string& path) const; - void renameToImpl(const std::string& path); - void removeImpl(); - bool createFileImpl(); - bool createDirectoryImpl(); - static void handleError(const std::string& path); - -private: - std::string _path; - std::wstring _upath; - - friend class FileHandle; - friend class DirectoryIteratorImpl; -}; - - -// -// inlines -// -inline const std::string& FileImpl::getPathImpl() const -{ - return _path; -} - - -} // namespace Poco - - -#endif // Foundation_File_WIN32U_INCLUDED +// +// File_WIN32U.h +// +// $Id: //poco/1.2/Foundation/include/Poco/File_WIN32U.h#1 $ +// +// Library: Foundation +// Package: Filesystem +// Module: File +// +// Definition of the Unicode FileImpl class for WIN32. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_File_WIN32U_INCLUDED +#define Foundation_File_WIN32U_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Timestamp.h" + + +namespace Poco { + + +class Foundation_API FileImpl +{ +protected: + typedef UInt64 FileSizeImpl; + + FileImpl(); + FileImpl(const std::string& path); + virtual ~FileImpl(); + void swapImpl(FileImpl& file); + void setPathImpl(const std::string& path); + const std::string& getPathImpl() const; + bool existsImpl() const; + bool canReadImpl() const; + bool canWriteImpl() const; + bool isFileImpl() const; + bool isDirectoryImpl() const; + bool isLinkImpl() const; + Timestamp createdImpl() const; + Timestamp getLastModifiedImpl() const; + void setLastModifiedImpl(const Timestamp& ts); + FileSizeImpl getSizeImpl() const; + void setSizeImpl(FileSizeImpl size); + void setWriteableImpl(bool flag = true); + void copyToImpl(const std::string& path) const; + void renameToImpl(const std::string& path); + void removeImpl(); + bool createFileImpl(); + bool createDirectoryImpl(); + static void handleError(const std::string& path); + +private: + std::string _path; + std::wstring _upath; + + friend class FileHandle; + friend class DirectoryIteratorImpl; +}; + + +// +// inlines +// +inline const std::string& FileImpl::getPathImpl() const +{ + return _path; +} + + +} // namespace Poco + + +#endif // Foundation_File_WIN32U_INCLUDED diff --git a/Foundation/include/Poco/Format.h b/Foundation/include/Poco/Format.h index d391ed169..174cf69f1 100644 --- a/Foundation/include/Poco/Format.h +++ b/Foundation/include/Poco/Format.h @@ -1,154 +1,154 @@ -// -// Format.h -// -// $Id: //poco/1.2/Foundation/include/Poco/Format.h#1 $ -// -// Library: Foundation -// Package: Core -// Module: Format -// -// Definition of the format freestanding function. -// -// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. -// 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. -// -// 3. Redistributions in any form must be accompanied by information on -// how to obtain complete source code for this software and any -// accompanying software that uses this software. The source code -// must either be included in the distribution or be available for no -// more than the cost of distribution plus a nominal fee, and must be -// freely redistributable under reasonable conditions. For an -// executable file, complete source code means the source code for all -// modules it contains. It does not include source code for modules or -// files that typically accompany the major components of the operating -// system on which the executable file runs. -// -// 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 Foundation_Format_INCLUDED -#define Foundation_Format_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/Any.h" -#include - - -namespace Poco { - - -std::string Foundation_API format(const std::string& fmt, const Any& value); - /// This function implements sprintf-style formatting in a typesafe way. - /// Various variants of the function are available, supporting a - /// different number of arguments (up to six). - /// - /// The formatting is controlled by the format string in fmt. - /// Format strings are quite similar to those of the printf() function, but - /// there are some minor differences. - /// - /// The format string can consist of any sequence of characters; certain - /// characters have a special meaning. Characters without a special meaning - /// are copied verbatim to the result. A percent sign (%) marks the beginning - /// of a format specification. Format specifications have the following syntax: - /// - /// %[][][.][] - /// - /// Flags, width, precision and prefix are optional. The only required part of - /// the format specification, apart from the percent sign, is the type. - /// - /// Following are valid type specifications and their meaning: - /// - /// * c character - /// * d signed decimal integer - /// * i signed decimal integer - /// * o unsigned octal integer - /// * u unsigned decimal integer - /// * x unsigned hexadecimal integer (lower case) - /// * X unsigned hexadecimal integer (upper case) - /// * e signed floating-point value in the form [-]d.dddde[]dd[d] - /// * E signed floating-point value in the form [-]d.ddddE[]dd[d] - /// * f signed floating-point value in the form [-]dddd.dddd - /// * s std::string - /// - /// The following flags are supported: - /// - /// * - left align the result within the given field width - /// * + prefix the output value with a sign (+ or –) if the output value is of a signed type - /// * 0 if width is prefixed with 0, zeros are added until the minimum width is reached - /// * # For o, x, X, the # flag prefixes any nonzero output value with 0, 0x, or 0X, respectively; - /// for e, E, f, the # flag forces the output value to contain a decimal point in all cases. - /// - /// The following modifiers are supported: - /// - /// * (none) argument is char (c), int (d, i), unsigned (o, u, x, X) double (e, E, f, g, G) or string (s) - /// * l argument is long (d, i), unsigned long (o, u, x, X) or long double (e, E, f, g, G) - /// * L argument is long long (d, i), unsigned long long (o, u, x, X) - /// * h argument is short (d, i), unsigned short (o, u, x, X) or float (e, E, f, g, G) - /// - /// The width argument is a nonnegative decimal integer controlling the minimum number of characters printed. - /// If the number of characters in the output value is less than the specified width, blanks or - /// leading zeros are added, according to the specified flags (-, +, 0). - /// - /// Precision is a nonnegative decimal integer, preceded by a period (.), which specifies the number of characters - /// to be printed, the number of decimal places, or the number of significant digits. - /// - /// Throws a BadCastException if an argument does not correspond to the type of its format specification. - /// - /// If there are more format specifiers than values, the format specifiers without a corresponding value - /// are copied verbatim to output. - /// - /// If there are more values than format specifiers, the superfluous values are ignored. - /// - /// Usage Example: - /// std::string s = format("The answer to life, the universe, and everything is %d", 42); - -std::string Foundation_API format(const std::string& fmt, const Any& value1, const Any& value2); -std::string Foundation_API format(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3); -std::string Foundation_API format(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4); -std::string Foundation_API format(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5); -std::string Foundation_API format(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6); - - -void Foundation_API format(std::string& result, const std::string& fmt, const Any& value); - /// Appends the formatted string to result. - -void Foundation_API format(std::string& result, const std::string& fmt, const Any& value1, const Any& value2); -void Foundation_API format(std::string& result, const std::string& fmt, const Any& value1, const Any& value2, const Any& value3); -void Foundation_API format(std::string& result, const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4); -void Foundation_API format(std::string& result, const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5); -void Foundation_API format(std::string& result, const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6); - - -void Foundation_API format(std::string& result, const std::string& fmt, const std::vector& values); - /// Supports a variable number of arguments and is used by - /// all other variants of format(). - - -} // namespace Poco - - -#endif // Foundation_Format_INCLUDED +// +// Format.h +// +// $Id: //poco/1.2/Foundation/include/Poco/Format.h#1 $ +// +// Library: Foundation +// Package: Core +// Module: Format +// +// Definition of the format freestanding function. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// 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. +// +// 3. Redistributions in any form must be accompanied by information on +// how to obtain complete source code for this software and any +// accompanying software that uses this software. The source code +// must either be included in the distribution or be available for no +// more than the cost of distribution plus a nominal fee, and must be +// freely redistributable under reasonable conditions. For an +// executable file, complete source code means the source code for all +// modules it contains. It does not include source code for modules or +// files that typically accompany the major components of the operating +// system on which the executable file runs. +// +// 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 Foundation_Format_INCLUDED +#define Foundation_Format_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Any.h" +#include + + +namespace Poco { + + +std::string Foundation_API format(const std::string& fmt, const Any& value); + /// This function implements sprintf-style formatting in a typesafe way. + /// Various variants of the function are available, supporting a + /// different number of arguments (up to six). + /// + /// The formatting is controlled by the format string in fmt. + /// Format strings are quite similar to those of the printf() function, but + /// there are some minor differences. + /// + /// The format string can consist of any sequence of characters; certain + /// characters have a special meaning. Characters without a special meaning + /// are copied verbatim to the result. A percent sign (%) marks the beginning + /// of a format specification. Format specifications have the following syntax: + /// + /// %[][][.][] + /// + /// Flags, width, precision and prefix are optional. The only required part of + /// the format specification, apart from the percent sign, is the type. + /// + /// Following are valid type specifications and their meaning: + /// + /// * c character + /// * d signed decimal integer + /// * i signed decimal integer + /// * o unsigned octal integer + /// * u unsigned decimal integer + /// * x unsigned hexadecimal integer (lower case) + /// * X unsigned hexadecimal integer (upper case) + /// * e signed floating-point value in the form [-]d.dddde[]dd[d] + /// * E signed floating-point value in the form [-]d.ddddE[]dd[d] + /// * f signed floating-point value in the form [-]dddd.dddd + /// * s std::string + /// + /// The following flags are supported: + /// + /// * - left align the result within the given field width + /// * + prefix the output value with a sign (+ or –) if the output value is of a signed type + /// * 0 if width is prefixed with 0, zeros are added until the minimum width is reached + /// * # For o, x, X, the # flag prefixes any nonzero output value with 0, 0x, or 0X, respectively; + /// for e, E, f, the # flag forces the output value to contain a decimal point in all cases. + /// + /// The following modifiers are supported: + /// + /// * (none) argument is char (c), int (d, i), unsigned (o, u, x, X) double (e, E, f, g, G) or string (s) + /// * l argument is long (d, i), unsigned long (o, u, x, X) or long double (e, E, f, g, G) + /// * L argument is long long (d, i), unsigned long long (o, u, x, X) + /// * h argument is short (d, i), unsigned short (o, u, x, X) or float (e, E, f, g, G) + /// + /// The width argument is a nonnegative decimal integer controlling the minimum number of characters printed. + /// If the number of characters in the output value is less than the specified width, blanks or + /// leading zeros are added, according to the specified flags (-, +, 0). + /// + /// Precision is a nonnegative decimal integer, preceded by a period (.), which specifies the number of characters + /// to be printed, the number of decimal places, or the number of significant digits. + /// + /// Throws a BadCastException if an argument does not correspond to the type of its format specification. + /// + /// If there are more format specifiers than values, the format specifiers without a corresponding value + /// are copied verbatim to output. + /// + /// If there are more values than format specifiers, the superfluous values are ignored. + /// + /// Usage Example: + /// std::string s = format("The answer to life, the universe, and everything is %d", 42); + +std::string Foundation_API format(const std::string& fmt, const Any& value1, const Any& value2); +std::string Foundation_API format(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3); +std::string Foundation_API format(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4); +std::string Foundation_API format(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5); +std::string Foundation_API format(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6); + + +void Foundation_API format(std::string& result, const std::string& fmt, const Any& value); + /// Appends the formatted string to result. + +void Foundation_API format(std::string& result, const std::string& fmt, const Any& value1, const Any& value2); +void Foundation_API format(std::string& result, const std::string& fmt, const Any& value1, const Any& value2, const Any& value3); +void Foundation_API format(std::string& result, const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4); +void Foundation_API format(std::string& result, const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5); +void Foundation_API format(std::string& result, const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6); + + +void Foundation_API format(std::string& result, const std::string& fmt, const std::vector& values); + /// Supports a variable number of arguments and is used by + /// all other variants of format(). + + +} // namespace Poco + + +#endif // Foundation_Format_INCLUDED diff --git a/Foundation/include/Poco/Formatter.h b/Foundation/include/Poco/Formatter.h index 86963f055..2adcb8e3f 100644 --- a/Foundation/include/Poco/Formatter.h +++ b/Foundation/include/Poco/Formatter.h @@ -1,96 +1,96 @@ -// -// Formatter.h -// -// $Id: //poco/1.2/Foundation/include/Poco/Formatter.h#1 $ -// -// Library: Foundation -// Package: Logging -// Module: Formatter -// -// Definition of the Formatter class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_Formatter_INCLUDED -#define Foundation_Formatter_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/Configurable.h" -#include "Poco/RefCountedObject.h" - - -namespace Poco { - - -class Message; - - -class Foundation_API Formatter: public Configurable, public RefCountedObject - /// The base class for all Formatter classes. - /// - /// A formatter basically takes a Message object - /// and formats it into a string. How the formatting - /// is exactly done is up to the implementation of - /// Formatter. For example, a very simple implementation - /// might simply take the message's Text (see Message::getText()). - /// A useful implementation should at least take the Message's - /// Time, Priority and Text fields and put them into a string. - /// - /// The Formatter class supports the Configurable - /// interface, so the behaviour of certain formatters - /// is configurable. - /// - /// Trivial implementations of of getProperty() and - /// setProperty() are provided. - /// - /// Subclasses must at least provide a format() method. -{ -public: - Formatter(); - /// Creates the formatter. - - virtual ~Formatter(); - /// Destroys the formatter. - - virtual void format(const Message& msg, std::string& text) = 0; - /// Formats the message and places the result in text. - /// Subclasses must override this method. - - void setProperty(const std::string& name, const std::string& value); - /// Throws a PropertyNotSupportedException. - - std::string getProperty(const std::string& name) const; - /// Throws a PropertyNotSupportedException. -}; - - -} // namespace Poco - - -#endif // Foundation_Formatter_INCLUDED +// +// Formatter.h +// +// $Id: //poco/1.2/Foundation/include/Poco/Formatter.h#1 $ +// +// Library: Foundation +// Package: Logging +// Module: Formatter +// +// Definition of the Formatter class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_Formatter_INCLUDED +#define Foundation_Formatter_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Configurable.h" +#include "Poco/RefCountedObject.h" + + +namespace Poco { + + +class Message; + + +class Foundation_API Formatter: public Configurable, public RefCountedObject + /// The base class for all Formatter classes. + /// + /// A formatter basically takes a Message object + /// and formats it into a string. How the formatting + /// is exactly done is up to the implementation of + /// Formatter. For example, a very simple implementation + /// might simply take the message's Text (see Message::getText()). + /// A useful implementation should at least take the Message's + /// Time, Priority and Text fields and put them into a string. + /// + /// The Formatter class supports the Configurable + /// interface, so the behaviour of certain formatters + /// is configurable. + /// + /// Trivial implementations of of getProperty() and + /// setProperty() are provided. + /// + /// Subclasses must at least provide a format() method. +{ +public: + Formatter(); + /// Creates the formatter. + + virtual ~Formatter(); + /// Destroys the formatter. + + virtual void format(const Message& msg, std::string& text) = 0; + /// Formats the message and places the result in text. + /// Subclasses must override this method. + + void setProperty(const std::string& name, const std::string& value); + /// Throws a PropertyNotSupportedException. + + std::string getProperty(const std::string& name) const; + /// Throws a PropertyNotSupportedException. +}; + + +} // namespace Poco + + +#endif // Foundation_Formatter_INCLUDED diff --git a/Foundation/include/Poco/FormattingChannel.h b/Foundation/include/Poco/FormattingChannel.h index 7e724fd18..7db0607c7 100644 --- a/Foundation/include/Poco/FormattingChannel.h +++ b/Foundation/include/Poco/FormattingChannel.h @@ -1,118 +1,118 @@ -// -// FormattingChannel.h -// -// $Id: //poco/1.2/Foundation/include/Poco/FormattingChannel.h#2 $ -// -// Library: Foundation -// Package: Logging -// Module: Formatter -// -// Definition of the FormattingChannel class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_FormattingChannel_INCLUDED -#define Foundation_FormattingChannel_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/Channel.h" - - -namespace Poco { - - -class Formatter; - - -class Foundation_API FormattingChannel: public Channel - /// The FormattingChannel is a filter channel that routes - /// a Message through a Formatter before passing it on - /// to the destination channel. -{ -public: - FormattingChannel(); - /// Creates a FormattingChannel. - - FormattingChannel(Formatter* pFormatter); - /// Creates a FormattingChannel and attaches a Formatter. - - FormattingChannel(Formatter* pFormatter, Channel* pChannel); - /// Creates a FormattingChannel and attaches a Formatter - /// and a Channel. - - void setFormatter(Formatter* pFormatter); - /// Sets the Formatter used to format the messages - /// before they are passed on. If null, the message - /// is passed on unmodified. - - Formatter* getFormatter() const; - /// Returns the Formatter used to format messages, - /// which may be null. - - void setChannel(Channel* pChannel); - /// Sets the destination channel to which the formatted - /// messages are passed on. - - Channel* getChannel() const; - /// Returns the channel to which the formatted - /// messages are passed on. - - void log(const Message& msg); - /// Formats the given Message using the Formatter and - /// passes the formatted message on to the destination - /// Channel. - - void setProperty(const std::string& name, const std::string& value); - /// Sets or changes a configuration property. - /// - /// Only the "channel" and "formatter" properties are supported, which allow - /// setting the target channel and formatter, respectively, via the LoggingRegistry. - /// The "channel" and "formatter" properties are set-only. - /// - /// Unsupported properties are passed to the attached Channel. - - void open(); - /// Opens the attached channel. - - void close(); - /// Closes the attached channel. - -protected: - ~FormattingChannel(); - -private: - Formatter* _pFormatter; - Channel* _pChannel; -}; - - -} // namespace Poco - - -#endif // Foundation_FormattingChannel_INCLUDED +// +// FormattingChannel.h +// +// $Id: //poco/1.2/Foundation/include/Poco/FormattingChannel.h#2 $ +// +// Library: Foundation +// Package: Logging +// Module: Formatter +// +// Definition of the FormattingChannel class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_FormattingChannel_INCLUDED +#define Foundation_FormattingChannel_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Channel.h" + + +namespace Poco { + + +class Formatter; + + +class Foundation_API FormattingChannel: public Channel + /// The FormattingChannel is a filter channel that routes + /// a Message through a Formatter before passing it on + /// to the destination channel. +{ +public: + FormattingChannel(); + /// Creates a FormattingChannel. + + FormattingChannel(Formatter* pFormatter); + /// Creates a FormattingChannel and attaches a Formatter. + + FormattingChannel(Formatter* pFormatter, Channel* pChannel); + /// Creates a FormattingChannel and attaches a Formatter + /// and a Channel. + + void setFormatter(Formatter* pFormatter); + /// Sets the Formatter used to format the messages + /// before they are passed on. If null, the message + /// is passed on unmodified. + + Formatter* getFormatter() const; + /// Returns the Formatter used to format messages, + /// which may be null. + + void setChannel(Channel* pChannel); + /// Sets the destination channel to which the formatted + /// messages are passed on. + + Channel* getChannel() const; + /// Returns the channel to which the formatted + /// messages are passed on. + + void log(const Message& msg); + /// Formats the given Message using the Formatter and + /// passes the formatted message on to the destination + /// Channel. + + void setProperty(const std::string& name, const std::string& value); + /// Sets or changes a configuration property. + /// + /// Only the "channel" and "formatter" properties are supported, which allow + /// setting the target channel and formatter, respectively, via the LoggingRegistry. + /// The "channel" and "formatter" properties are set-only. + /// + /// Unsupported properties are passed to the attached Channel. + + void open(); + /// Opens the attached channel. + + void close(); + /// Closes the attached channel. + +protected: + ~FormattingChannel(); + +private: + Formatter* _pFormatter; + Channel* _pChannel; +}; + + +} // namespace Poco + + +#endif // Foundation_FormattingChannel_INCLUDED diff --git a/Foundation/include/Poco/Foundation.h b/Foundation/include/Poco/Foundation.h index b430d13f9..58705e19d 100644 --- a/Foundation/include/Poco/Foundation.h +++ b/Foundation/include/Poco/Foundation.h @@ -1,104 +1,104 @@ -// -// Foundation.h -// -// $Id: //poco/1.2/Foundation/include/Poco/Foundation.h#2 $ -// -// Library: Foundation -// Package: Core -// Module: Foundation -// -// Basic definitions for the POCO Foundation library. -// This file must be the first file included by every other Foundation -// header file. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_Foundation_INCLUDED -#define Foundation_Foundation_INCLUDED - - -// -// Ensure that POCO_DLL is default unless POCO_STATIC is defined -// -#if defined(_WIN32) && defined(_DLL) - #if !defined(POCO_DLL) && !defined(POCO_STATIC) - #define POCO_DLL - #endif -#endif - - -// -// The following block is the standard way of creating macros which make exporting -// from a DLL simpler. All files within this DLL are compiled with the Foundation_EXPORTS -// symbol defined on the command line. this symbol should not be defined on any project -// that uses this DLL. This way any other project whose source files include this file see -// Foundation_API functions as being imported from a DLL, wheras this DLL sees symbols -// defined with this macro as being exported. -// -#if defined(_WIN32) && defined(POCO_DLL) - #if defined(Foundation_EXPORTS) - #define Foundation_API __declspec(dllexport) - #else - #define Foundation_API __declspec(dllimport) - #endif -#endif - - -#if !defined(Foundation_API) - #define Foundation_API -#endif - - -// -// Include library configuration -// -#include "Poco/Config.h" - - -// -// Include platform-specific definitions -// -#include "Poco/Platform.h" -#if defined(_WIN32) - #include "Poco/Platform_WIN32.h" -#elif defined(__VMS) - #include "Poco/Platform_VMS.h" -#elif defined(POCO_OS_FAMILY_UNIX) - #include "Poco/Platform_POSIX.h" -#endif - - -// -// Pull in basic definitions -// -#include "Poco/Bugcheck.h" -#include "Poco/Types.h" -#include - - -#endif // Foundation_Foundation_INCLUDED +// +// Foundation.h +// +// $Id: //poco/1.2/Foundation/include/Poco/Foundation.h#2 $ +// +// Library: Foundation +// Package: Core +// Module: Foundation +// +// Basic definitions for the POCO Foundation library. +// This file must be the first file included by every other Foundation +// header file. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_Foundation_INCLUDED +#define Foundation_Foundation_INCLUDED + + +// +// Ensure that POCO_DLL is default unless POCO_STATIC is defined +// +#if defined(_WIN32) && defined(_DLL) + #if !defined(POCO_DLL) && !defined(POCO_STATIC) + #define POCO_DLL + #endif +#endif + + +// +// The following block is the standard way of creating macros which make exporting +// from a DLL simpler. All files within this DLL are compiled with the Foundation_EXPORTS +// symbol defined on the command line. this symbol should not be defined on any project +// that uses this DLL. This way any other project whose source files include this file see +// Foundation_API functions as being imported from a DLL, wheras this DLL sees symbols +// defined with this macro as being exported. +// +#if defined(_WIN32) && defined(POCO_DLL) + #if defined(Foundation_EXPORTS) + #define Foundation_API __declspec(dllexport) + #else + #define Foundation_API __declspec(dllimport) + #endif +#endif + + +#if !defined(Foundation_API) + #define Foundation_API +#endif + + +// +// Include library configuration +// +#include "Poco/Config.h" + + +// +// Include platform-specific definitions +// +#include "Poco/Platform.h" +#if defined(_WIN32) + #include "Poco/Platform_WIN32.h" +#elif defined(__VMS) + #include "Poco/Platform_VMS.h" +#elif defined(POCO_OS_FAMILY_UNIX) + #include "Poco/Platform_POSIX.h" +#endif + + +// +// Pull in basic definitions +// +#include "Poco/Bugcheck.h" +#include "Poco/Types.h" +#include + + +#endif // Foundation_Foundation_INCLUDED diff --git a/Foundation/include/Poco/Glob.h b/Foundation/include/Poco/Glob.h index 935f6bbe9..40609277a 100644 --- a/Foundation/include/Poco/Glob.h +++ b/Foundation/include/Poco/Glob.h @@ -1,158 +1,158 @@ -// -// Glob.h -// -// $Id: //poco/1.2/Foundation/include/Poco/Glob.h#1 $ -// -// Library: Foundation -// Package: Filesystem -// Module: Glob -// -// Definition of the Glob class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_Glob_INCLUDED -#define Foundation_Glob_INCLUDED - - -#include "Poco/Foundation.h" -#include - - -namespace Poco { - - -class Path; - - -class Foundation_API Glob - /// This class implements glob-style pattern matching - /// as known from Unix shells. - /// - /// In the pattern string, '*' matches any sequence of characters, - /// '?' matches any character, [SET] matches any character in the - /// specified set, [!SET] matches any character not in the specified - /// set. - /// - /// A set is composed of characters or ranges; a range looks like - /// character hyphen character (as in 0-9 or A-Z). - /// [0-9a-zA-Z_] is the set of characters allowed in C identifiers. - /// Any other character in the pattern must be matched exactly. - /// - /// To suppress the special syntactic significance of any of '[]*?!-\', - /// and match the character exactly, precede it with a backslash. - /// - /// UTF-8 encoded strings are not supported. -{ -public: - enum Options - /// Flags that modify the matching behavior. - { - GLOB_DEFAULT = 0x00, /// default behavior - GLOB_DOT_SPECIAL = 0x01, /// '*' and '?' do not match '.' at beginning of subject - GLOB_DIRS_ONLY = 0x80 /// only glob for directories (for internal use only) - }; - - Glob(const std::string& pattern, int options = 0); - /// Creates the Glob, using the given pattern. The pattern - /// must not be an empty string. - /// - /// If the GLOB_DOT_SPECIAL option is specified, '*' and '?' do - /// not match '.' at the beginning of a matched subject. This is useful for - /// making dot-files invisible in good old Unix-style. - - ~Glob(); - /// Destroys the Glob. - - bool match(const std::string& subject); - /// Matches the given subject against the glob pattern. - /// Returns true if the subject matches the pattern, false - /// otherwise. - - static void glob(const std::string& pathPattern, std::set& files, int options = 0); - /// Creates a set of files that match the given pathPattern. - /// - /// The path may be give in either Unix, Windows or VMS syntax and - /// is automatically expanded by calling Path::expand(). - /// - /// The pattern may contain wildcard expressions even in intermediate - /// directory names (e.g. /usr/include/*/*.h). - /// - /// Note that, for obvious reasons, escaping characters in a pattern - /// with a backslash does not work in Windows-style paths. - /// - /// Directories that for whatever reason cannot be traversed are - /// ignored. - - static void glob(const char* pathPattern, std::set& files, int options = 0); - /// Creates a set of files that match the given pathPattern. - /// - /// The path may be give in either Unix, Windows or VMS syntax and - /// is automatically expanded by calling Path::expand(). - /// - /// The pattern may contain wildcard expressions even in intermediate - /// directory names (e.g. /usr/include/*/*.h). - /// - /// Note that, for obvious reasons, escaping characters in a pattern - /// with a backslash does not work in Windows-style paths. - /// - /// Directories that for whatever reason cannot be traversed are - /// ignored. - - static void glob(const Path& pathPattern, std::set& files, int options = 0); - /// Creates a set of files that match the given pathPattern. - /// - /// The pattern may contain wildcard expressions even in intermediate - /// directory names (e.g. /usr/include/*/*.h). - /// - /// Note that, for obvious reasons, escaping characters in a pattern - /// with a backslash does not work in Windows-style paths. - /// - /// Directories that for whatever reason cannot be traversed are - /// ignored. - -protected: - bool match(std::string::const_iterator& itp, const std::string::const_iterator& endp, std::string::const_iterator& its, const std::string::const_iterator& ends); - bool matchAfterAsterisk(std::string::const_iterator itp, const std::string::const_iterator& endp, std::string::const_iterator its, const std::string::const_iterator& ends); - bool matchSet(std::string::const_iterator& itp, const std::string::const_iterator& endp, char c); - static void collect(const Path& pathPattern, const Path& base, const Path& current, const std::string& pattern, std::set& files, int options); - -private: - std::string _pattern; - int _options; - - Glob(); - Glob(const Glob&); - Glob& operator = (const Glob&); -}; - - -} // namespace Poco - - -#endif // Foundation_Glob_INCLUDED +// +// Glob.h +// +// $Id: //poco/1.2/Foundation/include/Poco/Glob.h#1 $ +// +// Library: Foundation +// Package: Filesystem +// Module: Glob +// +// Definition of the Glob class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_Glob_INCLUDED +#define Foundation_Glob_INCLUDED + + +#include "Poco/Foundation.h" +#include + + +namespace Poco { + + +class Path; + + +class Foundation_API Glob + /// This class implements glob-style pattern matching + /// as known from Unix shells. + /// + /// In the pattern string, '*' matches any sequence of characters, + /// '?' matches any character, [SET] matches any character in the + /// specified set, [!SET] matches any character not in the specified + /// set. + /// + /// A set is composed of characters or ranges; a range looks like + /// character hyphen character (as in 0-9 or A-Z). + /// [0-9a-zA-Z_] is the set of characters allowed in C identifiers. + /// Any other character in the pattern must be matched exactly. + /// + /// To suppress the special syntactic significance of any of '[]*?!-\', + /// and match the character exactly, precede it with a backslash. + /// + /// UTF-8 encoded strings are not supported. +{ +public: + enum Options + /// Flags that modify the matching behavior. + { + GLOB_DEFAULT = 0x00, /// default behavior + GLOB_DOT_SPECIAL = 0x01, /// '*' and '?' do not match '.' at beginning of subject + GLOB_DIRS_ONLY = 0x80 /// only glob for directories (for internal use only) + }; + + Glob(const std::string& pattern, int options = 0); + /// Creates the Glob, using the given pattern. The pattern + /// must not be an empty string. + /// + /// If the GLOB_DOT_SPECIAL option is specified, '*' and '?' do + /// not match '.' at the beginning of a matched subject. This is useful for + /// making dot-files invisible in good old Unix-style. + + ~Glob(); + /// Destroys the Glob. + + bool match(const std::string& subject); + /// Matches the given subject against the glob pattern. + /// Returns true if the subject matches the pattern, false + /// otherwise. + + static void glob(const std::string& pathPattern, std::set& files, int options = 0); + /// Creates a set of files that match the given pathPattern. + /// + /// The path may be give in either Unix, Windows or VMS syntax and + /// is automatically expanded by calling Path::expand(). + /// + /// The pattern may contain wildcard expressions even in intermediate + /// directory names (e.g. /usr/include/*/*.h). + /// + /// Note that, for obvious reasons, escaping characters in a pattern + /// with a backslash does not work in Windows-style paths. + /// + /// Directories that for whatever reason cannot be traversed are + /// ignored. + + static void glob(const char* pathPattern, std::set& files, int options = 0); + /// Creates a set of files that match the given pathPattern. + /// + /// The path may be give in either Unix, Windows or VMS syntax and + /// is automatically expanded by calling Path::expand(). + /// + /// The pattern may contain wildcard expressions even in intermediate + /// directory names (e.g. /usr/include/*/*.h). + /// + /// Note that, for obvious reasons, escaping characters in a pattern + /// with a backslash does not work in Windows-style paths. + /// + /// Directories that for whatever reason cannot be traversed are + /// ignored. + + static void glob(const Path& pathPattern, std::set& files, int options = 0); + /// Creates a set of files that match the given pathPattern. + /// + /// The pattern may contain wildcard expressions even in intermediate + /// directory names (e.g. /usr/include/*/*.h). + /// + /// Note that, for obvious reasons, escaping characters in a pattern + /// with a backslash does not work in Windows-style paths. + /// + /// Directories that for whatever reason cannot be traversed are + /// ignored. + +protected: + bool match(std::string::const_iterator& itp, const std::string::const_iterator& endp, std::string::const_iterator& its, const std::string::const_iterator& ends); + bool matchAfterAsterisk(std::string::const_iterator itp, const std::string::const_iterator& endp, std::string::const_iterator its, const std::string::const_iterator& ends); + bool matchSet(std::string::const_iterator& itp, const std::string::const_iterator& endp, char c); + static void collect(const Path& pathPattern, const Path& base, const Path& current, const std::string& pattern, std::set& files, int options); + +private: + std::string _pattern; + int _options; + + Glob(); + Glob(const Glob&); + Glob& operator = (const Glob&); +}; + + +} // namespace Poco + + +#endif // Foundation_Glob_INCLUDED diff --git a/Foundation/include/Poco/HMACEngine.h b/Foundation/include/Poco/HMACEngine.h index ae9a0f4e1..778dc5195 100644 --- a/Foundation/include/Poco/HMACEngine.h +++ b/Foundation/include/Poco/HMACEngine.h @@ -1,166 +1,166 @@ -// -// HMACEngine.h -// -// $Id: //poco/1.2/Foundation/include/Poco/HMACEngine.h#1 $ -// -// Library: Foundation -// Package: Crypt -// Module: HMACEngine -// -// Definition of the HMACEngine class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_HMACEngine_INCLUDED -#define Foundation_HMACEngine_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/DigestEngine.h" -#include - - -namespace Poco { - - -template -class HMACEngine: public DigestEngine - /// This class implementes the HMAC message - /// authentication code algorithm, as specified - /// in RFC 2104. The underlying DigestEngine - /// (MD5Engine, SHA1Engine, etc.) must be given as - /// template argument. - /// Since the HMACEngine is a DigestEngine, it can - /// be used with the DigestStream class to create - /// a HMAC for a stream. -{ -public: - enum - { - BLOCK_SIZE = Engine::BLOCK_SIZE, - DIGEST_SIZE = Engine::DIGEST_SIZE - }; - - HMACEngine(const std::string& passphrase) - { - init(passphrase.data(), (unsigned) passphrase.length()); - } - - HMACEngine(const char* passphrase, unsigned length) - { - poco_check_ptr (passphrase); - - init(passphrase, length); - } - - ~HMACEngine() - { - memset(_ipad, 0, BLOCK_SIZE); - memset(_opad, 0, BLOCK_SIZE); - delete [] _ipad; - delete [] _opad; - } - - unsigned digestLength() const - { - return DIGEST_SIZE; - } - - void reset() - { - _engine.reset(); - _engine.update(_ipad, BLOCK_SIZE); - } - - const DigestEngine::Digest& digest() - { - const DigestEngine::Digest& d = _engine.digest(); - char db[DIGEST_SIZE]; - char* pdb = db; - for (DigestEngine::Digest::const_iterator it = d.begin(); it != d.end(); ++it) - *pdb++ = *it; - _engine.reset(); - _engine.update(_opad, BLOCK_SIZE); - _engine.update(db, DIGEST_SIZE); - const DigestEngine::Digest& result = _engine.digest(); - reset(); - return result; - } - -protected: - void init(const char* passphrase, unsigned length) - { - _ipad = new char[BLOCK_SIZE]; - _opad = new char[BLOCK_SIZE]; - memset(_ipad, 0, BLOCK_SIZE); - memset(_opad, 0, BLOCK_SIZE); - if (length > BLOCK_SIZE) - { - _engine.reset(); - _engine.update(passphrase, length); - const DigestEngine::Digest& d = _engine.digest(); - char* ipad = _ipad; - char* opad = _opad; - int n = BLOCK_SIZE; - for (DigestEngine::Digest::const_iterator it = d.begin(); it != d.end() && n-- > 0; ++it) - { - *ipad++ = *it; - *opad++ = *it; - } - } - else - { - memcpy(_ipad, passphrase, length); - memcpy(_opad, passphrase, length); - } - for (int i = 0; i < BLOCK_SIZE; ++i) - { - _ipad[i] ^= 0x36; - _opad[i] ^= 0x5c; - } - reset(); - } - - void updateImpl(const void* data, unsigned length) - { - _engine.update(data, length); - } - -private: - HMACEngine(); - - Engine _engine; - char* _ipad; - char* _opad; -}; - - -} // namespace Poco - - -#endif // Foundation_HMACEngine_INCLUDED +// +// HMACEngine.h +// +// $Id: //poco/1.2/Foundation/include/Poco/HMACEngine.h#1 $ +// +// Library: Foundation +// Package: Crypt +// Module: HMACEngine +// +// Definition of the HMACEngine class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_HMACEngine_INCLUDED +#define Foundation_HMACEngine_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/DigestEngine.h" +#include + + +namespace Poco { + + +template +class HMACEngine: public DigestEngine + /// This class implementes the HMAC message + /// authentication code algorithm, as specified + /// in RFC 2104. The underlying DigestEngine + /// (MD5Engine, SHA1Engine, etc.) must be given as + /// template argument. + /// Since the HMACEngine is a DigestEngine, it can + /// be used with the DigestStream class to create + /// a HMAC for a stream. +{ +public: + enum + { + BLOCK_SIZE = Engine::BLOCK_SIZE, + DIGEST_SIZE = Engine::DIGEST_SIZE + }; + + HMACEngine(const std::string& passphrase) + { + init(passphrase.data(), (unsigned) passphrase.length()); + } + + HMACEngine(const char* passphrase, unsigned length) + { + poco_check_ptr (passphrase); + + init(passphrase, length); + } + + ~HMACEngine() + { + memset(_ipad, 0, BLOCK_SIZE); + memset(_opad, 0, BLOCK_SIZE); + delete [] _ipad; + delete [] _opad; + } + + unsigned digestLength() const + { + return DIGEST_SIZE; + } + + void reset() + { + _engine.reset(); + _engine.update(_ipad, BLOCK_SIZE); + } + + const DigestEngine::Digest& digest() + { + const DigestEngine::Digest& d = _engine.digest(); + char db[DIGEST_SIZE]; + char* pdb = db; + for (DigestEngine::Digest::const_iterator it = d.begin(); it != d.end(); ++it) + *pdb++ = *it; + _engine.reset(); + _engine.update(_opad, BLOCK_SIZE); + _engine.update(db, DIGEST_SIZE); + const DigestEngine::Digest& result = _engine.digest(); + reset(); + return result; + } + +protected: + void init(const char* passphrase, unsigned length) + { + _ipad = new char[BLOCK_SIZE]; + _opad = new char[BLOCK_SIZE]; + memset(_ipad, 0, BLOCK_SIZE); + memset(_opad, 0, BLOCK_SIZE); + if (length > BLOCK_SIZE) + { + _engine.reset(); + _engine.update(passphrase, length); + const DigestEngine::Digest& d = _engine.digest(); + char* ipad = _ipad; + char* opad = _opad; + int n = BLOCK_SIZE; + for (DigestEngine::Digest::const_iterator it = d.begin(); it != d.end() && n-- > 0; ++it) + { + *ipad++ = *it; + *opad++ = *it; + } + } + else + { + memcpy(_ipad, passphrase, length); + memcpy(_opad, passphrase, length); + } + for (int i = 0; i < BLOCK_SIZE; ++i) + { + _ipad[i] ^= 0x36; + _opad[i] ^= 0x5c; + } + reset(); + } + + void updateImpl(const void* data, unsigned length) + { + _engine.update(data, length); + } + +private: + HMACEngine(); + + Engine _engine; + char* _ipad; + char* _opad; +}; + + +} // namespace Poco + + +#endif // Foundation_HMACEngine_INCLUDED diff --git a/Foundation/include/Poco/HashFunction.h b/Foundation/include/Poco/HashFunction.h index ea913423a..820b3aa83 100644 --- a/Foundation/include/Poco/HashFunction.h +++ b/Foundation/include/Poco/HashFunction.h @@ -1,82 +1,82 @@ -// -// HashFunction.h -// -// $Id: //poco/1.2/Foundation/include/Poco/HashFunction.h#1 $ -// -// Library: Foundation -// Package: Core -// Module: HashFunction -// -// Definition of the HashFunction class. -// -// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_HashFunction_INCLUDED -#define Foundation_HashFunction_INCLUDED - - -#include "Poco/Foundation.h" - - -namespace Poco { - -template -struct HashFunction - /// A generic hash function for numeric values. -{ - static UInt32 hash(T key, UInt32 maxValue) - /// Returns the hash value for the given key - { - return key * 0xf4243 % maxValue; - } -}; - - -template <> -struct HashFunction - /// A specialization of HashFunction for strings. -{ - static UInt32 hash(const std::string& key, UInt32 maxValue) - { - // hash function taken from XML expat - UInt32 h = 0; - - for (int i = 0; i < key.length(); ++i) - { - h = h * 0xf4243 ^ key[i]; - } - - return h % maxValue; - } -}; - - -} // namespace Poco - - -#endif // Foundation_HashFunctions_INCLUDED +// +// HashFunction.h +// +// $Id: //poco/1.2/Foundation/include/Poco/HashFunction.h#1 $ +// +// Library: Foundation +// Package: Core +// Module: HashFunction +// +// Definition of the HashFunction class. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_HashFunction_INCLUDED +#define Foundation_HashFunction_INCLUDED + + +#include "Poco/Foundation.h" + + +namespace Poco { + +template +struct HashFunction + /// A generic hash function for numeric values. +{ + static UInt32 hash(T key, UInt32 maxValue) + /// Returns the hash value for the given key + { + return key * 0xf4243 % maxValue; + } +}; + + +template <> +struct HashFunction + /// A specialization of HashFunction for strings. +{ + static UInt32 hash(const std::string& key, UInt32 maxValue) + { + // hash function taken from XML expat + UInt32 h = 0; + + for (int i = 0; i < key.length(); ++i) + { + h = h * 0xf4243 ^ key[i]; + } + + return h % maxValue; + } +}; + + +} // namespace Poco + + +#endif // Foundation_HashFunctions_INCLUDED diff --git a/Foundation/include/Poco/HashStatistic.h b/Foundation/include/Poco/HashStatistic.h index 4380c6ea7..ad90bd4f8 100644 --- a/Foundation/include/Poco/HashStatistic.h +++ b/Foundation/include/Poco/HashStatistic.h @@ -1,147 +1,147 @@ -// -// HashStatistic.h -// -// $Id: //poco/1.2/Foundation/include/Poco/HashStatistic.h#1 $ -// -// Library: Foundation -// Package: Core -// Module: HashStatistic -// -// Definition of the HashStatistic class. -// -// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_HashStatistic_INCLUDED -#define Foundation_HashStatistic_INCLUDED - - -#include "Poco/Foundation.h" -#include - - -namespace Poco { - - -class Foundation_API HashStatistic - /// HashStatistic class bundles statistical information on the current state of a HashTable -{ -public: - HashStatistic( - UInt32 tableSize, - UInt32 numEntries, - UInt32 numZeroEntries, - UInt32 maxEntry, - std::vector details = std::vector()); - /// Creates the HashStatistic. - - virtual ~HashStatistic(); - /// Destroys the HashStatistic. - - UInt32 maxPositionsOfTable() const; - /// Returns the maximum number of different hash values possible for the table - - UInt32 numberOfEntries() const; - /// Returns the total number of entries currently stored in the HashTable - - UInt32 numberOfZeroPositions() const; - /// Returns the number of hash positions that contain no entry. - - double avgEntriesPerHash() const; - /// Returns the average number of entries per position in the Hashtable, the higher this value the less efficient - /// performs hashing. If a large value is returned and getNumberOfZeroPositions also returns a large value, this - /// indicates an inefficient hashing function. If the number of zero entries is low, resizing the HashTable, should - /// be enough to improve performance - - double avgEntriesPerHashExclZeroEntries() const; - /// Same as getAvgEntriesPerHash but hash values that contain no entry are ignored, - /// getAvgEntriesPerHashExclZeroEntries >= getAvgEntriesPerHash will always be true. - - UInt32 maxEntriesPerHash() const; - /// Returns the maximum number of entries per hash value found in the current table. - - const std::vector detailedEntriesPerHash() const; - /// Will either be an empty vector or will contain for each possible hash value, the number of entries currently stored - - std::string toString() const; - /// Converts the whole data structure into a string. - -private: - UInt32 _sizeOfTable; - UInt32 _numberOfEntries; - UInt32 _numZeroEntries; - UInt32 _maxEntriesPerHash; - std::vector _detailedEntriesPerHash; -}; - - -inline UInt32 HashStatistic::maxPositionsOfTable() const -{ - return _sizeOfTable; -} - - -inline UInt32 HashStatistic::numberOfEntries() const -{ - return _numberOfEntries; -} - - -inline UInt32 HashStatistic::numberOfZeroPositions() const -{ - return _numZeroEntries; -} - - -inline double HashStatistic::avgEntriesPerHash() const -{ - return ((double) numberOfEntries()) / maxPositionsOfTable(); -} - - -inline double HashStatistic::avgEntriesPerHashExclZeroEntries() const -{ - return ((double) numberOfEntries()) / (maxPositionsOfTable() - numberOfZeroPositions()); -} - - -inline UInt32 HashStatistic::maxEntriesPerHash() const -{ - return _maxEntriesPerHash; -} - - -inline const std::vector HashStatistic::detailedEntriesPerHash() const -{ - return _detailedEntriesPerHash; -} - - -} // namespace Poco - - -#endif // Foundation_HashStatistic_INCLUDED +// +// HashStatistic.h +// +// $Id: //poco/1.2/Foundation/include/Poco/HashStatistic.h#1 $ +// +// Library: Foundation +// Package: Core +// Module: HashStatistic +// +// Definition of the HashStatistic class. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_HashStatistic_INCLUDED +#define Foundation_HashStatistic_INCLUDED + + +#include "Poco/Foundation.h" +#include + + +namespace Poco { + + +class Foundation_API HashStatistic + /// HashStatistic class bundles statistical information on the current state of a HashTable +{ +public: + HashStatistic( + UInt32 tableSize, + UInt32 numEntries, + UInt32 numZeroEntries, + UInt32 maxEntry, + std::vector details = std::vector()); + /// Creates the HashStatistic. + + virtual ~HashStatistic(); + /// Destroys the HashStatistic. + + UInt32 maxPositionsOfTable() const; + /// Returns the maximum number of different hash values possible for the table + + UInt32 numberOfEntries() const; + /// Returns the total number of entries currently stored in the HashTable + + UInt32 numberOfZeroPositions() const; + /// Returns the number of hash positions that contain no entry. + + double avgEntriesPerHash() const; + /// Returns the average number of entries per position in the Hashtable, the higher this value the less efficient + /// performs hashing. If a large value is returned and getNumberOfZeroPositions also returns a large value, this + /// indicates an inefficient hashing function. If the number of zero entries is low, resizing the HashTable, should + /// be enough to improve performance + + double avgEntriesPerHashExclZeroEntries() const; + /// Same as getAvgEntriesPerHash but hash values that contain no entry are ignored, + /// getAvgEntriesPerHashExclZeroEntries >= getAvgEntriesPerHash will always be true. + + UInt32 maxEntriesPerHash() const; + /// Returns the maximum number of entries per hash value found in the current table. + + const std::vector detailedEntriesPerHash() const; + /// Will either be an empty vector or will contain for each possible hash value, the number of entries currently stored + + std::string toString() const; + /// Converts the whole data structure into a string. + +private: + UInt32 _sizeOfTable; + UInt32 _numberOfEntries; + UInt32 _numZeroEntries; + UInt32 _maxEntriesPerHash; + std::vector _detailedEntriesPerHash; +}; + + +inline UInt32 HashStatistic::maxPositionsOfTable() const +{ + return _sizeOfTable; +} + + +inline UInt32 HashStatistic::numberOfEntries() const +{ + return _numberOfEntries; +} + + +inline UInt32 HashStatistic::numberOfZeroPositions() const +{ + return _numZeroEntries; +} + + +inline double HashStatistic::avgEntriesPerHash() const +{ + return ((double) numberOfEntries()) / maxPositionsOfTable(); +} + + +inline double HashStatistic::avgEntriesPerHashExclZeroEntries() const +{ + return ((double) numberOfEntries()) / (maxPositionsOfTable() - numberOfZeroPositions()); +} + + +inline UInt32 HashStatistic::maxEntriesPerHash() const +{ + return _maxEntriesPerHash; +} + + +inline const std::vector HashStatistic::detailedEntriesPerHash() const +{ + return _detailedEntriesPerHash; +} + + +} // namespace Poco + + +#endif // Foundation_HashStatistic_INCLUDED diff --git a/Foundation/include/Poco/HashTable.h b/Foundation/include/Poco/HashTable.h index d99e28419..f9c007b2e 100644 --- a/Foundation/include/Poco/HashTable.h +++ b/Foundation/include/Poco/HashTable.h @@ -1,362 +1,362 @@ -// -// HashTable.h -// -// $Id: //poco/1.2/Foundation/include/Poco/HashTable.h#2 $ -// -// Library: Foundation -// Package: Core -// Module: HashTable -// -// Definition of the HashTable class. -// -// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_HashTable_INCLUDED -#define Foundation_HashTable_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/Exception.h" -#include "Poco/HashFunction.h" -#include "Poco/HashStatistic.h" -#include -#include -#include - - -namespace Poco { - - -template > -class HashTable - /// A HashTable stores a key value pair that can be looked up via a hashed key. - /// - /// Collision handling is done via overflow maps(!). With small hash tables performance of this - /// data struct will be closer to that a map than a hash table, i.e. slower. On the plus side, - /// this class offers remove operations. Also HashTable full errors are not possible. If a fast - /// HashTable implementation is needed and the remove operation is not required, use SimpleHashTable - /// instead. - /// - /// This class is NOT thread safe. -{ -public: - typedef std::map HashEntryMap; - typedef HashEntryMap** HashTableVector; - - typedef typename HashEntryMap::const_iterator ConstIterator; - typedef typename HashEntryMap::iterator Iterator; - - HashTable(UInt32 initialSize = 251): - _entries(0), - _size(0), - _maxCapacity(initialSize) - /// Creates the HashTable. - { - _entries = new HashEntryMap*[initialSize]; - memset(_entries, '\0', sizeof(HashEntryMap*)*initialSize); - } - - HashTable(const HashTable& ht): - _entries(new HashEntryMap*[ht._maxCapacity]), - _size(ht._size), - _maxCapacity(ht._maxCapacity) - { - for (int i = 0; i < _maxCapacity; ++i) - { - if (ht._entries[i]) - _entries[i] = new HashEntryMap(ht._entries[i]->begin(), ht._entries[i]->end()); - else - _entries[i] = 0; - } - } - - ~HashTable() - /// Destroys the HashTable. - { - clear(); - } - - HashTable& operator = (const HashTable& ht) - { - if (this != &ht) - { - clear(); - _maxCapacity = ht._maxCapacity; - poco_assert_dbg (_entries == 0); - _entries = new HashEntryMap*[_maxCapacity]; - _size = ht._size; - - for (int i = 0; i < _maxCapacity; ++i) - { - if (ht._entries[i]) - _entries[i] = new HashEntryMap(ht._entries[i]->begin(), ht._entries[i]->end()); - else - _entries[i] = 0; - } - } - return *this; - } - - void clear() - { - if (!_entries) - return; - for (int i = 0; i < _maxCapacity; ++i) - { - if (_entries[i]) - delete _entries[i]; - } - delete[] _entries; - _entries = 0; - _size = 0; - _maxCapacity = 0; - } - - UInt32 insert(const Key& key, const Value& value) - /// Returns the hash value of the inserted item. - /// Throws an exception if the entry was already inserted - { - UInt32 hsh = hash(key); - insertRaw(key, hsh, value); - return hsh; - } - - void insertRaw(const Key& key, UInt32 hsh, const Value& value) - /// Returns the hash value of the inserted item. - /// Throws an exception if the entry was already inserted - { - if (!_entries[hsh]) - _entries[hsh] = new HashEntryMap(); - if (!_entries[hsh]->insert(std::make_pair(key, value)).second) - throw InvalidArgumentException("HashTable::insert, key already exists."); - _size++; - } - - UInt32 update(const Key& key, const Value& value) - /// Returns the hash value of the inserted item. - /// Replaces an existing entry if it finds one - { - UInt32 hsh = hash(key); - updateRaw(key, hsh, value); - return hsh; - } - - void updateRaw(const Key& key, UInt32 hsh, const Value& value) - /// Returns the hash value of the inserted item. - /// Replaces an existing entry if it finds one - { - if (!_entries[hsh]) - _entries[hsh] = new HashEntryMap(); - std::pair res = _entries[hsh]->insert(make_pair(key, value)); - if (res.second == false) - res.first->second = value; - else - _size++; - } - - void remove(const Key& key) - { - UInt32 hsh = hash(key); - removeRaw(key, hsh); - } - - void removeRaw(const Key& key, UInt32 hsh) - /// Performance version, allows to specify the hash value - { - if (_entries[hsh]) - { - _size -= _entries[hsh]->erase(key); - } - } - - UInt32 hash(const Key& key) const - { - return KeyHashFunction::hash(key, _maxCapacity); - } - - const Value& get(const Key& key) const - /// Throws an exception if the value does not exist - { - UInt32 hsh = hash(key); - return getRaw(key, hsh); - } - - const Value& getRaw(const Key& key, UInt32 hsh) const - /// Throws an exception if the value does not exist - { - if (!_entries[hsh]) - throw InvalidArgumentException("key not found"); - - ConstIterator it = _entries[hsh]->find(key); - if (it == _entries[hsh]->end()) - throw InvalidArgumentException("key not found"); - - return it->second; - } - - const Key& getKeyRaw(const Key& key, UInt32 hsh) - /// Throws an exception if the key does not exist. returns a reference to the internally - /// stored key. Useful when someone does an insert and wants for performance reason only to store - /// a pointer to the key in another collection - { - if (!_entries[hsh]) - throw InvalidArgumentException("key not found"); - ConstIterator it = _entries[hsh]->find(key); - if (it == _entries[hsh]->end()) - throw InvalidArgumentException("key not found"); - return it->first; - } - - bool get(const Key& key, Value& v) const - /// Sets v to the found value, returns false if no value was found - { - UInt32 hsh = hash(key); - return getRaw(key, hsh, v); - } - - bool getRaw(const Key& key, UInt32 hsh, Value& v) const - /// Sets v to the found value, returns false if no value was found - { - if (!_entries[hsh]) - return false; - - ConstIterator it = _entries[hsh]->find(key); - if (it == _entries[hsh]->end()) - return false; - - v = it->second; - return true; - } - - bool exists(const Key& key) - { - UInt32 hsh = hash(key); - return existsRaw(key, hsh); - } - - bool existsRaw(const Key& key, UInt32 hsh) - { - return _entries[hsh] && (_entries[hsh]->end() != _entries[hsh]->find(key)); - } - - - size_t size() const - /// Returns the number of elements already inserted into the HashTable - { - return _size; - } - - UInt32 maxCapacity() const - { - return _maxCapacity; - } - - void resize(UInt32 newSize) - /// Resizes the hashtable, rehashes all existing entries. Expensive! - { - if (_maxCapacity != newSize) - { - HashTableVector cpy = _entries; - _entries = 0; - UInt32 oldSize = _maxCapacity; - _maxCapacity = newSize; - _entries = new HashEntryMap*[_maxCapacity]; - memset(_entries, '\0', sizeof(HashEntryMap*)*_maxCapacity); - - if (_size == 0) - { - // no data was yet inserted - delete[] cpy; - return; - } - _size = 0; - for (int i=0; i < oldSize; ++i) - { - if (cpy[i]) - { - ConstIterator it = cpy[i]->begin(); - ConstIterator itEnd = cpy[i]->end(); - for (; it != itEnd; ++it) - { - insert(it->first, it->second); - } - delete cpy[i]; - } - } - delete[] cpy; - } - } - - HashStatistic currentState(bool details = false) const - /// Returns the current internal state - { - UInt32 numberOfEntries = (UInt32)_size; - UInt32 numZeroEntries = 0; - UInt32 maxEntriesPerHash = 0; - std::vector detailedEntriesPerHash; - #ifdef DEBUG - UInt32 totalSize = 0; - #endif - for (int i=0; i < _maxCapacity; ++i) - { - if (_entries[i]) - { - UInt32 size = (UInt32)_entries[i]->size(); - poco_assert_dbg(size != 0); - if (size > maxEntriesPerHash) - maxEntriesPerHash = size; - if (details) - detailedEntriesPerHash.push_back(size); - #ifdef DEBUG - totalSize += size; - #endif - } - else - { - numZeroEntries++; - if (details) - detailedEntriesPerHash.push_back(0); - } - } - #ifdef DEBUG - poco_assert_dbg(totalSize == numberOfEntries); - #endif - return HashStatistic(_maxCapacity, numberOfEntries, numZeroEntries, maxEntriesPerHash, detailedEntriesPerHash); - } - -private: - HashTableVector _entries; - size_t _size; - UInt32 _maxCapacity; -}; - - -} // namespace Poco - - -#endif // Foundation_HashTable_INCLUDED +// +// HashTable.h +// +// $Id: //poco/1.2/Foundation/include/Poco/HashTable.h#2 $ +// +// Library: Foundation +// Package: Core +// Module: HashTable +// +// Definition of the HashTable class. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_HashTable_INCLUDED +#define Foundation_HashTable_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Exception.h" +#include "Poco/HashFunction.h" +#include "Poco/HashStatistic.h" +#include +#include +#include + + +namespace Poco { + + +template > +class HashTable + /// A HashTable stores a key value pair that can be looked up via a hashed key. + /// + /// Collision handling is done via overflow maps(!). With small hash tables performance of this + /// data struct will be closer to that a map than a hash table, i.e. slower. On the plus side, + /// this class offers remove operations. Also HashTable full errors are not possible. If a fast + /// HashTable implementation is needed and the remove operation is not required, use SimpleHashTable + /// instead. + /// + /// This class is NOT thread safe. +{ +public: + typedef std::map HashEntryMap; + typedef HashEntryMap** HashTableVector; + + typedef typename HashEntryMap::const_iterator ConstIterator; + typedef typename HashEntryMap::iterator Iterator; + + HashTable(UInt32 initialSize = 251): + _entries(0), + _size(0), + _maxCapacity(initialSize) + /// Creates the HashTable. + { + _entries = new HashEntryMap*[initialSize]; + memset(_entries, '\0', sizeof(HashEntryMap*)*initialSize); + } + + HashTable(const HashTable& ht): + _entries(new HashEntryMap*[ht._maxCapacity]), + _size(ht._size), + _maxCapacity(ht._maxCapacity) + { + for (int i = 0; i < _maxCapacity; ++i) + { + if (ht._entries[i]) + _entries[i] = new HashEntryMap(ht._entries[i]->begin(), ht._entries[i]->end()); + else + _entries[i] = 0; + } + } + + ~HashTable() + /// Destroys the HashTable. + { + clear(); + } + + HashTable& operator = (const HashTable& ht) + { + if (this != &ht) + { + clear(); + _maxCapacity = ht._maxCapacity; + poco_assert_dbg (_entries == 0); + _entries = new HashEntryMap*[_maxCapacity]; + _size = ht._size; + + for (int i = 0; i < _maxCapacity; ++i) + { + if (ht._entries[i]) + _entries[i] = new HashEntryMap(ht._entries[i]->begin(), ht._entries[i]->end()); + else + _entries[i] = 0; + } + } + return *this; + } + + void clear() + { + if (!_entries) + return; + for (int i = 0; i < _maxCapacity; ++i) + { + if (_entries[i]) + delete _entries[i]; + } + delete[] _entries; + _entries = 0; + _size = 0; + _maxCapacity = 0; + } + + UInt32 insert(const Key& key, const Value& value) + /// Returns the hash value of the inserted item. + /// Throws an exception if the entry was already inserted + { + UInt32 hsh = hash(key); + insertRaw(key, hsh, value); + return hsh; + } + + void insertRaw(const Key& key, UInt32 hsh, const Value& value) + /// Returns the hash value of the inserted item. + /// Throws an exception if the entry was already inserted + { + if (!_entries[hsh]) + _entries[hsh] = new HashEntryMap(); + if (!_entries[hsh]->insert(std::make_pair(key, value)).second) + throw InvalidArgumentException("HashTable::insert, key already exists."); + _size++; + } + + UInt32 update(const Key& key, const Value& value) + /// Returns the hash value of the inserted item. + /// Replaces an existing entry if it finds one + { + UInt32 hsh = hash(key); + updateRaw(key, hsh, value); + return hsh; + } + + void updateRaw(const Key& key, UInt32 hsh, const Value& value) + /// Returns the hash value of the inserted item. + /// Replaces an existing entry if it finds one + { + if (!_entries[hsh]) + _entries[hsh] = new HashEntryMap(); + std::pair res = _entries[hsh]->insert(make_pair(key, value)); + if (res.second == false) + res.first->second = value; + else + _size++; + } + + void remove(const Key& key) + { + UInt32 hsh = hash(key); + removeRaw(key, hsh); + } + + void removeRaw(const Key& key, UInt32 hsh) + /// Performance version, allows to specify the hash value + { + if (_entries[hsh]) + { + _size -= _entries[hsh]->erase(key); + } + } + + UInt32 hash(const Key& key) const + { + return KeyHashFunction::hash(key, _maxCapacity); + } + + const Value& get(const Key& key) const + /// Throws an exception if the value does not exist + { + UInt32 hsh = hash(key); + return getRaw(key, hsh); + } + + const Value& getRaw(const Key& key, UInt32 hsh) const + /// Throws an exception if the value does not exist + { + if (!_entries[hsh]) + throw InvalidArgumentException("key not found"); + + ConstIterator it = _entries[hsh]->find(key); + if (it == _entries[hsh]->end()) + throw InvalidArgumentException("key not found"); + + return it->second; + } + + const Key& getKeyRaw(const Key& key, UInt32 hsh) + /// Throws an exception if the key does not exist. returns a reference to the internally + /// stored key. Useful when someone does an insert and wants for performance reason only to store + /// a pointer to the key in another collection + { + if (!_entries[hsh]) + throw InvalidArgumentException("key not found"); + ConstIterator it = _entries[hsh]->find(key); + if (it == _entries[hsh]->end()) + throw InvalidArgumentException("key not found"); + return it->first; + } + + bool get(const Key& key, Value& v) const + /// Sets v to the found value, returns false if no value was found + { + UInt32 hsh = hash(key); + return getRaw(key, hsh, v); + } + + bool getRaw(const Key& key, UInt32 hsh, Value& v) const + /// Sets v to the found value, returns false if no value was found + { + if (!_entries[hsh]) + return false; + + ConstIterator it = _entries[hsh]->find(key); + if (it == _entries[hsh]->end()) + return false; + + v = it->second; + return true; + } + + bool exists(const Key& key) + { + UInt32 hsh = hash(key); + return existsRaw(key, hsh); + } + + bool existsRaw(const Key& key, UInt32 hsh) + { + return _entries[hsh] && (_entries[hsh]->end() != _entries[hsh]->find(key)); + } + + + size_t size() const + /// Returns the number of elements already inserted into the HashTable + { + return _size; + } + + UInt32 maxCapacity() const + { + return _maxCapacity; + } + + void resize(UInt32 newSize) + /// Resizes the hashtable, rehashes all existing entries. Expensive! + { + if (_maxCapacity != newSize) + { + HashTableVector cpy = _entries; + _entries = 0; + UInt32 oldSize = _maxCapacity; + _maxCapacity = newSize; + _entries = new HashEntryMap*[_maxCapacity]; + memset(_entries, '\0', sizeof(HashEntryMap*)*_maxCapacity); + + if (_size == 0) + { + // no data was yet inserted + delete[] cpy; + return; + } + _size = 0; + for (int i=0; i < oldSize; ++i) + { + if (cpy[i]) + { + ConstIterator it = cpy[i]->begin(); + ConstIterator itEnd = cpy[i]->end(); + for (; it != itEnd; ++it) + { + insert(it->first, it->second); + } + delete cpy[i]; + } + } + delete[] cpy; + } + } + + HashStatistic currentState(bool details = false) const + /// Returns the current internal state + { + UInt32 numberOfEntries = (UInt32)_size; + UInt32 numZeroEntries = 0; + UInt32 maxEntriesPerHash = 0; + std::vector detailedEntriesPerHash; + #ifdef DEBUG + UInt32 totalSize = 0; + #endif + for (int i=0; i < _maxCapacity; ++i) + { + if (_entries[i]) + { + UInt32 size = (UInt32)_entries[i]->size(); + poco_assert_dbg(size != 0); + if (size > maxEntriesPerHash) + maxEntriesPerHash = size; + if (details) + detailedEntriesPerHash.push_back(size); + #ifdef DEBUG + totalSize += size; + #endif + } + else + { + numZeroEntries++; + if (details) + detailedEntriesPerHash.push_back(0); + } + } + #ifdef DEBUG + poco_assert_dbg(totalSize == numberOfEntries); + #endif + return HashStatistic(_maxCapacity, numberOfEntries, numZeroEntries, maxEntriesPerHash, detailedEntriesPerHash); + } + +private: + HashTableVector _entries; + size_t _size; + UInt32 _maxCapacity; +}; + + +} // namespace Poco + + +#endif // Foundation_HashTable_INCLUDED diff --git a/Foundation/include/Poco/HexBinaryDecoder.h b/Foundation/include/Poco/HexBinaryDecoder.h index dc8d69b42..9f22ed0c9 100644 --- a/Foundation/include/Poco/HexBinaryDecoder.h +++ b/Foundation/include/Poco/HexBinaryDecoder.h @@ -1,104 +1,104 @@ -// -// HexBinaryDecoder.h -// -// $Id: //poco/1.2/Foundation/include/Poco/HexBinaryDecoder.h#1 $ -// -// Library: Foundation -// Package: Streams -// Module: HexBinary -// -// Definition of the HexBinaryDecoder class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_HexBinaryDecoder_INCLUDED -#define Foundation_HexBinaryDecoder_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/UnbufferedStreamBuf.h" -#include - - -namespace Poco { - - -class Foundation_API HexBinaryDecoderBuf: public UnbufferedStreamBuf - /// This streambuf decodes all hexBinary-encoded data read - /// from the istream connected to it. - /// In hexBinary encoding, each binary octet is encoded as a character tuple, - /// consisting of two hexadecimal digits ([0-9a-fA-F]) representing the octet code. - /// See also: XML Schema Part 2: Datatypes (http://www.w3.org/TR/xmlschema-2/), - /// section 3.2.15. -{ -public: - HexBinaryDecoderBuf(std::istream& istr); - ~HexBinaryDecoderBuf(); - -private: - int readFromDevice(); - int readOne(); - - std::istream& _istr; -}; - - -class Foundation_API HexBinaryDecoderIOS: public virtual std::ios - /// The base class for HexBinaryDecoder. - /// - /// This class is needed to ensure the correct initialization - /// order of the stream buffer and base classes. -{ -public: - HexBinaryDecoderIOS(std::istream& istr); - ~HexBinaryDecoderIOS(); - HexBinaryDecoderBuf* rdbuf(); - -protected: - HexBinaryDecoderBuf _buf; -}; - - -class Foundation_API HexBinaryDecoder: public HexBinaryDecoderIOS, public std::istream - /// This istream decodes all hexBinary-encoded data read - /// from the istream connected to it. - /// In hexBinary encoding, each binary octet is encoded as a character tuple, - /// consisting of two hexadecimal digits ([0-9a-fA-F]) representing the octet code. - /// See also: XML Schema Part 2: Datatypes (http://www.w3.org/TR/xmlschema-2/), - /// section 3.2.15. -{ -public: - HexBinaryDecoder(std::istream& istr); - ~HexBinaryDecoder(); -}; - - -} // namespace Poco - - -#endif // Foundation_HexBinaryDecoder_INCLUDED +// +// HexBinaryDecoder.h +// +// $Id: //poco/1.2/Foundation/include/Poco/HexBinaryDecoder.h#1 $ +// +// Library: Foundation +// Package: Streams +// Module: HexBinary +// +// Definition of the HexBinaryDecoder class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_HexBinaryDecoder_INCLUDED +#define Foundation_HexBinaryDecoder_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/UnbufferedStreamBuf.h" +#include + + +namespace Poco { + + +class Foundation_API HexBinaryDecoderBuf: public UnbufferedStreamBuf + /// This streambuf decodes all hexBinary-encoded data read + /// from the istream connected to it. + /// In hexBinary encoding, each binary octet is encoded as a character tuple, + /// consisting of two hexadecimal digits ([0-9a-fA-F]) representing the octet code. + /// See also: XML Schema Part 2: Datatypes (http://www.w3.org/TR/xmlschema-2/), + /// section 3.2.15. +{ +public: + HexBinaryDecoderBuf(std::istream& istr); + ~HexBinaryDecoderBuf(); + +private: + int readFromDevice(); + int readOne(); + + std::istream& _istr; +}; + + +class Foundation_API HexBinaryDecoderIOS: public virtual std::ios + /// The base class for HexBinaryDecoder. + /// + /// This class is needed to ensure the correct initialization + /// order of the stream buffer and base classes. +{ +public: + HexBinaryDecoderIOS(std::istream& istr); + ~HexBinaryDecoderIOS(); + HexBinaryDecoderBuf* rdbuf(); + +protected: + HexBinaryDecoderBuf _buf; +}; + + +class Foundation_API HexBinaryDecoder: public HexBinaryDecoderIOS, public std::istream + /// This istream decodes all hexBinary-encoded data read + /// from the istream connected to it. + /// In hexBinary encoding, each binary octet is encoded as a character tuple, + /// consisting of two hexadecimal digits ([0-9a-fA-F]) representing the octet code. + /// See also: XML Schema Part 2: Datatypes (http://www.w3.org/TR/xmlschema-2/), + /// section 3.2.15. +{ +public: + HexBinaryDecoder(std::istream& istr); + ~HexBinaryDecoder(); +}; + + +} // namespace Poco + + +#endif // Foundation_HexBinaryDecoder_INCLUDED diff --git a/Foundation/include/Poco/HexBinaryEncoder.h b/Foundation/include/Poco/HexBinaryEncoder.h index 4a1bb146c..3aa02c071 100644 --- a/Foundation/include/Poco/HexBinaryEncoder.h +++ b/Foundation/include/Poco/HexBinaryEncoder.h @@ -1,117 +1,117 @@ -// -// HexBinaryEncoder.h -// -// $Id: //poco/1.2/Foundation/include/Poco/HexBinaryEncoder.h#1 $ -// -// Library: Foundation -// Package: Streams -// Module: HexBinary -// -// Definition of the HexBinaryEncoder class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_HexBinaryEncoder_INCLUDED -#define Foundation_HexBinaryEncoder_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/UnbufferedStreamBuf.h" -#include - - -namespace Poco { - - -class Foundation_API HexBinaryEncoderBuf: public UnbufferedStreamBuf - /// This streambuf encodes all data written - /// to it in hexBinary encoding and forwards it to a connected - /// ostream. - /// In hexBinary encoding, each binary octet is encoded as a character tuple, - /// consisting of two hexadecimal digits ([0-9a-fA-F]) representing the octet code. - /// See also: XML Schema Part 2: Datatypes (http://www.w3.org/TR/xmlschema-2/), - /// section 3.2.15. -{ -public: - HexBinaryEncoderBuf(std::ostream& ostr); - ~HexBinaryEncoderBuf(); - int close(); - - void setLineLength(int lineLength); - int getLineLength() const; - void setUppercase(bool flag = true); - -private: - int writeToDevice(char c); - - int _pos; - int _lineLength; - int _uppercase; - std::ostream& _ostr; -}; - - -class Foundation_API HexBinaryEncoderIOS: public virtual std::ios - /// The base class for HexBinaryEncoder. - /// - /// This class is needed to ensure the correct initialization - /// order of the stream buffer and base classes. -{ -public: - HexBinaryEncoderIOS(std::ostream& ostr); - ~HexBinaryEncoderIOS(); - int close(); - HexBinaryEncoderBuf* rdbuf(); - -protected: - HexBinaryEncoderBuf _buf; -}; - - -class Foundation_API HexBinaryEncoder: public HexBinaryEncoderIOS, public std::ostream - /// This ostream encodes all data - /// written to it in BinHex encoding and forwards it to - /// a connected ostream. - /// Always call close() when done - /// writing data, to ensure proper - /// completion of the encoding operation. - /// In hexBinary encoding, each binary octet is encoded as a character tuple, - /// consisting of two hexadecimal digits ([0-9a-fA-F]) representing the octet code. - /// See also: XML Schema Part 2: Datatypes (http://www.w3.org/TR/xmlschema-2/), - /// section 3.2.15. -{ -public: - HexBinaryEncoder(std::ostream& ostr); - ~HexBinaryEncoder(); -}; - - -} // namespace Poco - - -#endif // Foundation_HexBinaryEncoder_INCLUDED +// +// HexBinaryEncoder.h +// +// $Id: //poco/1.2/Foundation/include/Poco/HexBinaryEncoder.h#1 $ +// +// Library: Foundation +// Package: Streams +// Module: HexBinary +// +// Definition of the HexBinaryEncoder class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_HexBinaryEncoder_INCLUDED +#define Foundation_HexBinaryEncoder_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/UnbufferedStreamBuf.h" +#include + + +namespace Poco { + + +class Foundation_API HexBinaryEncoderBuf: public UnbufferedStreamBuf + /// This streambuf encodes all data written + /// to it in hexBinary encoding and forwards it to a connected + /// ostream. + /// In hexBinary encoding, each binary octet is encoded as a character tuple, + /// consisting of two hexadecimal digits ([0-9a-fA-F]) representing the octet code. + /// See also: XML Schema Part 2: Datatypes (http://www.w3.org/TR/xmlschema-2/), + /// section 3.2.15. +{ +public: + HexBinaryEncoderBuf(std::ostream& ostr); + ~HexBinaryEncoderBuf(); + int close(); + + void setLineLength(int lineLength); + int getLineLength() const; + void setUppercase(bool flag = true); + +private: + int writeToDevice(char c); + + int _pos; + int _lineLength; + int _uppercase; + std::ostream& _ostr; +}; + + +class Foundation_API HexBinaryEncoderIOS: public virtual std::ios + /// The base class for HexBinaryEncoder. + /// + /// This class is needed to ensure the correct initialization + /// order of the stream buffer and base classes. +{ +public: + HexBinaryEncoderIOS(std::ostream& ostr); + ~HexBinaryEncoderIOS(); + int close(); + HexBinaryEncoderBuf* rdbuf(); + +protected: + HexBinaryEncoderBuf _buf; +}; + + +class Foundation_API HexBinaryEncoder: public HexBinaryEncoderIOS, public std::ostream + /// This ostream encodes all data + /// written to it in BinHex encoding and forwards it to + /// a connected ostream. + /// Always call close() when done + /// writing data, to ensure proper + /// completion of the encoding operation. + /// In hexBinary encoding, each binary octet is encoded as a character tuple, + /// consisting of two hexadecimal digits ([0-9a-fA-F]) representing the octet code. + /// See also: XML Schema Part 2: Datatypes (http://www.w3.org/TR/xmlschema-2/), + /// section 3.2.15. +{ +public: + HexBinaryEncoder(std::ostream& ostr); + ~HexBinaryEncoder(); +}; + + +} // namespace Poco + + +#endif // Foundation_HexBinaryEncoder_INCLUDED diff --git a/Foundation/include/Poco/InflatingStream.h b/Foundation/include/Poco/InflatingStream.h index 8fadbe0e6..4bb906f6b 100644 --- a/Foundation/include/Poco/InflatingStream.h +++ b/Foundation/include/Poco/InflatingStream.h @@ -1,139 +1,139 @@ -// -// InflatingStream.h -// -// $Id: //poco/1.2/Foundation/include/Poco/InflatingStream.h#1 $ -// -// Library: Foundation -// Package: Streams -// Module: ZLibStream -// -// Definition of the InflatingInputStream and InflatingOutputStream classes. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_InflatingStream_INCLUDED -#define Foundation_InflatingStream_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/BufferedStreamBuf.h" -#include -#include -#include "Poco/zlib.h" - - -namespace Poco { - - -class Foundation_API InflatingStreamBuf: public BufferedStreamBuf - /// This is the streambuf class used by InflatingInputStream and InflatingOutputStream. - /// The actual work is delegated to zlib 1.2.1 (see http://www.gzip.org). - /// Both zlib (deflate) streams and gzip streams are supported. - /// Output streams should always call close() to ensure - /// proper completion of decompression. -{ -public: - enum StreamType - { - STREAM_ZLIB, - STREAM_GZIP - }; - - InflatingStreamBuf(std::istream& istr, StreamType type); - InflatingStreamBuf(std::ostream& ostr, StreamType type); - ~InflatingStreamBuf(); - int close(); - -protected: - int readFromDevice(char* buffer, std::streamsize length); - int writeToDevice(const char* buffer, std::streamsize length); - -private: - enum - { - STREAM_BUFFER_SIZE = 1024, - INFLATE_BUFFER_SIZE = 32768 - }; - - std::istream* _pIstr; - std::ostream* _pOstr; - char* _buffer; - z_stream _zstr; - bool _eof; -}; - - -class Foundation_API InflatingIOS: public virtual std::ios - /// The base class for InflatingOutputStream and InflatingInputStream. - /// - /// This class is needed to ensure the correct initialization - /// order of the stream buffer and base classes. -{ -public: - InflatingIOS(std::ostream& ostr, InflatingStreamBuf::StreamType type = InflatingStreamBuf::STREAM_ZLIB); - InflatingIOS(std::istream& istr, InflatingStreamBuf::StreamType type = InflatingStreamBuf::STREAM_ZLIB); - ~InflatingIOS(); - InflatingStreamBuf* rdbuf(); - -protected: - InflatingStreamBuf _buf; -}; - - -class Foundation_API InflatingOutputStream: public InflatingIOS, public std::ostream - /// This stream decompresses all data passing through it - /// using zlib's inflate algorithm. - /// After all data has been written to the stream, close() - /// must be called to ensure completion of decompression. -{ -public: - InflatingOutputStream(std::ostream& ostr, InflatingStreamBuf::StreamType type = InflatingStreamBuf::STREAM_ZLIB); - ~InflatingOutputStream(); - int close(); -}; - - -class Foundation_API InflatingInputStream: public InflatingIOS, public std::istream - /// This stream decompresses all data passing through it - /// using zlib's inflate algorithm. - /// Example: - /// std::ifstream istr("data.gz", std::ios::binary); - /// InflatingInputStream inflater(istr, InflatingStreamBuf::STREAM_GZIP); - /// std::string data; - /// istr >> data; -{ -public: - InflatingInputStream(std::istream& istr, InflatingStreamBuf::StreamType type = InflatingStreamBuf::STREAM_ZLIB); - ~InflatingInputStream(); -}; - - -} // namespace Poco - - -#endif // Foundation_InflatingStream_INCLUDED +// +// InflatingStream.h +// +// $Id: //poco/1.2/Foundation/include/Poco/InflatingStream.h#1 $ +// +// Library: Foundation +// Package: Streams +// Module: ZLibStream +// +// Definition of the InflatingInputStream and InflatingOutputStream classes. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_InflatingStream_INCLUDED +#define Foundation_InflatingStream_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/BufferedStreamBuf.h" +#include +#include +#include "Poco/zlib.h" + + +namespace Poco { + + +class Foundation_API InflatingStreamBuf: public BufferedStreamBuf + /// This is the streambuf class used by InflatingInputStream and InflatingOutputStream. + /// The actual work is delegated to zlib 1.2.1 (see http://www.gzip.org). + /// Both zlib (deflate) streams and gzip streams are supported. + /// Output streams should always call close() to ensure + /// proper completion of decompression. +{ +public: + enum StreamType + { + STREAM_ZLIB, + STREAM_GZIP + }; + + InflatingStreamBuf(std::istream& istr, StreamType type); + InflatingStreamBuf(std::ostream& ostr, StreamType type); + ~InflatingStreamBuf(); + int close(); + +protected: + int readFromDevice(char* buffer, std::streamsize length); + int writeToDevice(const char* buffer, std::streamsize length); + +private: + enum + { + STREAM_BUFFER_SIZE = 1024, + INFLATE_BUFFER_SIZE = 32768 + }; + + std::istream* _pIstr; + std::ostream* _pOstr; + char* _buffer; + z_stream _zstr; + bool _eof; +}; + + +class Foundation_API InflatingIOS: public virtual std::ios + /// The base class for InflatingOutputStream and InflatingInputStream. + /// + /// This class is needed to ensure the correct initialization + /// order of the stream buffer and base classes. +{ +public: + InflatingIOS(std::ostream& ostr, InflatingStreamBuf::StreamType type = InflatingStreamBuf::STREAM_ZLIB); + InflatingIOS(std::istream& istr, InflatingStreamBuf::StreamType type = InflatingStreamBuf::STREAM_ZLIB); + ~InflatingIOS(); + InflatingStreamBuf* rdbuf(); + +protected: + InflatingStreamBuf _buf; +}; + + +class Foundation_API InflatingOutputStream: public InflatingIOS, public std::ostream + /// This stream decompresses all data passing through it + /// using zlib's inflate algorithm. + /// After all data has been written to the stream, close() + /// must be called to ensure completion of decompression. +{ +public: + InflatingOutputStream(std::ostream& ostr, InflatingStreamBuf::StreamType type = InflatingStreamBuf::STREAM_ZLIB); + ~InflatingOutputStream(); + int close(); +}; + + +class Foundation_API InflatingInputStream: public InflatingIOS, public std::istream + /// This stream decompresses all data passing through it + /// using zlib's inflate algorithm. + /// Example: + /// std::ifstream istr("data.gz", std::ios::binary); + /// InflatingInputStream inflater(istr, InflatingStreamBuf::STREAM_GZIP); + /// std::string data; + /// istr >> data; +{ +public: + InflatingInputStream(std::istream& istr, InflatingStreamBuf::StreamType type = InflatingStreamBuf::STREAM_ZLIB); + ~InflatingInputStream(); +}; + + +} // namespace Poco + + +#endif // Foundation_InflatingStream_INCLUDED diff --git a/Foundation/include/Poco/Instantiator.h b/Foundation/include/Poco/Instantiator.h index 7acf9f960..afc60921f 100644 --- a/Foundation/include/Poco/Instantiator.h +++ b/Foundation/include/Poco/Instantiator.h @@ -1,104 +1,104 @@ -// -// Instantiator.h -// -// $Id: //poco/1.2/Foundation/include/Poco/Instantiator.h#1 $ -// -// Library: Foundation -// Package: Core -// Module: Instantiator -// -// Definition of the Instantiator class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_Instantiator_INCLUDED -#define Foundation_Instantiator_INCLUDED - - -#include "Poco/Foundation.h" - - -namespace Poco { - - -template -class AbstractInstantiator - /// The common base class for all Instantiator instantiations. - /// Used by DynamicFactory. -{ -public: - AbstractInstantiator() - /// Creates the AbstractInstantiator. - { - } - - virtual ~AbstractInstantiator() - /// Destroys the AbstractInstantiator. - { - } - - virtual Base* createInstance() const = 0; - /// Creates an instance of a concrete subclass of Base. - -private: - AbstractInstantiator(const AbstractInstantiator&); - AbstractInstantiator& operator = (const AbstractInstantiator&); -}; - - -template -class Instantiator: public AbstractInstantiator - /// A template class for the easy instantiation of - /// instantiators. - /// - /// For the Instantiator to work, the class of which - /// instances are to be instantiated must have a no-argument - /// constructor. -{ -public: - Instantiator() - /// Creates the Instantiator. - { - } - - virtual ~Instantiator() - /// Destroys the Instantiator. - { - } - - Base* createInstance() const - { - return new C; - } -}; - - -} // namespace Poco - - -#endif // Foundation_Instantiator_INCLUDED +// +// Instantiator.h +// +// $Id: //poco/1.2/Foundation/include/Poco/Instantiator.h#1 $ +// +// Library: Foundation +// Package: Core +// Module: Instantiator +// +// Definition of the Instantiator class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_Instantiator_INCLUDED +#define Foundation_Instantiator_INCLUDED + + +#include "Poco/Foundation.h" + + +namespace Poco { + + +template +class AbstractInstantiator + /// The common base class for all Instantiator instantiations. + /// Used by DynamicFactory. +{ +public: + AbstractInstantiator() + /// Creates the AbstractInstantiator. + { + } + + virtual ~AbstractInstantiator() + /// Destroys the AbstractInstantiator. + { + } + + virtual Base* createInstance() const = 0; + /// Creates an instance of a concrete subclass of Base. + +private: + AbstractInstantiator(const AbstractInstantiator&); + AbstractInstantiator& operator = (const AbstractInstantiator&); +}; + + +template +class Instantiator: public AbstractInstantiator + /// A template class for the easy instantiation of + /// instantiators. + /// + /// For the Instantiator to work, the class of which + /// instances are to be instantiated must have a no-argument + /// constructor. +{ +public: + Instantiator() + /// Creates the Instantiator. + { + } + + virtual ~Instantiator() + /// Destroys the Instantiator. + { + } + + Base* createInstance() const + { + return new C; + } +}; + + +} // namespace Poco + + +#endif // Foundation_Instantiator_INCLUDED diff --git a/Foundation/include/Poco/KeyValueArgs.h b/Foundation/include/Poco/KeyValueArgs.h index d08e6a65e..4c098e514 100644 --- a/Foundation/include/Poco/KeyValueArgs.h +++ b/Foundation/include/Poco/KeyValueArgs.h @@ -1,95 +1,95 @@ -// -// KeyValueArgs.h -// -// $Id: //poco/1.2/Foundation/include/Poco/KeyValueArgs.h#2 $ -// -// Library: Foundation -// Package: Cache -// Module: KeyValueArgs -// -// Definition of the KeyValueArgs class. -// -// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_KeyValueArgs_INCLUDED -#define Foundation_KeyValueArgs_INCLUDED - - -#include "Poco/Foundation.h" - - -namespace Poco { - - -template -class KeyValueArgs - /// Simply event arguments class to transfer a key and a value via an event call. - /// Note that key and value are *NOT* copied, only references to them are stored. -{ -public: - KeyValueArgs(const TKey& aKey, const TValue& aVal): - _key(aKey), - _value(aVal) - { - } - - KeyValueArgs(const KeyValueArgs& args): - _key(args._key), - _value(args._value) - { - } - - ~KeyValueArgs() - { - } - - const TKey& key() const - /// Returns a reference to the key, - { - return _key; - } - - const TValue& value() const - /// Returns a Reference to the value. - { - return _value; - } - -protected: - const TKey& _key; - const TValue& _value; - -private: - KeyValueArgs& operator = (const KeyValueArgs& args); -}; - - -} // namespace Poco - - -#endif +// +// KeyValueArgs.h +// +// $Id: //poco/1.2/Foundation/include/Poco/KeyValueArgs.h#2 $ +// +// Library: Foundation +// Package: Cache +// Module: KeyValueArgs +// +// Definition of the KeyValueArgs class. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_KeyValueArgs_INCLUDED +#define Foundation_KeyValueArgs_INCLUDED + + +#include "Poco/Foundation.h" + + +namespace Poco { + + +template +class KeyValueArgs + /// Simply event arguments class to transfer a key and a value via an event call. + /// Note that key and value are *NOT* copied, only references to them are stored. +{ +public: + KeyValueArgs(const TKey& aKey, const TValue& aVal): + _key(aKey), + _value(aVal) + { + } + + KeyValueArgs(const KeyValueArgs& args): + _key(args._key), + _value(args._value) + { + } + + ~KeyValueArgs() + { + } + + const TKey& key() const + /// Returns a reference to the key, + { + return _key; + } + + const TValue& value() const + /// Returns a Reference to the value. + { + return _value; + } + +protected: + const TKey& _key; + const TValue& _value; + +private: + KeyValueArgs& operator = (const KeyValueArgs& args); +}; + + +} // namespace Poco + + +#endif diff --git a/Foundation/include/Poco/LRUCache.h b/Foundation/include/Poco/LRUCache.h index 2926ed7b6..ad8431a14 100644 --- a/Foundation/include/Poco/LRUCache.h +++ b/Foundation/include/Poco/LRUCache.h @@ -1,73 +1,73 @@ -// -// LRUCache.h -// -// $Id: //poco/1.2/Foundation/include/Poco/LRUCache.h#4 $ -// -// Library: Foundation -// Package: Cache -// Module: LRUCache -// -// Definition of the LRUCache class. -// -// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_LRUCache_INCLUDED -#define Foundation_LRUCache_INCLUDED - - -#include "Poco/AbstractCache.h" -#include "Poco/LRUStrategy.h" - - -namespace Poco { - - -template -class LRUCache: public AbstractCache > - /// An LRUCache implements Least Recently Used caching. The default size for a cache is 1024 entries -{ -public: - LRUCache(long size = 1024): - AbstractCache >(LRUStrategy(size)) - { - } - - ~LRUCache() - { - } - -private: - LRUCache(const LRUCache& aCache); - LRUCache& operator = (const LRUCache& aCache); -}; - - -} // namespace Poco - - -#endif +// +// LRUCache.h +// +// $Id: //poco/1.2/Foundation/include/Poco/LRUCache.h#4 $ +// +// Library: Foundation +// Package: Cache +// Module: LRUCache +// +// Definition of the LRUCache class. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_LRUCache_INCLUDED +#define Foundation_LRUCache_INCLUDED + + +#include "Poco/AbstractCache.h" +#include "Poco/LRUStrategy.h" + + +namespace Poco { + + +template +class LRUCache: public AbstractCache > + /// An LRUCache implements Least Recently Used caching. The default size for a cache is 1024 entries +{ +public: + LRUCache(long size = 1024): + AbstractCache >(LRUStrategy(size)) + { + } + + ~LRUCache() + { + } + +private: + LRUCache(const LRUCache& aCache); + LRUCache& operator = (const LRUCache& aCache); +}; + + +} // namespace Poco + + +#endif diff --git a/Foundation/include/Poco/LRUStrategy.h b/Foundation/include/Poco/LRUStrategy.h index 6e987960b..2d473246f 100644 --- a/Foundation/include/Poco/LRUStrategy.h +++ b/Foundation/include/Poco/LRUStrategy.h @@ -1,161 +1,161 @@ -// -// LRUStrategy.h -// -// $Id: //poco/1.2/Foundation/include/Poco/LRUStrategy.h#2 $ -// -// Library: Foundation -// Package: Cache -// Module: LRUStrategy -// -// Definition of the LRUStrategy class. -// -// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_LRUStrategy_INCLUDED -#define Foundation_LRUStrategy_INCLUDED - - -#include "Poco/KeyValueArgs.h" -#include "Poco/ValidArgs.h" -#include "Poco/AbstractStrategy.h" -#include "Poco/EventArgs.h" -#include "Poco/Exception.h" -#include -#include - - -namespace Poco { - - -template -class LRUStrategy: public AbstractStrategy - /// An LRUStrategy implements least recently used cache replacement. -{ -public: - typedef std::list Keys; - typedef typename Keys::iterator Iterator; - typedef typename Keys::const_iterator ConstIterator; - typedef std::map KeyIndex; - typedef typename KeyIndex::iterator IndexIterator; - typedef typename KeyIndex::const_iterator ConstIndexIterator; - -public: - LRUStrategy(size_t size): - _size(size) - { - if (_size < 1) throw InvalidArgumentException("size must be > 0"); - } - - ~LRUStrategy() - { - } - - void onAdd(const void*, const KeyValueArgs & args) - { - _keys.push_front(args.key()); - std::pair stat = _keyIndex.insert(make_pair(args.key(), _keys.begin())); - if (!stat.second) - { - stat.first->second = _keys.begin(); - } - } - - void onRemove(const void*, const TKey& key) - { - IndexIterator it = _keyIndex.find(key); - - if (it != _keyIndex.end()) - { - _keys.erase(it->second); - _keyIndex.erase(it); - } - } - - void onGet(const void*, const TKey& key) - { - // LRU: in case of an hit, move to begin - IndexIterator it = _keyIndex.find(key); - - if (it != _keyIndex.end()) - { - _keys.splice(_keys.begin(), _keys, it->second); //_keys.erase(it->second)+_keys.push_front(key); - it->second = _keys.begin(); - } - } - - void onClear(const void*, const EventArgs& args) - { - _keys.clear(); - _keyIndex.clear(); - } - - void onIsValid(const void*, ValidArgs& args) - { - if (_keyIndex.find(args.key()) == _keyIndex.end()) - { - args.invalidate(); - } - } - - void onReplace(const void*, std::set& elemsToRemove) - { - // Note: replace only informs the cache which elements - // it would like to remove! - // it does not remove them on its own! - size_t curSize = _keyIndex.size(); - - if (curSize < _size) - { - return; - } - - size_t diff = curSize - _size; - Iterator it = --_keys.end(); //--keys can never be invoked on an empty list due to the minSize==1 requirement of LRU - size_t i = 0; - - while (i++ < diff) - { - elemsToRemove.insert(*it); - if (it != _keys.begin()) - { - --it; - } - } - } - -protected: - size_t _size; /// Number of keys the cache can store. - Keys _keys; - KeyIndex _keyIndex; /// For faster access to _keys -}; - - -} // namespace Poco - - -#endif +// +// LRUStrategy.h +// +// $Id: //poco/1.2/Foundation/include/Poco/LRUStrategy.h#2 $ +// +// Library: Foundation +// Package: Cache +// Module: LRUStrategy +// +// Definition of the LRUStrategy class. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_LRUStrategy_INCLUDED +#define Foundation_LRUStrategy_INCLUDED + + +#include "Poco/KeyValueArgs.h" +#include "Poco/ValidArgs.h" +#include "Poco/AbstractStrategy.h" +#include "Poco/EventArgs.h" +#include "Poco/Exception.h" +#include +#include + + +namespace Poco { + + +template +class LRUStrategy: public AbstractStrategy + /// An LRUStrategy implements least recently used cache replacement. +{ +public: + typedef std::list Keys; + typedef typename Keys::iterator Iterator; + typedef typename Keys::const_iterator ConstIterator; + typedef std::map KeyIndex; + typedef typename KeyIndex::iterator IndexIterator; + typedef typename KeyIndex::const_iterator ConstIndexIterator; + +public: + LRUStrategy(size_t size): + _size(size) + { + if (_size < 1) throw InvalidArgumentException("size must be > 0"); + } + + ~LRUStrategy() + { + } + + void onAdd(const void*, const KeyValueArgs & args) + { + _keys.push_front(args.key()); + std::pair stat = _keyIndex.insert(make_pair(args.key(), _keys.begin())); + if (!stat.second) + { + stat.first->second = _keys.begin(); + } + } + + void onRemove(const void*, const TKey& key) + { + IndexIterator it = _keyIndex.find(key); + + if (it != _keyIndex.end()) + { + _keys.erase(it->second); + _keyIndex.erase(it); + } + } + + void onGet(const void*, const TKey& key) + { + // LRU: in case of an hit, move to begin + IndexIterator it = _keyIndex.find(key); + + if (it != _keyIndex.end()) + { + _keys.splice(_keys.begin(), _keys, it->second); //_keys.erase(it->second)+_keys.push_front(key); + it->second = _keys.begin(); + } + } + + void onClear(const void*, const EventArgs& args) + { + _keys.clear(); + _keyIndex.clear(); + } + + void onIsValid(const void*, ValidArgs& args) + { + if (_keyIndex.find(args.key()) == _keyIndex.end()) + { + args.invalidate(); + } + } + + void onReplace(const void*, std::set& elemsToRemove) + { + // Note: replace only informs the cache which elements + // it would like to remove! + // it does not remove them on its own! + size_t curSize = _keyIndex.size(); + + if (curSize < _size) + { + return; + } + + size_t diff = curSize - _size; + Iterator it = --_keys.end(); //--keys can never be invoked on an empty list due to the minSize==1 requirement of LRU + size_t i = 0; + + while (i++ < diff) + { + elemsToRemove.insert(*it); + if (it != _keys.begin()) + { + --it; + } + } + } + +protected: + size_t _size; /// Number of keys the cache can store. + Keys _keys; + KeyIndex _keyIndex; /// For faster access to _keys +}; + + +} // namespace Poco + + +#endif diff --git a/Foundation/include/Poco/Latin1Encoding.h b/Foundation/include/Poco/Latin1Encoding.h index 901504ac6..80bd7c15f 100644 --- a/Foundation/include/Poco/Latin1Encoding.h +++ b/Foundation/include/Poco/Latin1Encoding.h @@ -1,68 +1,68 @@ -// -// Latin1Encoding.h -// -// $Id: //poco/1.2/Foundation/include/Poco/Latin1Encoding.h#1 $ -// -// Library: Foundation -// Package: Text -// Module: Latin1Encoding -// -// Definition of the Latin1Encoding class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_Latin1Encoding_INCLUDED -#define Foundation_Latin1Encoding_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/TextEncoding.h" - - -namespace Poco { - - -class Foundation_API Latin1Encoding: public TextEncoding - /// ISO Latin-1 (8859-1) text encoding. -{ -public: - Latin1Encoding(); - ~Latin1Encoding(); - const CharacterMap& characterMap() const; - int convert(const unsigned char* bytes) const; - int convert(int ch, unsigned char* bytes, int length) const; - -private: - static const CharacterMap _charMap; -}; - - -} // namespace Poco - - -#endif // Foundation_Latin1Encoding_INCLUDED +// +// Latin1Encoding.h +// +// $Id: //poco/1.2/Foundation/include/Poco/Latin1Encoding.h#1 $ +// +// Library: Foundation +// Package: Text +// Module: Latin1Encoding +// +// Definition of the Latin1Encoding class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_Latin1Encoding_INCLUDED +#define Foundation_Latin1Encoding_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/TextEncoding.h" + + +namespace Poco { + + +class Foundation_API Latin1Encoding: public TextEncoding + /// ISO Latin-1 (8859-1) text encoding. +{ +public: + Latin1Encoding(); + ~Latin1Encoding(); + const CharacterMap& characterMap() const; + int convert(const unsigned char* bytes) const; + int convert(int ch, unsigned char* bytes, int length) const; + +private: + static const CharacterMap _charMap; +}; + + +} // namespace Poco + + +#endif // Foundation_Latin1Encoding_INCLUDED diff --git a/Foundation/include/Poco/Latin9Encoding.h b/Foundation/include/Poco/Latin9Encoding.h index 484e42265..6f184bc66 100644 --- a/Foundation/include/Poco/Latin9Encoding.h +++ b/Foundation/include/Poco/Latin9Encoding.h @@ -1,71 +1,71 @@ -// -// Latin9Encoding.h -// -// $Id: //poco/1.2/Foundation/include/Poco/Latin9Encoding.h#1 $ -// -// Library: Foundation -// Package: Text -// Module: Latin9Encoding -// -// Definition of the Latin9Encoding class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_Latin9Encoding_INCLUDED -#define Foundation_Latin9Encoding_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/TextEncoding.h" - - -namespace Poco { - - -class Foundation_API Latin9Encoding: public TextEncoding - /// ISO Latin-9 (8859-15) text encoding. - /// - /// Latin-9 is basically Latin-1 with the EURO sign plus - /// some other minor changes. -{ -public: - Latin9Encoding(); - ~Latin9Encoding(); - const CharacterMap& characterMap() const; - int convert(const unsigned char* bytes) const; - int convert(int ch, unsigned char* bytes, int length) const; - -private: - static const CharacterMap _charMap; -}; - - -} // namespace Poco - - -#endif // Foundation_Latin9Encoding_INCLUDED +// +// Latin9Encoding.h +// +// $Id: //poco/1.2/Foundation/include/Poco/Latin9Encoding.h#1 $ +// +// Library: Foundation +// Package: Text +// Module: Latin9Encoding +// +// Definition of the Latin9Encoding class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_Latin9Encoding_INCLUDED +#define Foundation_Latin9Encoding_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/TextEncoding.h" + + +namespace Poco { + + +class Foundation_API Latin9Encoding: public TextEncoding + /// ISO Latin-9 (8859-15) text encoding. + /// + /// Latin-9 is basically Latin-1 with the EURO sign plus + /// some other minor changes. +{ +public: + Latin9Encoding(); + ~Latin9Encoding(); + const CharacterMap& characterMap() const; + int convert(const unsigned char* bytes) const; + int convert(int ch, unsigned char* bytes, int length) const; + +private: + static const CharacterMap _charMap; +}; + + +} // namespace Poco + + +#endif // Foundation_Latin9Encoding_INCLUDED diff --git a/Foundation/include/Poco/LineEndingConverter.h b/Foundation/include/Poco/LineEndingConverter.h index 7fc566726..1bd2623a6 100644 --- a/Foundation/include/Poco/LineEndingConverter.h +++ b/Foundation/include/Poco/LineEndingConverter.h @@ -1,203 +1,203 @@ -// -// LineEndingConverter.h -// -// $Id: //poco/1.2/Foundation/include/Poco/LineEndingConverter.h#1 $ -// -// Library: Foundation -// Package: Streams -// Module: LineEndingConverter -// -// Definition of the LineEndingConverter class. -// -// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_LineEndingConverter_INCLUDED -#define Foundation_LineEndingConverter_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/UnbufferedStreamBuf.h" -#include -#include - - -namespace Poco { - - -class Foundation_API LineEnding - /// This class defines valid line ending sequences - /// for InputLineEndingConverter and OutputLineEndingConverter. -{ -public: - static const std::string NEWLINE_DEFAULT; - static const std::string NEWLINE_CR; - static const std::string NEWLINE_CRLF; - static const std::string NEWLINE_LF; -}; - - -class Foundation_API LineEndingConverterStreamBuf: public UnbufferedStreamBuf - /// This stream buffer performs line ending conversion - /// on text streams. The converter can convert from and to - /// the Unix (LF), Mac (CR) and DOS/Windows/Network (CF-LF) endings. - /// - /// Any newline sequence in the source will be replaced by the - /// target newline sequence. -{ -public: - LineEndingConverterStreamBuf(std::istream& istr); - /// Creates the LineEndingConverterStreamBuf and connects it - /// to the given input stream. - - LineEndingConverterStreamBuf(std::ostream& ostr); - /// Creates the LineEndingConverterStreamBuf and connects it - /// to the given output stream. - - ~LineEndingConverterStreamBuf(); - /// Destroys the LineEndingConverterStream. - - void setNewLine(const std::string& newLineCharacters); - /// Sets the target line ending for the converter. - /// - /// Possible values are: - /// * NEWLINE_DEFAULT (whatever is appropriate for the current platform) - /// * NEWLINE_CRLF (Windows), - /// * NEWLINE_LF (Unix), - /// * NEWLINE_CR (Macintosh) - /// - /// In theory, any character sequence can be used as newline sequence. - /// In practice, however, only the above three make sense. - - const std::string& getNewLine() const; - /// Returns the line ending currently in use. - -protected: - int readFromDevice(); - int writeToDevice(char c); - -private: - std::istream* _pIstr; - std::ostream* _pOstr; - std::string _newLine; - std::string::const_iterator _it; - char _lastChar; -}; - - -class Foundation_API LineEndingConverterIOS: public virtual std::ios - /// The base class for InputLineEndingConverter and OutputLineEndingConverter. - /// - /// This class provides common methods and is also needed to ensure - /// the correct initialization order of the stream buffer and base classes. -{ -public: - LineEndingConverterIOS(std::istream& istr); - /// Creates the LineEndingConverterIOS and connects it - /// to the given input stream. - - LineEndingConverterIOS(std::ostream& ostr); - /// Creates the LineEndingConverterIOS and connects it - /// to the given output stream. - - ~LineEndingConverterIOS(); - /// Destroys the stream. - - void setNewLine(const std::string& newLineCharacters); - /// Sets the target line ending for the converter. - /// - /// Possible values are: - /// * NEWLINE_DEFAULT (whatever is appropriate for the current platform) - /// * NEWLINE_CRLF (Windows), - /// * NEWLINE_LF (Unix), - /// * NEWLINE_CR (Macintosh) - /// - /// In theory, any character sequence can be used as newline sequence. - /// In practice, however, only the above three make sense. - /// - /// If an empty string is given, all newline characters are removed from - /// the stream. - - const std::string& getNewLine() const; - /// Returns the line ending currently in use. - - LineEndingConverterStreamBuf* rdbuf(); - /// Returns a pointer to the underlying streambuf. - -protected: - LineEndingConverterStreamBuf _buf; -}; - - -class Foundation_API InputLineEndingConverter: public LineEndingConverterIOS, public std::istream - /// InputLineEndingConverter performs line ending conversion - /// on text input streams. The converter can convert from and to - /// the Unix (LF), Mac (CR) and DOS/Windows/Network (CF-LF) endings. - /// - /// Any newline sequence in the source will be replaced by the - /// target newline sequence. -{ -public: - InputLineEndingConverter(std::istream& istr); - /// Creates the LineEndingConverterInputStream and connects it - /// to the given input stream. - - InputLineEndingConverter(std::istream& istr, const std::string& newLineCharacters); - /// Creates the LineEndingConverterInputStream and connects it - /// to the given input stream. - - ~InputLineEndingConverter(); - /// Destroys the stream. -}; - - -class Foundation_API OutputLineEndingConverter: public LineEndingConverterIOS, public std::ostream - /// OutputLineEndingConverter performs line ending conversion - /// on text output streams. The converter can convert from and to - /// the Unix (LF), Mac (CR) and DOS/Windows/Network (CF-LF) endings. - /// - /// Any newline sequence in the source will be replaced by the - /// target newline sequence. -{ -public: - OutputLineEndingConverter(std::ostream& ostr); - /// Creates the LineEndingConverterOutputStream and connects it - /// to the given input stream. - - OutputLineEndingConverter(std::ostream& ostr, const std::string& newLineCharacters); - /// Creates the LineEndingConverterOutputStream and connects it - /// to the given input stream. - - ~OutputLineEndingConverter(); - /// Destroys the LineEndingConverterOutputStream. -}; - - -} // namespace Poco - - -#endif // Foundation_LineEndingConverter_INCLUDED +// +// LineEndingConverter.h +// +// $Id: //poco/1.2/Foundation/include/Poco/LineEndingConverter.h#1 $ +// +// Library: Foundation +// Package: Streams +// Module: LineEndingConverter +// +// Definition of the LineEndingConverter class. +// +// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_LineEndingConverter_INCLUDED +#define Foundation_LineEndingConverter_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/UnbufferedStreamBuf.h" +#include +#include + + +namespace Poco { + + +class Foundation_API LineEnding + /// This class defines valid line ending sequences + /// for InputLineEndingConverter and OutputLineEndingConverter. +{ +public: + static const std::string NEWLINE_DEFAULT; + static const std::string NEWLINE_CR; + static const std::string NEWLINE_CRLF; + static const std::string NEWLINE_LF; +}; + + +class Foundation_API LineEndingConverterStreamBuf: public UnbufferedStreamBuf + /// This stream buffer performs line ending conversion + /// on text streams. The converter can convert from and to + /// the Unix (LF), Mac (CR) and DOS/Windows/Network (CF-LF) endings. + /// + /// Any newline sequence in the source will be replaced by the + /// target newline sequence. +{ +public: + LineEndingConverterStreamBuf(std::istream& istr); + /// Creates the LineEndingConverterStreamBuf and connects it + /// to the given input stream. + + LineEndingConverterStreamBuf(std::ostream& ostr); + /// Creates the LineEndingConverterStreamBuf and connects it + /// to the given output stream. + + ~LineEndingConverterStreamBuf(); + /// Destroys the LineEndingConverterStream. + + void setNewLine(const std::string& newLineCharacters); + /// Sets the target line ending for the converter. + /// + /// Possible values are: + /// * NEWLINE_DEFAULT (whatever is appropriate for the current platform) + /// * NEWLINE_CRLF (Windows), + /// * NEWLINE_LF (Unix), + /// * NEWLINE_CR (Macintosh) + /// + /// In theory, any character sequence can be used as newline sequence. + /// In practice, however, only the above three make sense. + + const std::string& getNewLine() const; + /// Returns the line ending currently in use. + +protected: + int readFromDevice(); + int writeToDevice(char c); + +private: + std::istream* _pIstr; + std::ostream* _pOstr; + std::string _newLine; + std::string::const_iterator _it; + char _lastChar; +}; + + +class Foundation_API LineEndingConverterIOS: public virtual std::ios + /// The base class for InputLineEndingConverter and OutputLineEndingConverter. + /// + /// This class provides common methods and is also needed to ensure + /// the correct initialization order of the stream buffer and base classes. +{ +public: + LineEndingConverterIOS(std::istream& istr); + /// Creates the LineEndingConverterIOS and connects it + /// to the given input stream. + + LineEndingConverterIOS(std::ostream& ostr); + /// Creates the LineEndingConverterIOS and connects it + /// to the given output stream. + + ~LineEndingConverterIOS(); + /// Destroys the stream. + + void setNewLine(const std::string& newLineCharacters); + /// Sets the target line ending for the converter. + /// + /// Possible values are: + /// * NEWLINE_DEFAULT (whatever is appropriate for the current platform) + /// * NEWLINE_CRLF (Windows), + /// * NEWLINE_LF (Unix), + /// * NEWLINE_CR (Macintosh) + /// + /// In theory, any character sequence can be used as newline sequence. + /// In practice, however, only the above three make sense. + /// + /// If an empty string is given, all newline characters are removed from + /// the stream. + + const std::string& getNewLine() const; + /// Returns the line ending currently in use. + + LineEndingConverterStreamBuf* rdbuf(); + /// Returns a pointer to the underlying streambuf. + +protected: + LineEndingConverterStreamBuf _buf; +}; + + +class Foundation_API InputLineEndingConverter: public LineEndingConverterIOS, public std::istream + /// InputLineEndingConverter performs line ending conversion + /// on text input streams. The converter can convert from and to + /// the Unix (LF), Mac (CR) and DOS/Windows/Network (CF-LF) endings. + /// + /// Any newline sequence in the source will be replaced by the + /// target newline sequence. +{ +public: + InputLineEndingConverter(std::istream& istr); + /// Creates the LineEndingConverterInputStream and connects it + /// to the given input stream. + + InputLineEndingConverter(std::istream& istr, const std::string& newLineCharacters); + /// Creates the LineEndingConverterInputStream and connects it + /// to the given input stream. + + ~InputLineEndingConverter(); + /// Destroys the stream. +}; + + +class Foundation_API OutputLineEndingConverter: public LineEndingConverterIOS, public std::ostream + /// OutputLineEndingConverter performs line ending conversion + /// on text output streams. The converter can convert from and to + /// the Unix (LF), Mac (CR) and DOS/Windows/Network (CF-LF) endings. + /// + /// Any newline sequence in the source will be replaced by the + /// target newline sequence. +{ +public: + OutputLineEndingConverter(std::ostream& ostr); + /// Creates the LineEndingConverterOutputStream and connects it + /// to the given input stream. + + OutputLineEndingConverter(std::ostream& ostr, const std::string& newLineCharacters); + /// Creates the LineEndingConverterOutputStream and connects it + /// to the given input stream. + + ~OutputLineEndingConverter(); + /// Destroys the LineEndingConverterOutputStream. +}; + + +} // namespace Poco + + +#endif // Foundation_LineEndingConverter_INCLUDED diff --git a/Foundation/include/Poco/LocalDateTime.h b/Foundation/include/Poco/LocalDateTime.h index e34c0cc4f..88a271bfc 100644 --- a/Foundation/include/Poco/LocalDateTime.h +++ b/Foundation/include/Poco/LocalDateTime.h @@ -1,370 +1,370 @@ -// -// LocalDateTime.h -// -// $Id: //poco/1.2/Foundation/include/Poco/LocalDateTime.h#1 $ -// -// Library: Foundation -// Package: DateTime -// Module: LocalDateTime -// -// Definition of the LocalDateTime class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_LocalDateTime_INCLUDED -#define Foundation_LocalDateTime_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/DateTime.h" - - -namespace Poco { - - -class Foundation_API LocalDateTime - /// This class represents an instant in local time - /// (as opposed to UTC), expressed in years, months, days, - /// hours, minutes, seconds and milliseconds based on the - /// Gregorian calendar. - /// - /// In addition to the date and time, the class also - /// maintains a time zone differential, which denotes - /// the difference in seconds from UTC to local time, - /// i.e. UTC = local time - time zone differential. - /// - /// Although LocalDateTime supports relational and arithmetic - /// operators, all date/time comparisons and date/time arithmetics - /// should be done in UTC, using the DateTime or Timestamp - /// class for better performance. The relational operators - /// normalize the dates/times involved to UTC before carrying out - /// the comparison. -{ -public: - LocalDateTime(); - /// Creates a LocalDateTime with the current date/time - /// for the current time zone. - - LocalDateTime(int year, int month, int day, int hour = 0, int minute = 0, int second = 0, int millisecond = 0, int microsecond = 0); - /// Creates a DateTime for the given Gregorian local date and time. - /// * year is from 0 to 9999. - /// * month is from 1 to 12. - /// * day is from 1 to 31. - /// * hour is from 0 to 23. - /// * minute is from 0 to 59. - /// * second is from 0 to 59. - /// * millisecond is from 0 to 999. - /// * microsecond is from 0 to 999. - - LocalDateTime(int tzd, int year, int month, int day, int hour, int minute, int second, int millisecond, int microsecond); - /// Creates a DateTime for the given Gregorian date and time in the - /// time zone denoted by the time zone differential in tzd. - /// * tzd is in seconds. - /// * year is from 0 to 9999. - /// * month is from 1 to 12. - /// * day is from 1 to 31. - /// * hour is from 0 to 23. - /// * minute is from 0 to 59. - /// * second is from 0 to 59. - /// * millisecond is from 0 to 999. - /// * microsecond is from 0 to 999. - - LocalDateTime(const DateTime& dateTime); - /// Creates a LocalDateTime from the UTC time given in dateTime, - /// using the time zone differential of the current time zone. - - LocalDateTime(int tzd, const DateTime& dateTime); - /// Creates a LocalDateTime from the UTC time given in dateTime, - /// using the given time zone differential. - - LocalDateTime(double julianDay); - /// Creates a LocalDateTime for the given Julian day in the local time zone. - - LocalDateTime(int tzd, double julianDay); - /// Creates a LocalDateTime for the given Julian day in the time zone - /// denoted by the time zone differential in tzd. - - LocalDateTime(const LocalDateTime& dateTime); - /// Copy constructor. Creates the LocalDateTime from another one. - - ~LocalDateTime(); - /// Destroys the LocalDateTime. - - LocalDateTime& operator = (const LocalDateTime& dateTime); - /// Assigns another LocalDateTime. - - LocalDateTime& operator = (const Timestamp& timestamp); - /// Assigns a timestamp - - LocalDateTime& operator = (double julianDay); - /// Assigns a Julian day in the local time zone. - - LocalDateTime& assign(int year, int month, int day, int hour = 0, int minute = 0, int second = 0, int millisecond = 0, int microseconds = 0); - /// Assigns a Gregorian local date and time. - /// * year is from 0 to 9999. - /// * month is from 1 to 12. - /// * day is from 1 to 31. - /// * hour is from 0 to 23. - /// * minute is from 0 to 59. - /// * second is from 0 to 59. - /// * millisecond is from 0 to 999. - /// * microsecond is from 0 to 999. - - LocalDateTime& assign(int tzd, int year, int month, int day, int hour, int minute, int second, int millisecond, int microseconds); - /// Assigns a Gregorian local date and time in the time zone denoted by - /// the time zone differential in tzd. - /// * tzd is in seconds. - /// * year is from 0 to 9999. - /// * month is from 1 to 12. - /// * day is from 1 to 31. - /// * hour is from 0 to 23. - /// * minute is from 0 to 59. - /// * second is from 0 to 59. - /// * millisecond is from 0 to 999. - /// * microsecond is from 0 to 999. - - LocalDateTime& assign(int tzd, double julianDay); - /// Assigns a Julian day in the time zone denoted by the - /// time zone differential in tzd. - - void swap(LocalDateTime& dateTime); - /// Swaps the LocalDateTime with another one. - - int year() const; - /// Returns the year. - - int month() const; - /// Returns the month (1 to 12). - - int week(int firstDayOfWeek = DateTime::MONDAY) const; - /// Returns the week number within the year. - /// FirstDayOfWeek should be either SUNDAY (0) or MONDAY (1). - /// The returned week number will be from 0 to 53. Week number 1 is the week - /// containing January 4. This is in accordance to ISO 8601. - /// - /// The following example assumes that firstDayOfWeek is MONDAY. For 2005, which started - /// on a Saturday, week 1 will be the week starting on Monday, January 3. - /// January 1 and 2 will fall within week 0 (or the last week of the previous year). - /// - /// For 2007, which starts on a Monday, week 1 will be the week startung on Monday, January 1. - /// There will be no week 0 in 2007. - - int day() const; - /// Returns the day witin the month (1 to 31). - - int dayOfWeek() const; - /// Returns the weekday (0 to 6, where - /// 0 = Sunday, 1 = Monday, ..., 6 = Saturday). - - int dayOfYear() const; - /// Returns the number of the day in the year. - /// January 1 is 1, February 1 is 32, etc. - - int hour() const; - /// Returns the hour (0 to 23). - - int hourAMPM() const; - /// Returns the hour (0 to 12). - - bool isAM() const; - /// Returns true if hour < 12; - - bool isPM() const; - /// Returns true if hour >= 12. - - int minute() const; - /// Returns the minute (0 to 59). - - int second() const; - /// Returns the second (0 to 59). - - int millisecond() const; - /// Returns the millisecond (0 to 999) - - int microsecond() const; - /// Returns the microsecond (0 to 999) - - double julianDay() const; - /// Returns the julian day for the date. - - int tzd() const; - /// Returns the time zone differential. - - DateTime utc() const; - /// Returns the UTC equivalent for the local date and time. - - Timestamp timestamp() const; - /// Returns the date and time expressed as a Timestamp. - - Timestamp::UtcTimeVal utcTime() const; - /// Returns the UTC equivalent for the local date and time. - - bool operator == (const LocalDateTime& dateTime) const; - bool operator != (const LocalDateTime& dateTime) const; - bool operator < (const LocalDateTime& dateTime) const; - bool operator <= (const LocalDateTime& dateTime) const; - bool operator > (const LocalDateTime& dateTime) const; - bool operator >= (const LocalDateTime& dateTime) const; - - LocalDateTime operator + (const Timespan& span) const; - LocalDateTime operator - (const Timespan& span) const; - Timespan operator - (const LocalDateTime& dateTime) const; - LocalDateTime& operator += (const Timespan& span); - LocalDateTime& operator -= (const Timespan& span); - -protected: - LocalDateTime(Timestamp::UtcTimeVal utcTime, Timestamp::TimeDiff diff, int tzd); - -private: - DateTime _dateTime; - int _tzd; - - friend class DateTimeFormatter; - friend class DateTimeParser; -}; - - -// -// inlines -// -inline int LocalDateTime::year() const -{ - return _dateTime.year(); -} - - -inline int LocalDateTime::month() const -{ - return _dateTime.month(); -} - - -inline int LocalDateTime::week(int firstDayOfWeek) const -{ - return _dateTime.week(firstDayOfWeek); -} - - -inline int LocalDateTime::day() const -{ - return _dateTime.day(); -} - - -inline int LocalDateTime::dayOfWeek() const -{ - return _dateTime.dayOfWeek(); -} - - -inline int LocalDateTime::dayOfYear() const -{ - return _dateTime.dayOfYear(); -} - - -inline int LocalDateTime::hour() const -{ - return _dateTime.hour(); -} - - -inline int LocalDateTime::hourAMPM() const -{ - return _dateTime.hourAMPM(); -} - - -inline bool LocalDateTime::isAM() const -{ - return _dateTime.isAM(); -} - - -inline bool LocalDateTime::isPM() const -{ - return _dateTime.isPM(); -} - - -inline int LocalDateTime::minute() const -{ - return _dateTime.minute(); -} - - -inline int LocalDateTime::second() const -{ - return _dateTime.second(); -} - - -inline int LocalDateTime::millisecond() const -{ - return _dateTime.millisecond(); -} - - -inline int LocalDateTime::microsecond() const -{ - return _dateTime.microsecond(); -} - - -inline double LocalDateTime::julianDay() const -{ - return _dateTime.julianDay(); -} - - -inline int LocalDateTime::tzd() const -{ - return _tzd; -} - -inline Timestamp LocalDateTime::timestamp() const -{ - return Timestamp::fromUtcTime(_dateTime.utcTime()); -} - -inline Timestamp::UtcTimeVal LocalDateTime::utcTime() const -{ - return _dateTime.utcTime() - ((Timestamp::TimeDiff) _tzd)*10000000; -} - - -inline void swap(LocalDateTime& d1, LocalDateTime& d2) -{ - d1.swap(d2); -} - - -} // namespace Poco - - -#endif // Foundation_LocalDateTime_INCLUDED +// +// LocalDateTime.h +// +// $Id: //poco/1.2/Foundation/include/Poco/LocalDateTime.h#1 $ +// +// Library: Foundation +// Package: DateTime +// Module: LocalDateTime +// +// Definition of the LocalDateTime class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_LocalDateTime_INCLUDED +#define Foundation_LocalDateTime_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/DateTime.h" + + +namespace Poco { + + +class Foundation_API LocalDateTime + /// This class represents an instant in local time + /// (as opposed to UTC), expressed in years, months, days, + /// hours, minutes, seconds and milliseconds based on the + /// Gregorian calendar. + /// + /// In addition to the date and time, the class also + /// maintains a time zone differential, which denotes + /// the difference in seconds from UTC to local time, + /// i.e. UTC = local time - time zone differential. + /// + /// Although LocalDateTime supports relational and arithmetic + /// operators, all date/time comparisons and date/time arithmetics + /// should be done in UTC, using the DateTime or Timestamp + /// class for better performance. The relational operators + /// normalize the dates/times involved to UTC before carrying out + /// the comparison. +{ +public: + LocalDateTime(); + /// Creates a LocalDateTime with the current date/time + /// for the current time zone. + + LocalDateTime(int year, int month, int day, int hour = 0, int minute = 0, int second = 0, int millisecond = 0, int microsecond = 0); + /// Creates a DateTime for the given Gregorian local date and time. + /// * year is from 0 to 9999. + /// * month is from 1 to 12. + /// * day is from 1 to 31. + /// * hour is from 0 to 23. + /// * minute is from 0 to 59. + /// * second is from 0 to 59. + /// * millisecond is from 0 to 999. + /// * microsecond is from 0 to 999. + + LocalDateTime(int tzd, int year, int month, int day, int hour, int minute, int second, int millisecond, int microsecond); + /// Creates a DateTime for the given Gregorian date and time in the + /// time zone denoted by the time zone differential in tzd. + /// * tzd is in seconds. + /// * year is from 0 to 9999. + /// * month is from 1 to 12. + /// * day is from 1 to 31. + /// * hour is from 0 to 23. + /// * minute is from 0 to 59. + /// * second is from 0 to 59. + /// * millisecond is from 0 to 999. + /// * microsecond is from 0 to 999. + + LocalDateTime(const DateTime& dateTime); + /// Creates a LocalDateTime from the UTC time given in dateTime, + /// using the time zone differential of the current time zone. + + LocalDateTime(int tzd, const DateTime& dateTime); + /// Creates a LocalDateTime from the UTC time given in dateTime, + /// using the given time zone differential. + + LocalDateTime(double julianDay); + /// Creates a LocalDateTime for the given Julian day in the local time zone. + + LocalDateTime(int tzd, double julianDay); + /// Creates a LocalDateTime for the given Julian day in the time zone + /// denoted by the time zone differential in tzd. + + LocalDateTime(const LocalDateTime& dateTime); + /// Copy constructor. Creates the LocalDateTime from another one. + + ~LocalDateTime(); + /// Destroys the LocalDateTime. + + LocalDateTime& operator = (const LocalDateTime& dateTime); + /// Assigns another LocalDateTime. + + LocalDateTime& operator = (const Timestamp& timestamp); + /// Assigns a timestamp + + LocalDateTime& operator = (double julianDay); + /// Assigns a Julian day in the local time zone. + + LocalDateTime& assign(int year, int month, int day, int hour = 0, int minute = 0, int second = 0, int millisecond = 0, int microseconds = 0); + /// Assigns a Gregorian local date and time. + /// * year is from 0 to 9999. + /// * month is from 1 to 12. + /// * day is from 1 to 31. + /// * hour is from 0 to 23. + /// * minute is from 0 to 59. + /// * second is from 0 to 59. + /// * millisecond is from 0 to 999. + /// * microsecond is from 0 to 999. + + LocalDateTime& assign(int tzd, int year, int month, int day, int hour, int minute, int second, int millisecond, int microseconds); + /// Assigns a Gregorian local date and time in the time zone denoted by + /// the time zone differential in tzd. + /// * tzd is in seconds. + /// * year is from 0 to 9999. + /// * month is from 1 to 12. + /// * day is from 1 to 31. + /// * hour is from 0 to 23. + /// * minute is from 0 to 59. + /// * second is from 0 to 59. + /// * millisecond is from 0 to 999. + /// * microsecond is from 0 to 999. + + LocalDateTime& assign(int tzd, double julianDay); + /// Assigns a Julian day in the time zone denoted by the + /// time zone differential in tzd. + + void swap(LocalDateTime& dateTime); + /// Swaps the LocalDateTime with another one. + + int year() const; + /// Returns the year. + + int month() const; + /// Returns the month (1 to 12). + + int week(int firstDayOfWeek = DateTime::MONDAY) const; + /// Returns the week number within the year. + /// FirstDayOfWeek should be either SUNDAY (0) or MONDAY (1). + /// The returned week number will be from 0 to 53. Week number 1 is the week + /// containing January 4. This is in accordance to ISO 8601. + /// + /// The following example assumes that firstDayOfWeek is MONDAY. For 2005, which started + /// on a Saturday, week 1 will be the week starting on Monday, January 3. + /// January 1 and 2 will fall within week 0 (or the last week of the previous year). + /// + /// For 2007, which starts on a Monday, week 1 will be the week startung on Monday, January 1. + /// There will be no week 0 in 2007. + + int day() const; + /// Returns the day witin the month (1 to 31). + + int dayOfWeek() const; + /// Returns the weekday (0 to 6, where + /// 0 = Sunday, 1 = Monday, ..., 6 = Saturday). + + int dayOfYear() const; + /// Returns the number of the day in the year. + /// January 1 is 1, February 1 is 32, etc. + + int hour() const; + /// Returns the hour (0 to 23). + + int hourAMPM() const; + /// Returns the hour (0 to 12). + + bool isAM() const; + /// Returns true if hour < 12; + + bool isPM() const; + /// Returns true if hour >= 12. + + int minute() const; + /// Returns the minute (0 to 59). + + int second() const; + /// Returns the second (0 to 59). + + int millisecond() const; + /// Returns the millisecond (0 to 999) + + int microsecond() const; + /// Returns the microsecond (0 to 999) + + double julianDay() const; + /// Returns the julian day for the date. + + int tzd() const; + /// Returns the time zone differential. + + DateTime utc() const; + /// Returns the UTC equivalent for the local date and time. + + Timestamp timestamp() const; + /// Returns the date and time expressed as a Timestamp. + + Timestamp::UtcTimeVal utcTime() const; + /// Returns the UTC equivalent for the local date and time. + + bool operator == (const LocalDateTime& dateTime) const; + bool operator != (const LocalDateTime& dateTime) const; + bool operator < (const LocalDateTime& dateTime) const; + bool operator <= (const LocalDateTime& dateTime) const; + bool operator > (const LocalDateTime& dateTime) const; + bool operator >= (const LocalDateTime& dateTime) const; + + LocalDateTime operator + (const Timespan& span) const; + LocalDateTime operator - (const Timespan& span) const; + Timespan operator - (const LocalDateTime& dateTime) const; + LocalDateTime& operator += (const Timespan& span); + LocalDateTime& operator -= (const Timespan& span); + +protected: + LocalDateTime(Timestamp::UtcTimeVal utcTime, Timestamp::TimeDiff diff, int tzd); + +private: + DateTime _dateTime; + int _tzd; + + friend class DateTimeFormatter; + friend class DateTimeParser; +}; + + +// +// inlines +// +inline int LocalDateTime::year() const +{ + return _dateTime.year(); +} + + +inline int LocalDateTime::month() const +{ + return _dateTime.month(); +} + + +inline int LocalDateTime::week(int firstDayOfWeek) const +{ + return _dateTime.week(firstDayOfWeek); +} + + +inline int LocalDateTime::day() const +{ + return _dateTime.day(); +} + + +inline int LocalDateTime::dayOfWeek() const +{ + return _dateTime.dayOfWeek(); +} + + +inline int LocalDateTime::dayOfYear() const +{ + return _dateTime.dayOfYear(); +} + + +inline int LocalDateTime::hour() const +{ + return _dateTime.hour(); +} + + +inline int LocalDateTime::hourAMPM() const +{ + return _dateTime.hourAMPM(); +} + + +inline bool LocalDateTime::isAM() const +{ + return _dateTime.isAM(); +} + + +inline bool LocalDateTime::isPM() const +{ + return _dateTime.isPM(); +} + + +inline int LocalDateTime::minute() const +{ + return _dateTime.minute(); +} + + +inline int LocalDateTime::second() const +{ + return _dateTime.second(); +} + + +inline int LocalDateTime::millisecond() const +{ + return _dateTime.millisecond(); +} + + +inline int LocalDateTime::microsecond() const +{ + return _dateTime.microsecond(); +} + + +inline double LocalDateTime::julianDay() const +{ + return _dateTime.julianDay(); +} + + +inline int LocalDateTime::tzd() const +{ + return _tzd; +} + +inline Timestamp LocalDateTime::timestamp() const +{ + return Timestamp::fromUtcTime(_dateTime.utcTime()); +} + +inline Timestamp::UtcTimeVal LocalDateTime::utcTime() const +{ + return _dateTime.utcTime() - ((Timestamp::TimeDiff) _tzd)*10000000; +} + + +inline void swap(LocalDateTime& d1, LocalDateTime& d2) +{ + d1.swap(d2); +} + + +} // namespace Poco + + +#endif // Foundation_LocalDateTime_INCLUDED diff --git a/Foundation/include/Poco/LogFile.h b/Foundation/include/Poco/LogFile.h index d088b01dd..a0187b837 100644 --- a/Foundation/include/Poco/LogFile.h +++ b/Foundation/include/Poco/LogFile.h @@ -1,115 +1,115 @@ -// -// LogFile.h -// -// $Id: //poco/1.2/Foundation/include/Poco/LogFile.h#1 $ -// -// Library: Foundation -// Package: Logging -// Module: LogFile -// -// Definition of the LogFile class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_LogFile_INCLUDED -#define Foundation_LogFile_INCLUDED - - -#include "Poco/Foundation.h" - - -#if defined(POCO_OS_FAMILY_WINDOWS) && defined(POCO_WIN32_UTF8) -#include "Poco/LogFile_WIN32U.h" -#elif defined(POCO_OS_FAMILY_WINDOWS) -#include "Poco/LogFile_WIN32.h" -#elif defined(POCO_OS_FAMILY_VMS) -#include "Poco/LogFile_VMS.h" -#else -#include "Poco/LogFile_STD.h" -#endif - - -namespace Poco { - - -class Foundation_API LogFile: public LogFileImpl - /// This class is used by FileChannel to work - /// with a log file. -{ -public: - LogFile(const std::string& path); - /// Creates the LogFile. - - ~LogFile(); - /// Destroys the LogFile. - - void write(const std::string& text); - /// Writes the given text to the log file. - - UInt64 size() const; - /// Returns the current size in bytes of the log file. - - Timestamp creationDate() const; - /// Returns the date and time the log file was created. - - const std::string& path() const; - /// Returns the path given in the constructor. -}; - - -// -// inlines -// -inline void LogFile::write(const std::string& text) -{ - writeImpl(text); -} - - -inline UInt64 LogFile::size() const -{ - return sizeImpl(); -} - - -inline Timestamp LogFile::creationDate() const -{ - return creationDateImpl(); -} - - -inline const std::string& LogFile::path() const -{ - return pathImpl(); -} - - -} // namespace Poco - - -#endif // Foundation_LogFile_INCLUDED +// +// LogFile.h +// +// $Id: //poco/1.2/Foundation/include/Poco/LogFile.h#1 $ +// +// Library: Foundation +// Package: Logging +// Module: LogFile +// +// Definition of the LogFile class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_LogFile_INCLUDED +#define Foundation_LogFile_INCLUDED + + +#include "Poco/Foundation.h" + + +#if defined(POCO_OS_FAMILY_WINDOWS) && defined(POCO_WIN32_UTF8) +#include "Poco/LogFile_WIN32U.h" +#elif defined(POCO_OS_FAMILY_WINDOWS) +#include "Poco/LogFile_WIN32.h" +#elif defined(POCO_OS_FAMILY_VMS) +#include "Poco/LogFile_VMS.h" +#else +#include "Poco/LogFile_STD.h" +#endif + + +namespace Poco { + + +class Foundation_API LogFile: public LogFileImpl + /// This class is used by FileChannel to work + /// with a log file. +{ +public: + LogFile(const std::string& path); + /// Creates the LogFile. + + ~LogFile(); + /// Destroys the LogFile. + + void write(const std::string& text); + /// Writes the given text to the log file. + + UInt64 size() const; + /// Returns the current size in bytes of the log file. + + Timestamp creationDate() const; + /// Returns the date and time the log file was created. + + const std::string& path() const; + /// Returns the path given in the constructor. +}; + + +// +// inlines +// +inline void LogFile::write(const std::string& text) +{ + writeImpl(text); +} + + +inline UInt64 LogFile::size() const +{ + return sizeImpl(); +} + + +inline Timestamp LogFile::creationDate() const +{ + return creationDateImpl(); +} + + +inline const std::string& LogFile::path() const +{ + return pathImpl(); +} + + +} // namespace Poco + + +#endif // Foundation_LogFile_INCLUDED diff --git a/Foundation/include/Poco/LogFile_STD.h b/Foundation/include/Poco/LogFile_STD.h index 1cc003144..65dda489a 100644 --- a/Foundation/include/Poco/LogFile_STD.h +++ b/Foundation/include/Poco/LogFile_STD.h @@ -1,74 +1,74 @@ -// -// LogFile_STD.h -// -// $Id: //poco/1.2/Foundation/include/Poco/LogFile_STD.h#1 $ -// -// Library: Foundation -// Package: Logging -// Module: LogFile -// -// Definition of the LogFileImpl class using iostreams. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_LogFile_STD_INCLUDED -#define Foundation_LogFile_STD_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/Timestamp.h" -#include - - -namespace Poco { - - -class Foundation_API LogFileImpl - /// The implementation of LogFile for Windows. - /// The native filesystem APIs are used for - /// total control over locking behavior. -{ -public: - LogFileImpl(const std::string& path); - ~LogFileImpl(); - void writeImpl(const std::string& text); - UInt64 sizeImpl() const; - Timestamp creationDateImpl() const; - const std::string& pathImpl() const; - -private: - std::string _path; - mutable std::ofstream _str; - Timestamp _creationDate; -}; - - -} // namespace Poco - - -#endif // Foundation_LogFile_STD_INCLUDED +// +// LogFile_STD.h +// +// $Id: //poco/1.2/Foundation/include/Poco/LogFile_STD.h#1 $ +// +// Library: Foundation +// Package: Logging +// Module: LogFile +// +// Definition of the LogFileImpl class using iostreams. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_LogFile_STD_INCLUDED +#define Foundation_LogFile_STD_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Timestamp.h" +#include + + +namespace Poco { + + +class Foundation_API LogFileImpl + /// The implementation of LogFile for Windows. + /// The native filesystem APIs are used for + /// total control over locking behavior. +{ +public: + LogFileImpl(const std::string& path); + ~LogFileImpl(); + void writeImpl(const std::string& text); + UInt64 sizeImpl() const; + Timestamp creationDateImpl() const; + const std::string& pathImpl() const; + +private: + std::string _path; + mutable std::ofstream _str; + Timestamp _creationDate; +}; + + +} // namespace Poco + + +#endif // Foundation_LogFile_STD_INCLUDED diff --git a/Foundation/include/Poco/LogFile_VMS.h b/Foundation/include/Poco/LogFile_VMS.h index 75f2c4cf7..ca6918b3c 100644 --- a/Foundation/include/Poco/LogFile_VMS.h +++ b/Foundation/include/Poco/LogFile_VMS.h @@ -1,75 +1,75 @@ -// -// LogFile_VMS.h -// -// $Id: //poco/1.2/Foundation/include/Poco/LogFile_VMS.h#1 $ -// -// Library: Foundation -// Package: Logging -// Module: LogFile -// -// Definition of the LogFileImpl class using C I/O with OpenVMS extensions. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_LogFile_VMS_INCLUDED -#define Foundation_LogFile_VMS_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/Timestamp.h" -#include - - -namespace Poco { - - -class Foundation_API LogFileImpl - /// The implementation of LogFile for OpenVMS. - /// The C Standard Library functions for file I/O - /// are used with OpenVMS-specific extensions to - /// control sharing and locking behavior. -{ -public: - LogFileImpl(const std::string& path); - ~LogFileImpl(); - void writeImpl(const std::string& text); - UInt64 sizeImpl() const; - Timestamp creationDateImpl() const; - const std::string& pathImpl() const; - -private: - std::string _path; - mutable FILE* _file; - Timestamp _creationDate; -}; - - -} // namespace Poco - - -#endif // Foundation_LogFile_VMS_INCLUDED +// +// LogFile_VMS.h +// +// $Id: //poco/1.2/Foundation/include/Poco/LogFile_VMS.h#1 $ +// +// Library: Foundation +// Package: Logging +// Module: LogFile +// +// Definition of the LogFileImpl class using C I/O with OpenVMS extensions. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_LogFile_VMS_INCLUDED +#define Foundation_LogFile_VMS_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Timestamp.h" +#include + + +namespace Poco { + + +class Foundation_API LogFileImpl + /// The implementation of LogFile for OpenVMS. + /// The C Standard Library functions for file I/O + /// are used with OpenVMS-specific extensions to + /// control sharing and locking behavior. +{ +public: + LogFileImpl(const std::string& path); + ~LogFileImpl(); + void writeImpl(const std::string& text); + UInt64 sizeImpl() const; + Timestamp creationDateImpl() const; + const std::string& pathImpl() const; + +private: + std::string _path; + mutable FILE* _file; + Timestamp _creationDate; +}; + + +} // namespace Poco + + +#endif // Foundation_LogFile_VMS_INCLUDED diff --git a/Foundation/include/Poco/LogFile_WIN32.h b/Foundation/include/Poco/LogFile_WIN32.h index f0b162867..597cd35b0 100644 --- a/Foundation/include/Poco/LogFile_WIN32.h +++ b/Foundation/include/Poco/LogFile_WIN32.h @@ -1,74 +1,74 @@ -// -// LogFile_WIN32.h -// -// $Id: //poco/1.2/Foundation/include/Poco/LogFile_WIN32.h#1 $ -// -// Library: Foundation -// Package: Logging -// Module: LogFile -// -// Definition of the LogFileImpl class using the Windows file APIs. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_LogFile_WIN32_INCLUDED -#define Foundation_LogFile_WIN32_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/Timestamp.h" -#include - - -namespace Poco { - - -class Foundation_API LogFileImpl - /// The implementation of LogFile for Windows. - /// The native filesystem APIs are used for - /// total control over locking behavior. -{ -public: - LogFileImpl(const std::string& path); - ~LogFileImpl(); - void writeImpl(const std::string& text); - UInt64 sizeImpl() const; - Timestamp creationDateImpl() const; - const std::string& pathImpl() const; - -private: - std::string _path; - HANDLE _hFile; - Timestamp _creationDate; -}; - - -} // namespace Poco - - -#endif // Foundation_LogFile_WIN32_INCLUDED +// +// LogFile_WIN32.h +// +// $Id: //poco/1.2/Foundation/include/Poco/LogFile_WIN32.h#1 $ +// +// Library: Foundation +// Package: Logging +// Module: LogFile +// +// Definition of the LogFileImpl class using the Windows file APIs. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_LogFile_WIN32_INCLUDED +#define Foundation_LogFile_WIN32_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Timestamp.h" +#include + + +namespace Poco { + + +class Foundation_API LogFileImpl + /// The implementation of LogFile for Windows. + /// The native filesystem APIs are used for + /// total control over locking behavior. +{ +public: + LogFileImpl(const std::string& path); + ~LogFileImpl(); + void writeImpl(const std::string& text); + UInt64 sizeImpl() const; + Timestamp creationDateImpl() const; + const std::string& pathImpl() const; + +private: + std::string _path; + HANDLE _hFile; + Timestamp _creationDate; +}; + + +} // namespace Poco + + +#endif // Foundation_LogFile_WIN32_INCLUDED diff --git a/Foundation/include/Poco/LogFile_WIN32U.h b/Foundation/include/Poco/LogFile_WIN32U.h index 17d877121..897cd40ab 100644 --- a/Foundation/include/Poco/LogFile_WIN32U.h +++ b/Foundation/include/Poco/LogFile_WIN32U.h @@ -1,74 +1,74 @@ -// -// LogFile_WIN32U.h -// -// $Id: //poco/1.2/Foundation/include/Poco/LogFile_WIN32U.h#1 $ -// -// Library: Foundation -// Package: Logging -// Module: LogFile -// -// Definition of the LogFileImpl class using the Windows file APIs. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_LogFile_WIN32U_INCLUDED -#define Foundation_LogFile_WIN32U_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/Timestamp.h" -#include - - -namespace Poco { - - -class Foundation_API LogFileImpl - /// The implementation of LogFile for Windows. - /// The native filesystem APIs are used for - /// total control over locking behavior. -{ -public: - LogFileImpl(const std::string& path); - ~LogFileImpl(); - void writeImpl(const std::string& text); - UInt64 sizeImpl() const; - Timestamp creationDateImpl() const; - const std::string& pathImpl() const; - -private: - std::string _path; - HANDLE _hFile; - Timestamp _creationDate; -}; - - -} // namespace Poco - - -#endif // Foundation_LogFile_WIN32U_INCLUDED +// +// LogFile_WIN32U.h +// +// $Id: //poco/1.2/Foundation/include/Poco/LogFile_WIN32U.h#1 $ +// +// Library: Foundation +// Package: Logging +// Module: LogFile +// +// Definition of the LogFileImpl class using the Windows file APIs. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_LogFile_WIN32U_INCLUDED +#define Foundation_LogFile_WIN32U_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Timestamp.h" +#include + + +namespace Poco { + + +class Foundation_API LogFileImpl + /// The implementation of LogFile for Windows. + /// The native filesystem APIs are used for + /// total control over locking behavior. +{ +public: + LogFileImpl(const std::string& path); + ~LogFileImpl(); + void writeImpl(const std::string& text); + UInt64 sizeImpl() const; + Timestamp creationDateImpl() const; + const std::string& pathImpl() const; + +private: + std::string _path; + HANDLE _hFile; + Timestamp _creationDate; +}; + + +} // namespace Poco + + +#endif // Foundation_LogFile_WIN32U_INCLUDED diff --git a/Foundation/include/Poco/LogStream.h b/Foundation/include/Poco/LogStream.h index 86b4564ec..5216bdebd 100644 --- a/Foundation/include/Poco/LogStream.h +++ b/Foundation/include/Poco/LogStream.h @@ -1,166 +1,166 @@ -// -// LogStream.h -// -// $Id: //poco/1.2/Foundation/include/Poco/LogStream.h#1 $ -// -// Library: Foundation -// Package: Logging -// Module: LogStream -// -// Definition of the LogStream class. -// -// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_LogStream_INCLUDED -#define Foundation_LogStream_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/Logger.h" -#include "Poco/UnbufferedStreamBuf.h" -#include - - -namespace Poco { - - -class Foundation_API LogStreamBuf: public UnbufferedStreamBuf - /// This class implements a streambuf interface - /// to a Logger. - /// - /// The streambuf appends all characters written to it - /// to a string. As soon as a CR or LF (std::endl) is written, - /// the string is sent to the Logger, with the set - /// priority. -{ -public: - LogStreamBuf(Logger& logger, Message::Priority priority); - /// Creates the LogStream. - - ~LogStreamBuf(); - /// Destroys the LogStream. - - void setPriority(Message::Priority priority); - /// Sets the priority for log messages. - - Message::Priority getPriority() const; - /// Returns the priority for log messages. - -private: - int writeToDevice(char c); - -private: - Logger& _logger; - Message::Priority _priority; - std::string _message; -}; - - -class Foundation_API LogIOS: public virtual std::ios - /// The base class for LogStream. - /// - /// This class is needed to ensure the correct initialization - /// order of the stream buffer and base classes. -{ -public: - LogIOS(Logger& logger, Message::Priority priority); - ~LogIOS(); - LogStreamBuf* rdbuf(); - -protected: - LogStreamBuf _buf; -}; - - -class Foundation_API LogStream: public LogIOS, public std::ostream - /// This class implements an ostream interface - /// to a Logger. - /// - /// The stream's buffer appends all characters written to it - /// to a string. As soon as a CR or LF (std::endl) is written, - /// the string is sent to the Logger, with the current - /// priority. - /// - /// Usage example: - /// LogStream ls(someLogger); - /// ls << "Some informational message" << std::endl; - /// ls.error() << "Some error message" << std::endl; -{ -public: - LogStream(Logger& logger, Message::Priority priority = Message::PRIO_INFORMATION); - /// Creates the LogStream, using the given logger and priority. - - LogStream(const std::string& loggerName, Message::Priority priority = Message::PRIO_INFORMATION); - /// Creates the LogStream, using the logger identified - /// by loggerName, and sets the priority. - - ~LogStream(); - /// Destroys the LogStream. - - LogStream& fatal(); - /// Sets the priority for log messages to Message::PRIO_FATAL. - - LogStream& critical(); - /// Sets the priority for log messages to Message::PRIO_CRITICAL. - - LogStream& error(); - /// Sets the priority for log messages to Message::PRIO_ERROR. - - LogStream& warning(); - /// Sets the priority for log messages to Message::PRIO_WARNING. - - LogStream& notice(); - /// Sets the priority for log messages to Message::PRIO_NOTICE. - - LogStream& information(); - /// Sets the priority for log messages to Message::PRIO_INFORMATION. - - LogStream& debug(); - /// Sets the priority for log messages to Message::PRIO_DEBUG. - - LogStream& trace(); - /// Sets the priority for log messages to Message::PRIO_TRACE. - - LogStream& priority(Message::Priority priority); - /// Sets the priority for log messages. -}; - - -// -// inlines -// -inline Message::Priority LogStreamBuf::getPriority() const -{ - return _priority; -} - - -} // namespace Poco - - -#endif // Foundation_LogStream_INCLUDED +// +// LogStream.h +// +// $Id: //poco/1.2/Foundation/include/Poco/LogStream.h#1 $ +// +// Library: Foundation +// Package: Logging +// Module: LogStream +// +// Definition of the LogStream class. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_LogStream_INCLUDED +#define Foundation_LogStream_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Logger.h" +#include "Poco/UnbufferedStreamBuf.h" +#include + + +namespace Poco { + + +class Foundation_API LogStreamBuf: public UnbufferedStreamBuf + /// This class implements a streambuf interface + /// to a Logger. + /// + /// The streambuf appends all characters written to it + /// to a string. As soon as a CR or LF (std::endl) is written, + /// the string is sent to the Logger, with the set + /// priority. +{ +public: + LogStreamBuf(Logger& logger, Message::Priority priority); + /// Creates the LogStream. + + ~LogStreamBuf(); + /// Destroys the LogStream. + + void setPriority(Message::Priority priority); + /// Sets the priority for log messages. + + Message::Priority getPriority() const; + /// Returns the priority for log messages. + +private: + int writeToDevice(char c); + +private: + Logger& _logger; + Message::Priority _priority; + std::string _message; +}; + + +class Foundation_API LogIOS: public virtual std::ios + /// The base class for LogStream. + /// + /// This class is needed to ensure the correct initialization + /// order of the stream buffer and base classes. +{ +public: + LogIOS(Logger& logger, Message::Priority priority); + ~LogIOS(); + LogStreamBuf* rdbuf(); + +protected: + LogStreamBuf _buf; +}; + + +class Foundation_API LogStream: public LogIOS, public std::ostream + /// This class implements an ostream interface + /// to a Logger. + /// + /// The stream's buffer appends all characters written to it + /// to a string. As soon as a CR or LF (std::endl) is written, + /// the string is sent to the Logger, with the current + /// priority. + /// + /// Usage example: + /// LogStream ls(someLogger); + /// ls << "Some informational message" << std::endl; + /// ls.error() << "Some error message" << std::endl; +{ +public: + LogStream(Logger& logger, Message::Priority priority = Message::PRIO_INFORMATION); + /// Creates the LogStream, using the given logger and priority. + + LogStream(const std::string& loggerName, Message::Priority priority = Message::PRIO_INFORMATION); + /// Creates the LogStream, using the logger identified + /// by loggerName, and sets the priority. + + ~LogStream(); + /// Destroys the LogStream. + + LogStream& fatal(); + /// Sets the priority for log messages to Message::PRIO_FATAL. + + LogStream& critical(); + /// Sets the priority for log messages to Message::PRIO_CRITICAL. + + LogStream& error(); + /// Sets the priority for log messages to Message::PRIO_ERROR. + + LogStream& warning(); + /// Sets the priority for log messages to Message::PRIO_WARNING. + + LogStream& notice(); + /// Sets the priority for log messages to Message::PRIO_NOTICE. + + LogStream& information(); + /// Sets the priority for log messages to Message::PRIO_INFORMATION. + + LogStream& debug(); + /// Sets the priority for log messages to Message::PRIO_DEBUG. + + LogStream& trace(); + /// Sets the priority for log messages to Message::PRIO_TRACE. + + LogStream& priority(Message::Priority priority); + /// Sets the priority for log messages. +}; + + +// +// inlines +// +inline Message::Priority LogStreamBuf::getPriority() const +{ + return _priority; +} + + +} // namespace Poco + + +#endif // Foundation_LogStream_INCLUDED diff --git a/Foundation/include/Poco/Logger.h b/Foundation/include/Poco/Logger.h index a7f78517c..aa7a6201c 100644 --- a/Foundation/include/Poco/Logger.h +++ b/Foundation/include/Poco/Logger.h @@ -1,483 +1,483 @@ -// -// Logger.h -// -// $Id: //poco/1.2/Foundation/include/Poco/Logger.h#2 $ -// -// Library: Foundation -// Package: Logging -// Module: Logger -// -// Definition of the Logger class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_Logger_INCLUDED -#define Foundation_Logger_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/Channel.h" -#include "Poco/Message.h" -#include -#include - - -namespace Poco { - - -class Exception; - - -class Foundation_API Logger: public Channel - /// Logger is a special Channel that acts as the main - /// entry point into the logging framework. - /// - /// An application uses instances of the Logger class to generate its log messages - /// and send them on their way to their final destination. Logger instances - /// are organized in a hierarchical, tree-like manner and are maintained by - /// the framework. Every Logger object has exactly one direct ancestor, with - /// the exception of the root logger. A newly created logger inherits its properties - - /// channel and level - from its direct ancestor. Every logger is connected - /// to a channel, to which it passes on its messages. Furthermore, every logger - /// has a log level, which is used for filtering messages based on their priority. - /// Only messages with a priority equal to or higher than the specified level - /// are passed on. For example, if the level of a logger is set to three (PRIO_ERROR), - /// only messages with priority PRIO_ERROR, PRIO_CRITICAL and PRIO_FATAL will - /// propagate. If the level is set to zero, the logger is effectively disabled. - /// - /// The name of a logger determines the logger's place within the logger hierarchy. - /// The name of the root logger is always "", the empty string. For all other - /// loggers, the name is made up of one or more components, separated by a period. - /// For example, the loggers with the name HTTPServer.RequestHandler and HTTPServer.Listener - /// are descendants of the logger HTTPServer, which itself is a descendant of - /// the root logger. There is not limit as to how deep - /// the logger hierarchy can become. Once a logger has been created and it has - /// inherited the channel and level from its ancestor, it loses the connection - /// to it. So changes to the level or channel of a logger do not affect its - /// descendants. This greatly simplifies the implementation of the framework - /// and is no real restriction, because almost always levels and channels are - /// set up at application startup and never changed afterwards. Nevertheless, - /// there are methods to simultaneously change the level and channel of all - /// loggers in a certain hierarchy. -{ -public: - const std::string& name() const; - /// Returns the name of the logger, which is set as the - /// message source on all messages created by the logger. - - void setChannel(Channel* pChannel); - /// Attaches the given Channel to the Logger. - - Channel* getChannel() const; - /// Returns the Channel attached to the logger. - - void setLevel(int level); - /// Sets the Logger's log level. - - int getLevel() const; - /// Returns the Logger's log level. - - void setLevel(const std::string& level); - /// Sets the Logger's log level using a symbolic value. - /// - /// Valid values are: - /// - fatal - /// - critical - /// - error - /// - warning - /// - notice - /// - information - /// - debug - /// - trace - - void setProperty(const std::string& name, const std::string& value); - /// Sets or changes a configuration property. - /// - /// Only the "channel" and "level" properties are supported, which allow - /// setting the target channel and log level, respectively, via the LoggingRegistry. - /// The "channel" and "level" properties are set-only. - - void log(const Message& msg); - /// Logs the given message if its priority is - /// greater than or equal to the Logger's log level. - - void log(const Exception& exc); - /// Logs the given exception with priority PRIO_ERROR. - - void fatal(const std::string& msg); - /// If the Logger's log level is at least PRIO_FATAL, - /// creates a Message with priority PRIO_FATAL - /// and the given message text and sends it - /// to the attached channel. - - void critical(const std::string& msg); - /// If the Logger's log level is at least PRIO_CRITICAL, - /// creates a Message with priority PRIO_CRITICAL - /// and the given message text and sends it - /// to the attached channel. - - void error(const std::string& msg); - /// If the Logger's log level is at least PRIO_ERROR, - /// creates a Message with priority PRIO_ERROR - /// and the given message text and sends it - /// to the attached channel. - - void warning(const std::string& msg); - /// If the Logger's log level is at least PRIO_WARNING, - /// creates a Message with priority PRIO_WARNING - /// and the given message text and sends it - /// to the attached channel. - - void notice(const std::string& msg); - /// If the Logger's log level is at least PRIO_NOTICE, - /// creates a Message with priority PRIO_NOTICE - /// and the given message text and sends it - /// to the attached channel. - - void information(const std::string& msg); - /// If the Logger's log level is at least PRIO_INFORMATION, - /// creates a Message with priority PRIO_INFORMATION - /// and the given message text and sends it - /// to the attached channel. - - void debug(const std::string& msg); - /// If the Logger's log level is at least PRIO_DEBUG, - /// creates a Message with priority PRIO_DEBUG - /// and the given message text and sends it - /// to the attached channel. - - void trace(const std::string& msg); - /// If the Logger's log level is at least PRIO_TRACE, - /// creates a Message with priority PRIO_TRACE - /// and the given message text and sends it - /// to the attached channel. - - void dump(const std::string& msg, const void* buffer, int length, Message::Priority prio = Message::PRIO_DEBUG); - /// Logs the given message, followed by the data in buffer. - /// - /// The data in buffer is written in canonical hex+ASCII form: - /// Offset (4 bytes) in hexadecimal, followed by sixteen - /// space-separated, two column, hexadecimal bytes, - /// followed by the same sixteen bytes as ASCII characters. - /// For bytes outside the range 32 .. 127, a dot is printed. - - bool is(int level) const; - /// Returns true if at least the given log level is set. - - bool fatal() const; - /// Returns true if the log level is at least PRIO_FATAL. - - bool critical() const; - /// Returns true if the log level is at least PRIO_CRITICAL. - - bool error() const; - /// Returns true if the log level is at least PRIO_ERROR. - - bool warning() const; - /// Returns true if the log level is at least PRIO_WARNING. - - bool notice() const; - /// Returns true if the log level is at least PRIO_NOTICE. - - bool information() const; - /// Returns true if the log level is at least PRIO_INFORMATION. - - bool debug() const; - /// Returns true if the log level is at least PRIO_DEBUG. - - bool trace() const; - /// Returns true if the log level is at least PRIO_TRACE. - - static std::string format(const std::string& fmt, const std::string& arg); - /// Replaces all occurences of $0 in fmt with the string given in arg and - /// returns the result. To include a dollar sign in the result string, - /// specify two dollar signs ($$) in the format string. - - static std::string format(const std::string& fmt, const std::string& arg0, const std::string& arg1); - /// Replaces all occurences of $ in fmt with the string given in arg and - /// returns the result. To include a dollar sign in the result string, - /// specify two dollar signs ($$) in the format string. - - static std::string format(const std::string& fmt, const std::string& arg0, const std::string& arg1, const std::string& arg2); - /// Replaces all occurences of $ in fmt with the string given in arg and - /// returns the result. To include a dollar sign in the result string, - /// specify two dollar signs ($$) in the format string. - - static std::string format(const std::string& fmt, const std::string& arg0, const std::string& arg1, const std::string& arg2, const std::string& arg3); - /// Replaces all occurences of $ in fmt with the string given in arg and - /// returns the result. To include a dollar sign in the result string, - /// specify two dollar signs ($$) in the format string. - - static void setLevel(const std::string& name, int level); - /// Sets the given log level on all loggers that are - /// descendants of the Logger with the given name. - - static void setChannel(const std::string& name, Channel* pChannel); - /// Attaches the given Channel to all loggers that are - /// descendants of the Logger with the given name. - - static void setProperty(const std::string& loggerName, const std::string& propertyName, const std::string& value); - /// Sets or changes a configuration property for all loggers - /// that are descendants of the Logger with the given name. - - static Logger& get(const std::string& name); - /// Returns a reference to the Logger with the given name. - /// If the Logger does not yet exist, it is created, based - /// on its parent logger. - - static Logger& unsafeGet(const std::string& name); - /// Returns a reference to the Logger with the given name. - /// If the Logger does not yet exist, it is created, based - /// on its parent logger. - /// - /// WARNING: This method is not thread safe. You should - /// probably use get() instead. - /// The only time this method should be used is during - /// program initialization, when only one thread is running. - - static Logger& create(const std::string& name, Channel* pChannel, int level = Message::PRIO_INFORMATION); - /// Creates and returns a reference to a Logger with the - /// given name. The Logger's Channel and log level as set as - /// specified. - - static Logger& root(); - /// Returns a reference to the root logger, which is the ultimate - /// ancestor of all Loggers. - - static Logger* has(const std::string& name); - /// Returns a pointer to the Logger with the given name if it - /// exists, or a null pointer otherwse. - - static void destroy(const std::string& name); - /// Destroys the logger with the specified name. Does nothing - /// if the logger is not found. - /// - /// After a logger has been destroyed, all references to it - /// become invalid. - - static void shutdown(); - /// Shuts down the logging framework and releases all - /// Loggers. - - static void names(std::vector& names); - /// Fills the given vector with the names - /// of all currently defined loggers. - - static const std::string ROOT; /// The name of the root logger (""). - -protected: - typedef std::map LoggerMap; - - Logger(const std::string& name, Channel* pChannel, int level); - ~Logger(); - - void log(const std::string& text, Message::Priority prio); - - static std::string format(const std::string& fmt, int argc, std::string argv[]); - static void formatDump(std::string& message, const void* buffer, int length); - static Logger& parent(const std::string& name); - static void add(Logger* pLogger); - static Logger* find(const std::string& name); - -private: - Logger(); - Logger(const Logger&); - Logger& operator = (const Logger&); - - std::string _name; - Channel* _pChannel; - int _level; - - static LoggerMap* _pLoggerMap; - static Mutex _mapMtx; -}; - - -// -// convenience macros -// -#define poco_fatal(logger, msg) \ - if ((logger).fatal()) (logger).fatal(msg) else (void) 0 - -#define poco_critical(logger, msg) \ - if ((logger).critical()) (logger).critical(msg) else (void) 0 - -#define poco_error(logger, msg) \ - if ((logger).error()) (logger).error(msg) else (void) 0 - -#define poco_warning(logger, msg) \ - if ((logger).warning()) (logger).warning(msg) else (void) 0 - -#define poco_notice(logger, msg) \ - if ((logger).notice()) (logger).notice(msg) else (void) 0 - -#define poco_information(logger, msg) \ - if ((logger).information()) (logger).information(msg) else (void) 0 - -#if defined(_DEBUG) - #define poco_debug(logger, msg) \ - if ((logger).debug()) (logger).debug(msg) else (void) 0 - - #define poco_trace(logger, msg) \ - if ((logger).trace()) (logger).trace(msg) else (void) 0 -#else - #define poco_debug(logger, msg) - #define poco_trace(logger, msg) -#endif - - -// -// inlines -// -inline const std::string& Logger::name() const -{ - return _name; -} - - -inline int Logger::getLevel() const -{ - return _level; -} - - -inline void Logger::log(const std::string& text, Message::Priority prio) -{ - if (_level >= prio && _pChannel) - { - _pChannel->log(Message(_name, text, prio)); - } -} - - -inline void Logger::fatal(const std::string& msg) -{ - log(msg, Message::PRIO_FATAL); -} - - -inline void Logger::critical(const std::string& msg) -{ - log(msg, Message::PRIO_CRITICAL); -} - - -inline void Logger::error(const std::string& msg) -{ - log(msg, Message::PRIO_ERROR); -} - - -inline void Logger::warning(const std::string& msg) -{ - log(msg, Message::PRIO_WARNING); -} - - -inline void Logger::notice(const std::string& msg) -{ - log(msg, Message::PRIO_NOTICE); -} - - -inline void Logger::information(const std::string& msg) -{ - log(msg, Message::PRIO_INFORMATION); -} - - -inline void Logger::debug(const std::string& msg) -{ - log(msg, Message::PRIO_DEBUG); -} - - -inline void Logger::trace(const std::string& msg) -{ - log(msg, Message::PRIO_TRACE); -} - - -inline bool Logger::is(int level) const -{ - return _level >= level; -} - - -inline bool Logger::fatal() const -{ - return _level >= Message::PRIO_FATAL; -} - - -inline bool Logger::critical() const -{ - return _level >= Message::PRIO_CRITICAL; -} - - -inline bool Logger::error() const -{ - return _level >= Message::PRIO_ERROR; -} - - -inline bool Logger::warning() const -{ - return _level >= Message::PRIO_WARNING; -} - - -inline bool Logger::notice() const -{ - return _level >= Message::PRIO_NOTICE; -} - - -inline bool Logger::information() const -{ - return _level >= Message::PRIO_INFORMATION; -} - - -inline bool Logger::debug() const -{ - return _level >= Message::PRIO_DEBUG; -} - - -inline bool Logger::trace() const -{ - return _level >= Message::PRIO_TRACE; -} - - -} // namespace Poco - - -#endif // Foundation_Logger_INCLUDED +// +// Logger.h +// +// $Id: //poco/1.2/Foundation/include/Poco/Logger.h#2 $ +// +// Library: Foundation +// Package: Logging +// Module: Logger +// +// Definition of the Logger class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_Logger_INCLUDED +#define Foundation_Logger_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Channel.h" +#include "Poco/Message.h" +#include +#include + + +namespace Poco { + + +class Exception; + + +class Foundation_API Logger: public Channel + /// Logger is a special Channel that acts as the main + /// entry point into the logging framework. + /// + /// An application uses instances of the Logger class to generate its log messages + /// and send them on their way to their final destination. Logger instances + /// are organized in a hierarchical, tree-like manner and are maintained by + /// the framework. Every Logger object has exactly one direct ancestor, with + /// the exception of the root logger. A newly created logger inherits its properties - + /// channel and level - from its direct ancestor. Every logger is connected + /// to a channel, to which it passes on its messages. Furthermore, every logger + /// has a log level, which is used for filtering messages based on their priority. + /// Only messages with a priority equal to or higher than the specified level + /// are passed on. For example, if the level of a logger is set to three (PRIO_ERROR), + /// only messages with priority PRIO_ERROR, PRIO_CRITICAL and PRIO_FATAL will + /// propagate. If the level is set to zero, the logger is effectively disabled. + /// + /// The name of a logger determines the logger's place within the logger hierarchy. + /// The name of the root logger is always "", the empty string. For all other + /// loggers, the name is made up of one or more components, separated by a period. + /// For example, the loggers with the name HTTPServer.RequestHandler and HTTPServer.Listener + /// are descendants of the logger HTTPServer, which itself is a descendant of + /// the root logger. There is not limit as to how deep + /// the logger hierarchy can become. Once a logger has been created and it has + /// inherited the channel and level from its ancestor, it loses the connection + /// to it. So changes to the level or channel of a logger do not affect its + /// descendants. This greatly simplifies the implementation of the framework + /// and is no real restriction, because almost always levels and channels are + /// set up at application startup and never changed afterwards. Nevertheless, + /// there are methods to simultaneously change the level and channel of all + /// loggers in a certain hierarchy. +{ +public: + const std::string& name() const; + /// Returns the name of the logger, which is set as the + /// message source on all messages created by the logger. + + void setChannel(Channel* pChannel); + /// Attaches the given Channel to the Logger. + + Channel* getChannel() const; + /// Returns the Channel attached to the logger. + + void setLevel(int level); + /// Sets the Logger's log level. + + int getLevel() const; + /// Returns the Logger's log level. + + void setLevel(const std::string& level); + /// Sets the Logger's log level using a symbolic value. + /// + /// Valid values are: + /// - fatal + /// - critical + /// - error + /// - warning + /// - notice + /// - information + /// - debug + /// - trace + + void setProperty(const std::string& name, const std::string& value); + /// Sets or changes a configuration property. + /// + /// Only the "channel" and "level" properties are supported, which allow + /// setting the target channel and log level, respectively, via the LoggingRegistry. + /// The "channel" and "level" properties are set-only. + + void log(const Message& msg); + /// Logs the given message if its priority is + /// greater than or equal to the Logger's log level. + + void log(const Exception& exc); + /// Logs the given exception with priority PRIO_ERROR. + + void fatal(const std::string& msg); + /// If the Logger's log level is at least PRIO_FATAL, + /// creates a Message with priority PRIO_FATAL + /// and the given message text and sends it + /// to the attached channel. + + void critical(const std::string& msg); + /// If the Logger's log level is at least PRIO_CRITICAL, + /// creates a Message with priority PRIO_CRITICAL + /// and the given message text and sends it + /// to the attached channel. + + void error(const std::string& msg); + /// If the Logger's log level is at least PRIO_ERROR, + /// creates a Message with priority PRIO_ERROR + /// and the given message text and sends it + /// to the attached channel. + + void warning(const std::string& msg); + /// If the Logger's log level is at least PRIO_WARNING, + /// creates a Message with priority PRIO_WARNING + /// and the given message text and sends it + /// to the attached channel. + + void notice(const std::string& msg); + /// If the Logger's log level is at least PRIO_NOTICE, + /// creates a Message with priority PRIO_NOTICE + /// and the given message text and sends it + /// to the attached channel. + + void information(const std::string& msg); + /// If the Logger's log level is at least PRIO_INFORMATION, + /// creates a Message with priority PRIO_INFORMATION + /// and the given message text and sends it + /// to the attached channel. + + void debug(const std::string& msg); + /// If the Logger's log level is at least PRIO_DEBUG, + /// creates a Message with priority PRIO_DEBUG + /// and the given message text and sends it + /// to the attached channel. + + void trace(const std::string& msg); + /// If the Logger's log level is at least PRIO_TRACE, + /// creates a Message with priority PRIO_TRACE + /// and the given message text and sends it + /// to the attached channel. + + void dump(const std::string& msg, const void* buffer, int length, Message::Priority prio = Message::PRIO_DEBUG); + /// Logs the given message, followed by the data in buffer. + /// + /// The data in buffer is written in canonical hex+ASCII form: + /// Offset (4 bytes) in hexadecimal, followed by sixteen + /// space-separated, two column, hexadecimal bytes, + /// followed by the same sixteen bytes as ASCII characters. + /// For bytes outside the range 32 .. 127, a dot is printed. + + bool is(int level) const; + /// Returns true if at least the given log level is set. + + bool fatal() const; + /// Returns true if the log level is at least PRIO_FATAL. + + bool critical() const; + /// Returns true if the log level is at least PRIO_CRITICAL. + + bool error() const; + /// Returns true if the log level is at least PRIO_ERROR. + + bool warning() const; + /// Returns true if the log level is at least PRIO_WARNING. + + bool notice() const; + /// Returns true if the log level is at least PRIO_NOTICE. + + bool information() const; + /// Returns true if the log level is at least PRIO_INFORMATION. + + bool debug() const; + /// Returns true if the log level is at least PRIO_DEBUG. + + bool trace() const; + /// Returns true if the log level is at least PRIO_TRACE. + + static std::string format(const std::string& fmt, const std::string& arg); + /// Replaces all occurences of $0 in fmt with the string given in arg and + /// returns the result. To include a dollar sign in the result string, + /// specify two dollar signs ($$) in the format string. + + static std::string format(const std::string& fmt, const std::string& arg0, const std::string& arg1); + /// Replaces all occurences of $ in fmt with the string given in arg and + /// returns the result. To include a dollar sign in the result string, + /// specify two dollar signs ($$) in the format string. + + static std::string format(const std::string& fmt, const std::string& arg0, const std::string& arg1, const std::string& arg2); + /// Replaces all occurences of $ in fmt with the string given in arg and + /// returns the result. To include a dollar sign in the result string, + /// specify two dollar signs ($$) in the format string. + + static std::string format(const std::string& fmt, const std::string& arg0, const std::string& arg1, const std::string& arg2, const std::string& arg3); + /// Replaces all occurences of $ in fmt with the string given in arg and + /// returns the result. To include a dollar sign in the result string, + /// specify two dollar signs ($$) in the format string. + + static void setLevel(const std::string& name, int level); + /// Sets the given log level on all loggers that are + /// descendants of the Logger with the given name. + + static void setChannel(const std::string& name, Channel* pChannel); + /// Attaches the given Channel to all loggers that are + /// descendants of the Logger with the given name. + + static void setProperty(const std::string& loggerName, const std::string& propertyName, const std::string& value); + /// Sets or changes a configuration property for all loggers + /// that are descendants of the Logger with the given name. + + static Logger& get(const std::string& name); + /// Returns a reference to the Logger with the given name. + /// If the Logger does not yet exist, it is created, based + /// on its parent logger. + + static Logger& unsafeGet(const std::string& name); + /// Returns a reference to the Logger with the given name. + /// If the Logger does not yet exist, it is created, based + /// on its parent logger. + /// + /// WARNING: This method is not thread safe. You should + /// probably use get() instead. + /// The only time this method should be used is during + /// program initialization, when only one thread is running. + + static Logger& create(const std::string& name, Channel* pChannel, int level = Message::PRIO_INFORMATION); + /// Creates and returns a reference to a Logger with the + /// given name. The Logger's Channel and log level as set as + /// specified. + + static Logger& root(); + /// Returns a reference to the root logger, which is the ultimate + /// ancestor of all Loggers. + + static Logger* has(const std::string& name); + /// Returns a pointer to the Logger with the given name if it + /// exists, or a null pointer otherwse. + + static void destroy(const std::string& name); + /// Destroys the logger with the specified name. Does nothing + /// if the logger is not found. + /// + /// After a logger has been destroyed, all references to it + /// become invalid. + + static void shutdown(); + /// Shuts down the logging framework and releases all + /// Loggers. + + static void names(std::vector& names); + /// Fills the given vector with the names + /// of all currently defined loggers. + + static const std::string ROOT; /// The name of the root logger (""). + +protected: + typedef std::map LoggerMap; + + Logger(const std::string& name, Channel* pChannel, int level); + ~Logger(); + + void log(const std::string& text, Message::Priority prio); + + static std::string format(const std::string& fmt, int argc, std::string argv[]); + static void formatDump(std::string& message, const void* buffer, int length); + static Logger& parent(const std::string& name); + static void add(Logger* pLogger); + static Logger* find(const std::string& name); + +private: + Logger(); + Logger(const Logger&); + Logger& operator = (const Logger&); + + std::string _name; + Channel* _pChannel; + int _level; + + static LoggerMap* _pLoggerMap; + static Mutex _mapMtx; +}; + + +// +// convenience macros +// +#define poco_fatal(logger, msg) \ + if ((logger).fatal()) (logger).fatal(msg) else (void) 0 + +#define poco_critical(logger, msg) \ + if ((logger).critical()) (logger).critical(msg) else (void) 0 + +#define poco_error(logger, msg) \ + if ((logger).error()) (logger).error(msg) else (void) 0 + +#define poco_warning(logger, msg) \ + if ((logger).warning()) (logger).warning(msg) else (void) 0 + +#define poco_notice(logger, msg) \ + if ((logger).notice()) (logger).notice(msg) else (void) 0 + +#define poco_information(logger, msg) \ + if ((logger).information()) (logger).information(msg) else (void) 0 + +#if defined(_DEBUG) + #define poco_debug(logger, msg) \ + if ((logger).debug()) (logger).debug(msg) else (void) 0 + + #define poco_trace(logger, msg) \ + if ((logger).trace()) (logger).trace(msg) else (void) 0 +#else + #define poco_debug(logger, msg) + #define poco_trace(logger, msg) +#endif + + +// +// inlines +// +inline const std::string& Logger::name() const +{ + return _name; +} + + +inline int Logger::getLevel() const +{ + return _level; +} + + +inline void Logger::log(const std::string& text, Message::Priority prio) +{ + if (_level >= prio && _pChannel) + { + _pChannel->log(Message(_name, text, prio)); + } +} + + +inline void Logger::fatal(const std::string& msg) +{ + log(msg, Message::PRIO_FATAL); +} + + +inline void Logger::critical(const std::string& msg) +{ + log(msg, Message::PRIO_CRITICAL); +} + + +inline void Logger::error(const std::string& msg) +{ + log(msg, Message::PRIO_ERROR); +} + + +inline void Logger::warning(const std::string& msg) +{ + log(msg, Message::PRIO_WARNING); +} + + +inline void Logger::notice(const std::string& msg) +{ + log(msg, Message::PRIO_NOTICE); +} + + +inline void Logger::information(const std::string& msg) +{ + log(msg, Message::PRIO_INFORMATION); +} + + +inline void Logger::debug(const std::string& msg) +{ + log(msg, Message::PRIO_DEBUG); +} + + +inline void Logger::trace(const std::string& msg) +{ + log(msg, Message::PRIO_TRACE); +} + + +inline bool Logger::is(int level) const +{ + return _level >= level; +} + + +inline bool Logger::fatal() const +{ + return _level >= Message::PRIO_FATAL; +} + + +inline bool Logger::critical() const +{ + return _level >= Message::PRIO_CRITICAL; +} + + +inline bool Logger::error() const +{ + return _level >= Message::PRIO_ERROR; +} + + +inline bool Logger::warning() const +{ + return _level >= Message::PRIO_WARNING; +} + + +inline bool Logger::notice() const +{ + return _level >= Message::PRIO_NOTICE; +} + + +inline bool Logger::information() const +{ + return _level >= Message::PRIO_INFORMATION; +} + + +inline bool Logger::debug() const +{ + return _level >= Message::PRIO_DEBUG; +} + + +inline bool Logger::trace() const +{ + return _level >= Message::PRIO_TRACE; +} + + +} // namespace Poco + + +#endif // Foundation_Logger_INCLUDED diff --git a/Foundation/include/Poco/LoggingFactory.h b/Foundation/include/Poco/LoggingFactory.h index ff7d0f3b7..cb486dba2 100644 --- a/Foundation/include/Poco/LoggingFactory.h +++ b/Foundation/include/Poco/LoggingFactory.h @@ -1,115 +1,115 @@ -// -// LoggingFactory.h -// -// $Id: //poco/1.2/Foundation/include/Poco/LoggingFactory.h#1 $ -// -// Library: Foundation -// Package: Logging -// Module: LoggingFactory -// -// Definition of the LoggingFactory class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_LoggingFactory_INCLUDED -#define Foundation_LoggingFactory_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/DynamicFactory.h" -#include "Poco/Channel.h" -#include "Poco/Formatter.h" - - -namespace Poco { - - -class Foundation_API LoggingFactory - /// An extensible factory for channels and formatters. - /// - /// The following channel classes are pre-registered: - /// - AsyncChannel - /// - ConsoleChannel - /// - EventLogChannel (Windows platforms only) - /// - FileChannel - /// - FormattingChannel - /// - NullChannel - /// - OpcomChannel (OpenVMS only) - /// - SplitterChannel - /// - SyslogChannel (Unix platforms only) - /// - /// The following formatter classes are pre-registered: - /// - PatternFormatter -{ -public: - typedef AbstractInstantiator ChannelInstantiator; - typedef AbstractInstantiator FormatterFactory; - - LoggingFactory(); - /// Creates the LoggingFactory. - /// - /// Automatically registers class factories for the - /// built-in channel and formatter classes. - - ~LoggingFactory(); - /// Destroys the LoggingFactory. - - void registerChannelClass(const std::string& className, ChannelInstantiator* pFactory); - /// Registers a channel class with the LoggingFactory. - - void registerFormatterClass(const std::string& className, FormatterFactory* pFactory); - /// Registers a formatter class with the LoggingFactory. - - Channel* createChannel(const std::string& className) const; - /// Creates a new Channel instance from specified class. - /// - /// Throws a NotFoundException if the specified channel class - /// has not been registered. - - Formatter* createFormatter(const std::string& className) const; - /// Creates a new Formatter instance from specified class. - /// - /// Throws a NotFoundException if the specified formatter class - /// has not been registered. - - static LoggingFactory& defaultFactory(); - /// Returns a reference to the default - /// LoggingFactory. - -private: - void registerBuiltins(); - - DynamicFactory _channelFactory; - DynamicFactory _formatterFactory; -}; - - -} // namespace Poco - - -#endif // Foundation_LoggingFactory_INCLUDED +// +// LoggingFactory.h +// +// $Id: //poco/1.2/Foundation/include/Poco/LoggingFactory.h#1 $ +// +// Library: Foundation +// Package: Logging +// Module: LoggingFactory +// +// Definition of the LoggingFactory class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_LoggingFactory_INCLUDED +#define Foundation_LoggingFactory_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/DynamicFactory.h" +#include "Poco/Channel.h" +#include "Poco/Formatter.h" + + +namespace Poco { + + +class Foundation_API LoggingFactory + /// An extensible factory for channels and formatters. + /// + /// The following channel classes are pre-registered: + /// - AsyncChannel + /// - ConsoleChannel + /// - EventLogChannel (Windows platforms only) + /// - FileChannel + /// - FormattingChannel + /// - NullChannel + /// - OpcomChannel (OpenVMS only) + /// - SplitterChannel + /// - SyslogChannel (Unix platforms only) + /// + /// The following formatter classes are pre-registered: + /// - PatternFormatter +{ +public: + typedef AbstractInstantiator ChannelInstantiator; + typedef AbstractInstantiator FormatterFactory; + + LoggingFactory(); + /// Creates the LoggingFactory. + /// + /// Automatically registers class factories for the + /// built-in channel and formatter classes. + + ~LoggingFactory(); + /// Destroys the LoggingFactory. + + void registerChannelClass(const std::string& className, ChannelInstantiator* pFactory); + /// Registers a channel class with the LoggingFactory. + + void registerFormatterClass(const std::string& className, FormatterFactory* pFactory); + /// Registers a formatter class with the LoggingFactory. + + Channel* createChannel(const std::string& className) const; + /// Creates a new Channel instance from specified class. + /// + /// Throws a NotFoundException if the specified channel class + /// has not been registered. + + Formatter* createFormatter(const std::string& className) const; + /// Creates a new Formatter instance from specified class. + /// + /// Throws a NotFoundException if the specified formatter class + /// has not been registered. + + static LoggingFactory& defaultFactory(); + /// Returns a reference to the default + /// LoggingFactory. + +private: + void registerBuiltins(); + + DynamicFactory _channelFactory; + DynamicFactory _formatterFactory; +}; + + +} // namespace Poco + + +#endif // Foundation_LoggingFactory_INCLUDED diff --git a/Foundation/include/Poco/LoggingRegistry.h b/Foundation/include/Poco/LoggingRegistry.h index 657447e9a..0dbed01f1 100644 --- a/Foundation/include/Poco/LoggingRegistry.h +++ b/Foundation/include/Poco/LoggingRegistry.h @@ -1,121 +1,121 @@ -// -// LoggingRegistry.h -// -// $Id: //poco/1.2/Foundation/include/Poco/LoggingRegistry.h#1 $ -// -// Library: Foundation -// Package: Logging -// Module: LoggingRegistry -// -// Definition of the LoggingRegistry class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_LoggingRegistry_INCLUDED -#define Foundation_LoggingRegistry_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/AutoPtr.h" -#include "Poco/Channel.h" -#include "Poco/Formatter.h" -#include "Poco/Mutex.h" -#include - - -namespace Poco { - - -class Foundation_API LoggingRegistry - /// A registry for channels and formatters. - /// - /// The LoggingRegistry class is used for configuring - /// the logging framework. -{ -public: - LoggingRegistry(); - /// Creates the LoggingRegistry. - - ~LoggingRegistry(); - /// Destroys the LoggingRegistry. - - Channel* channelForName(const std::string& name) const; - /// Returns the Channel object which has been registered - /// under the given name. - /// - /// Throws a NotFoundException if the name is unknown. - - Formatter* formatterForName(const std::string& name) const; - /// Returns the Formatter object which has been registered - /// under the given name. - /// - /// Throws a NotFoundException if the name is unknown. - - void registerChannel(const std::string& name, Channel* pChannel); - /// Registers a channel under a given name. - /// It is okay to re-register a different channel under an - /// already existing name. - - void registerFormatter(const std::string& name, Formatter* pFormatter); - /// Registers a formatter under a given name. - /// It is okay to re-register a different formatter under an - /// already existing name. - - void unregisterChannel(const std::string& name); - /// Unregisters the given channel. - /// - /// Throws a NotFoundException if the name is unknown. - - void unregisterFormatter(const std::string& name); - /// Unregisters the given formatter. - /// - /// Throws a NotFoundException if the name is unknown. - - void clear(); - /// Unregisters all registered channels and formatters. - - static LoggingRegistry& defaultRegistry(); - /// Returns a reference to the default - /// LoggingRegistry. - -private: - typedef AutoPtr ChannelPtr; - typedef AutoPtr FormatterPtr; - typedef std::map ChannelMap; - typedef std::map FormatterMap; - - ChannelMap _channelMap; - FormatterMap _formatterMap; - mutable FastMutex _mutex; -}; - - -} // namespace Poco - - -#endif // Foundation_LoggingRegistry_INCLUDED +// +// LoggingRegistry.h +// +// $Id: //poco/1.2/Foundation/include/Poco/LoggingRegistry.h#1 $ +// +// Library: Foundation +// Package: Logging +// Module: LoggingRegistry +// +// Definition of the LoggingRegistry class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_LoggingRegistry_INCLUDED +#define Foundation_LoggingRegistry_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/AutoPtr.h" +#include "Poco/Channel.h" +#include "Poco/Formatter.h" +#include "Poco/Mutex.h" +#include + + +namespace Poco { + + +class Foundation_API LoggingRegistry + /// A registry for channels and formatters. + /// + /// The LoggingRegistry class is used for configuring + /// the logging framework. +{ +public: + LoggingRegistry(); + /// Creates the LoggingRegistry. + + ~LoggingRegistry(); + /// Destroys the LoggingRegistry. + + Channel* channelForName(const std::string& name) const; + /// Returns the Channel object which has been registered + /// under the given name. + /// + /// Throws a NotFoundException if the name is unknown. + + Formatter* formatterForName(const std::string& name) const; + /// Returns the Formatter object which has been registered + /// under the given name. + /// + /// Throws a NotFoundException if the name is unknown. + + void registerChannel(const std::string& name, Channel* pChannel); + /// Registers a channel under a given name. + /// It is okay to re-register a different channel under an + /// already existing name. + + void registerFormatter(const std::string& name, Formatter* pFormatter); + /// Registers a formatter under a given name. + /// It is okay to re-register a different formatter under an + /// already existing name. + + void unregisterChannel(const std::string& name); + /// Unregisters the given channel. + /// + /// Throws a NotFoundException if the name is unknown. + + void unregisterFormatter(const std::string& name); + /// Unregisters the given formatter. + /// + /// Throws a NotFoundException if the name is unknown. + + void clear(); + /// Unregisters all registered channels and formatters. + + static LoggingRegistry& defaultRegistry(); + /// Returns a reference to the default + /// LoggingRegistry. + +private: + typedef AutoPtr ChannelPtr; + typedef AutoPtr FormatterPtr; + typedef std::map ChannelMap; + typedef std::map FormatterMap; + + ChannelMap _channelMap; + FormatterMap _formatterMap; + mutable FastMutex _mutex; +}; + + +} // namespace Poco + + +#endif // Foundation_LoggingRegistry_INCLUDED diff --git a/Foundation/include/Poco/MD2Engine.h b/Foundation/include/Poco/MD2Engine.h index f9b52c1c4..020329c57 100644 --- a/Foundation/include/Poco/MD2Engine.h +++ b/Foundation/include/Poco/MD2Engine.h @@ -1,109 +1,109 @@ -// -// MD2Engine.h -// -// $Id: //poco/1.2/Foundation/include/Poco/MD2Engine.h#1 $ -// -// Library: Foundation -// Package: Crypt -// Module: MD2Engine -// -// Definition of class MD2Engine. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// -// -// MD2 (RFC 1319) algorithm: -// Copyright (C) 1990-2, RSA Data Security, Inc. Created 1990. All -// rights reserved. -// -// License to copy and use this software is granted for -// non-commercial Internet Privacy-Enhanced Mail provided that it is -// identified as the "RSA Data Security, Inc. MD2 Message Digest -// Algorithm" in all material mentioning or referencing this software -// or this function. -// -// RSA Data Security, Inc. makes no representations concerning either -// the merchantability of this software or the suitability of this -// software for any particular purpose. It is provided "as is" -// without express or implied warranty of any kind. -// -// These notices must be retained in any copies of any part of this -// documentation and/or software. -// - - -#ifndef Foundation_MD2Engine_INCLUDED -#define Foundation_MD2Engine_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/DigestEngine.h" - - -namespace Poco { - - -class Foundation_API MD2Engine: public DigestEngine - /// This class implementes the MD2 message digest algorithm, - /// described in RFC 1319. -{ -public: - enum - { - BLOCK_SIZE = 16, - DIGEST_SIZE = 16 - }; - - MD2Engine(); - ~MD2Engine(); - - unsigned digestLength() const; - void reset(); - const DigestEngine::Digest& digest(); - -protected: - void updateImpl(const void* data, unsigned length); - -private: - static void transform(unsigned char state[16], unsigned char checksum[16], const unsigned char block[16]); - - struct Context - { - unsigned char state[16]; // state - unsigned char checksum[16]; // checksum - unsigned int count; // number of bytes, modulo 16 - unsigned char buffer[16]; // input buffer - }; - - Context _context; - DigestEngine::Digest _digest; -}; - - -} // namespace Poco - - -#endif // Foundation_MD2Engine_INCLUDED +// +// MD2Engine.h +// +// $Id: //poco/1.2/Foundation/include/Poco/MD2Engine.h#1 $ +// +// Library: Foundation +// Package: Crypt +// Module: MD2Engine +// +// Definition of class MD2Engine. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// +// +// MD2 (RFC 1319) algorithm: +// Copyright (C) 1990-2, RSA Data Security, Inc. Created 1990. All +// rights reserved. +// +// License to copy and use this software is granted for +// non-commercial Internet Privacy-Enhanced Mail provided that it is +// identified as the "RSA Data Security, Inc. MD2 Message Digest +// Algorithm" in all material mentioning or referencing this software +// or this function. +// +// RSA Data Security, Inc. makes no representations concerning either +// the merchantability of this software or the suitability of this +// software for any particular purpose. It is provided "as is" +// without express or implied warranty of any kind. +// +// These notices must be retained in any copies of any part of this +// documentation and/or software. +// + + +#ifndef Foundation_MD2Engine_INCLUDED +#define Foundation_MD2Engine_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/DigestEngine.h" + + +namespace Poco { + + +class Foundation_API MD2Engine: public DigestEngine + /// This class implementes the MD2 message digest algorithm, + /// described in RFC 1319. +{ +public: + enum + { + BLOCK_SIZE = 16, + DIGEST_SIZE = 16 + }; + + MD2Engine(); + ~MD2Engine(); + + unsigned digestLength() const; + void reset(); + const DigestEngine::Digest& digest(); + +protected: + void updateImpl(const void* data, unsigned length); + +private: + static void transform(unsigned char state[16], unsigned char checksum[16], const unsigned char block[16]); + + struct Context + { + unsigned char state[16]; // state + unsigned char checksum[16]; // checksum + unsigned int count; // number of bytes, modulo 16 + unsigned char buffer[16]; // input buffer + }; + + Context _context; + DigestEngine::Digest _digest; +}; + + +} // namespace Poco + + +#endif // Foundation_MD2Engine_INCLUDED diff --git a/Foundation/include/Poco/MD4Engine.h b/Foundation/include/Poco/MD4Engine.h index 978b33807..e16336f73 100644 --- a/Foundation/include/Poco/MD4Engine.h +++ b/Foundation/include/Poco/MD4Engine.h @@ -1,114 +1,114 @@ -// -// MD4Engine.h -// -// $Id: //poco/1.2/Foundation/include/Poco/MD4Engine.h#1 $ -// -// Library: Foundation -// Package: Crypt -// Module: MD4Engine -// -// Definition of class MD4Engine. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// -// -// MD4 (RFC 1320) algorithm: -// Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All -// rights reserved. -// -// License to copy and use this software is granted provided that it -// is identified as the "RSA Data Security, Inc. MD4 Message-Digest -// Algorithm" in all material mentioning or referencing this software -// or this function. -// -// License is also granted to make and use derivative works provided -// that such works are identified as "derived from the RSA Data -// Security, Inc. MD4 Message-Digest Algorithm" in all material -// mentioning or referencing the derived work. -// -// RSA Data Security, Inc. makes no representations concerning either -// the merchantability of this software or the suitability of this -// software for any particular purpose. It is provided "as is" -// without express or implied warranty of any kind. -// -// These notices must be retained in any copies of any part of this -// documentation and/or software. -// - - -#ifndef Foundation_MD4Engine_INCLUDED -#define Foundation_MD4Engine_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/DigestEngine.h" - - -namespace Poco { - - -class Foundation_API MD4Engine: public DigestEngine - /// This class implementes the MD4 message digest algorithm, - /// described in RFC 1320. -{ -public: - enum - { - BLOCK_SIZE = 64, - DIGEST_SIZE = 16 - }; - - MD4Engine(); - ~MD4Engine(); - - unsigned digestLength() const; - void reset(); - const DigestEngine::Digest& digest(); - -protected: - void updateImpl(const void* data, unsigned length); - -private: - static void transform(UInt32 state[4], const unsigned char block[64]); - static void encode(unsigned char* output, const UInt32* input, unsigned int len); - static void decode(UInt32* output, const unsigned char* input, unsigned int len); - - struct Context - { - UInt32 state[4]; // state (ABCD) - UInt32 count[2]; // number of bits, modulo 2^64 (lsb first) - unsigned char buffer[64]; // input buffer - }; - - Context _context; - DigestEngine::Digest _digest; -}; - - -} // namespace Poco - - -#endif // Foundation_MD5Engine_INCLUDED +// +// MD4Engine.h +// +// $Id: //poco/1.2/Foundation/include/Poco/MD4Engine.h#1 $ +// +// Library: Foundation +// Package: Crypt +// Module: MD4Engine +// +// Definition of class MD4Engine. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// +// +// MD4 (RFC 1320) algorithm: +// Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All +// rights reserved. +// +// License to copy and use this software is granted provided that it +// is identified as the "RSA Data Security, Inc. MD4 Message-Digest +// Algorithm" in all material mentioning or referencing this software +// or this function. +// +// License is also granted to make and use derivative works provided +// that such works are identified as "derived from the RSA Data +// Security, Inc. MD4 Message-Digest Algorithm" in all material +// mentioning or referencing the derived work. +// +// RSA Data Security, Inc. makes no representations concerning either +// the merchantability of this software or the suitability of this +// software for any particular purpose. It is provided "as is" +// without express or implied warranty of any kind. +// +// These notices must be retained in any copies of any part of this +// documentation and/or software. +// + + +#ifndef Foundation_MD4Engine_INCLUDED +#define Foundation_MD4Engine_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/DigestEngine.h" + + +namespace Poco { + + +class Foundation_API MD4Engine: public DigestEngine + /// This class implementes the MD4 message digest algorithm, + /// described in RFC 1320. +{ +public: + enum + { + BLOCK_SIZE = 64, + DIGEST_SIZE = 16 + }; + + MD4Engine(); + ~MD4Engine(); + + unsigned digestLength() const; + void reset(); + const DigestEngine::Digest& digest(); + +protected: + void updateImpl(const void* data, unsigned length); + +private: + static void transform(UInt32 state[4], const unsigned char block[64]); + static void encode(unsigned char* output, const UInt32* input, unsigned int len); + static void decode(UInt32* output, const unsigned char* input, unsigned int len); + + struct Context + { + UInt32 state[4]; // state (ABCD) + UInt32 count[2]; // number of bits, modulo 2^64 (lsb first) + unsigned char buffer[64]; // input buffer + }; + + Context _context; + DigestEngine::Digest _digest; +}; + + +} // namespace Poco + + +#endif // Foundation_MD5Engine_INCLUDED diff --git a/Foundation/include/Poco/MD5Engine.h b/Foundation/include/Poco/MD5Engine.h index 90d08437d..f1047a71a 100644 --- a/Foundation/include/Poco/MD5Engine.h +++ b/Foundation/include/Poco/MD5Engine.h @@ -1,114 +1,114 @@ -// -// MD5Engine.h -// -// $Id: //poco/1.2/Foundation/include/Poco/MD5Engine.h#1 $ -// -// Library: Foundation -// Package: Crypt -// Module: MD5Engine -// -// Definition of class MD5Engine. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// -// -// MD5 (RFC 1321) algorithm: -// Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All -// rights reserved. -// -// License to copy and use this software is granted provided that it -// is identified as the "RSA Data Security, Inc. MD5 Message-Digest -// Algorithm" in all material mentioning or referencing this software -// or this function. -// -// License is also granted to make and use derivative works provided -// that such works are identified as "derived from the RSA Data -// Security, Inc. MD5 Message-Digest Algorithm" in all material -// mentioning or referencing the derived work. -// -// RSA Data Security, Inc. makes no representations concerning either -// the merchantability of this software or the suitability of this -// software for any particular purpose. It is provided "as is" -// without express or implied warranty of any kind. -// -// These notices must be retained in any copies of any part of this -// documentation and/or software. -// - - -#ifndef Foundation_MD5Engine_INCLUDED -#define Foundation_MD5Engine_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/DigestEngine.h" - - -namespace Poco { - - -class Foundation_API MD5Engine: public DigestEngine - /// This class implementes the MD5 message digest algorithm, - /// described in RFC 1321. -{ -public: - enum - { - BLOCK_SIZE = 64, - DIGEST_SIZE = 16 - }; - - MD5Engine(); - ~MD5Engine(); - - unsigned digestLength() const; - void reset(); - const DigestEngine::Digest& digest(); - -protected: - void updateImpl(const void* data, unsigned length); - -private: - static void transform(UInt32 state[4], const unsigned char block[64]); - static void encode(unsigned char* output, const UInt32* input, unsigned int len); - static void decode(UInt32* output, const unsigned char* input, unsigned int len); - - struct Context - { - UInt32 state[4]; // state (ABCD) - UInt32 count[2]; // number of bits, modulo 2^64 (lsb first) - unsigned char buffer[64]; // input buffer - }; - - Context _context; - DigestEngine::Digest _digest; -}; - - -} // namespace Poco - - -#endif // Foundation_MD5Engine_INCLUDED +// +// MD5Engine.h +// +// $Id: //poco/1.2/Foundation/include/Poco/MD5Engine.h#1 $ +// +// Library: Foundation +// Package: Crypt +// Module: MD5Engine +// +// Definition of class MD5Engine. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// +// +// MD5 (RFC 1321) algorithm: +// Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All +// rights reserved. +// +// License to copy and use this software is granted provided that it +// is identified as the "RSA Data Security, Inc. MD5 Message-Digest +// Algorithm" in all material mentioning or referencing this software +// or this function. +// +// License is also granted to make and use derivative works provided +// that such works are identified as "derived from the RSA Data +// Security, Inc. MD5 Message-Digest Algorithm" in all material +// mentioning or referencing the derived work. +// +// RSA Data Security, Inc. makes no representations concerning either +// the merchantability of this software or the suitability of this +// software for any particular purpose. It is provided "as is" +// without express or implied warranty of any kind. +// +// These notices must be retained in any copies of any part of this +// documentation and/or software. +// + + +#ifndef Foundation_MD5Engine_INCLUDED +#define Foundation_MD5Engine_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/DigestEngine.h" + + +namespace Poco { + + +class Foundation_API MD5Engine: public DigestEngine + /// This class implementes the MD5 message digest algorithm, + /// described in RFC 1321. +{ +public: + enum + { + BLOCK_SIZE = 64, + DIGEST_SIZE = 16 + }; + + MD5Engine(); + ~MD5Engine(); + + unsigned digestLength() const; + void reset(); + const DigestEngine::Digest& digest(); + +protected: + void updateImpl(const void* data, unsigned length); + +private: + static void transform(UInt32 state[4], const unsigned char block[64]); + static void encode(unsigned char* output, const UInt32* input, unsigned int len); + static void decode(UInt32* output, const unsigned char* input, unsigned int len); + + struct Context + { + UInt32 state[4]; // state (ABCD) + UInt32 count[2]; // number of bits, modulo 2^64 (lsb first) + unsigned char buffer[64]; // input buffer + }; + + Context _context; + DigestEngine::Digest _digest; +}; + + +} // namespace Poco + + +#endif // Foundation_MD5Engine_INCLUDED diff --git a/Foundation/include/Poco/Manifest.h b/Foundation/include/Poco/Manifest.h index bcf25fe60..b4751ff7e 100644 --- a/Foundation/include/Poco/Manifest.h +++ b/Foundation/include/Poco/Manifest.h @@ -1,202 +1,202 @@ -// -// Manifest.h -// -// $Id: //poco/1.2/Foundation/include/Poco/Manifest.h#1 $ -// -// Library: Foundation -// Package: SharedLibrary -// Module: ClassLoader -// -// Definition of the Manifest class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_Manifest_INCLUDED -#define Foundation_Manifest_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/MetaObject.h" -#include -#include - - -namespace Poco { - - -class Foundation_API ManifestBase - /// ManifestBase is a common base class for - /// all instantiations of Manifest. -{ -public: - ManifestBase(); - virtual ~ManifestBase(); - - virtual const char* className() const = 0; - /// Returns the type name of the manifest's class. -}; - - -template -class Manifest: public ManifestBase - /// A Manifest maintains a list of all classes - /// contained in a dynamically loadable class - /// library. - /// Internally, the information is held - /// in a map. An iterator is provided to - /// iterate over all the classes in a Manifest. -{ -public: - typedef AbstractMetaObject Meta; - typedef std::map MetaMap; - - class Iterator - /// The Manifest's very own iterator class. - { - public: - Iterator(const typename MetaMap::const_iterator& it) - { - _it = it; - } - Iterator(const Iterator& it) - { - _it = it._it; - } - ~Iterator() - { - } - Iterator& operator = (const Iterator& it) - { - _it = it._it; - return *this; - } - inline bool operator == (const Iterator& it) const - { - return _it == it._it; - } - inline bool operator != (const Iterator& it) const - { - return _it != it._it; - } - Iterator& operator ++ () // prefix - { - ++_it; - return *this; - } - Iterator operator ++ (int) // postfix - { - Iterator result(_it); - ++_it; - return result; - } - inline const Meta* operator * () const - { - return _it->second; - } - inline const Meta* operator -> () const - { - return _it->second; - } - - private: - typename MetaMap::const_iterator _it; - }; - - Manifest() - /// Creates an empty Manifest. - { - } - - virtual ~Manifest() - /// Destroys the Manifest. - { - clear(); - } - - Iterator find(const std::string& className) const - /// Returns an iterator pointing to the MetaObject - /// for the given class. If the MetaObject cannot - /// be found, the iterator points to end(). - { - return Iterator(_metaMap.find(className)); - } - - Iterator begin() const - { - return Iterator(_metaMap.begin()); - } - - Iterator end() const - { - return Iterator(_metaMap.end()); - } - - bool insert(const Meta* pMeta) - /// Inserts a MetaObject. Returns true if insertion - /// was successful, false if a class with the same - /// name already exists. - { - return _metaMap.insert(typename MetaMap::value_type(pMeta->name(), pMeta)).second; - } - - void clear() - /// Removes all MetaObjects from the manifest. - { - for (typename MetaMap::iterator it = _metaMap.begin(); it != _metaMap.end(); ++it) - { - delete it->second; - } - _metaMap.clear(); - } - - int size() const - /// Returns the number of MetaObjects in the Manifest. - { - return int(_metaMap.size()); - } - - bool empty() const - /// Returns true iff the Manifest does not contain any MetaObjects. - { - return _metaMap.empty(); - } - - const char* className() const - { - return typeid(*this).name(); - } - -private: - MetaMap _metaMap; -}; - - -} // namespace Poco - - -#endif // Foundation_Manifest_INCLUDED +// +// Manifest.h +// +// $Id: //poco/1.2/Foundation/include/Poco/Manifest.h#1 $ +// +// Library: Foundation +// Package: SharedLibrary +// Module: ClassLoader +// +// Definition of the Manifest class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_Manifest_INCLUDED +#define Foundation_Manifest_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/MetaObject.h" +#include +#include + + +namespace Poco { + + +class Foundation_API ManifestBase + /// ManifestBase is a common base class for + /// all instantiations of Manifest. +{ +public: + ManifestBase(); + virtual ~ManifestBase(); + + virtual const char* className() const = 0; + /// Returns the type name of the manifest's class. +}; + + +template +class Manifest: public ManifestBase + /// A Manifest maintains a list of all classes + /// contained in a dynamically loadable class + /// library. + /// Internally, the information is held + /// in a map. An iterator is provided to + /// iterate over all the classes in a Manifest. +{ +public: + typedef AbstractMetaObject Meta; + typedef std::map MetaMap; + + class Iterator + /// The Manifest's very own iterator class. + { + public: + Iterator(const typename MetaMap::const_iterator& it) + { + _it = it; + } + Iterator(const Iterator& it) + { + _it = it._it; + } + ~Iterator() + { + } + Iterator& operator = (const Iterator& it) + { + _it = it._it; + return *this; + } + inline bool operator == (const Iterator& it) const + { + return _it == it._it; + } + inline bool operator != (const Iterator& it) const + { + return _it != it._it; + } + Iterator& operator ++ () // prefix + { + ++_it; + return *this; + } + Iterator operator ++ (int) // postfix + { + Iterator result(_it); + ++_it; + return result; + } + inline const Meta* operator * () const + { + return _it->second; + } + inline const Meta* operator -> () const + { + return _it->second; + } + + private: + typename MetaMap::const_iterator _it; + }; + + Manifest() + /// Creates an empty Manifest. + { + } + + virtual ~Manifest() + /// Destroys the Manifest. + { + clear(); + } + + Iterator find(const std::string& className) const + /// Returns an iterator pointing to the MetaObject + /// for the given class. If the MetaObject cannot + /// be found, the iterator points to end(). + { + return Iterator(_metaMap.find(className)); + } + + Iterator begin() const + { + return Iterator(_metaMap.begin()); + } + + Iterator end() const + { + return Iterator(_metaMap.end()); + } + + bool insert(const Meta* pMeta) + /// Inserts a MetaObject. Returns true if insertion + /// was successful, false if a class with the same + /// name already exists. + { + return _metaMap.insert(typename MetaMap::value_type(pMeta->name(), pMeta)).second; + } + + void clear() + /// Removes all MetaObjects from the manifest. + { + for (typename MetaMap::iterator it = _metaMap.begin(); it != _metaMap.end(); ++it) + { + delete it->second; + } + _metaMap.clear(); + } + + int size() const + /// Returns the number of MetaObjects in the Manifest. + { + return int(_metaMap.size()); + } + + bool empty() const + /// Returns true iff the Manifest does not contain any MetaObjects. + { + return _metaMap.empty(); + } + + const char* className() const + { + return typeid(*this).name(); + } + +private: + MetaMap _metaMap; +}; + + +} // namespace Poco + + +#endif // Foundation_Manifest_INCLUDED diff --git a/Foundation/include/Poco/MemoryPool.h b/Foundation/include/Poco/MemoryPool.h index e49f799b3..afb9e3df4 100644 --- a/Foundation/include/Poco/MemoryPool.h +++ b/Foundation/include/Poco/MemoryPool.h @@ -1,134 +1,134 @@ -// -// MemoryPool.h -// -// $Id: //poco/1.2/Foundation/include/Poco/MemoryPool.h#1 $ -// -// Library: Foundation -// Package: Core -// Module: MemoryPool -// -// Definition of the MemoryPool class. -// -// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_MemoryPool_INCLUDED -#define Foundation_MemoryPool_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/Mutex.h" -#include - - -namespace Poco { - - -class Foundation_API MemoryPool - /// A simple pool for fixed-size memory blocks. - /// - /// The main purpose of this class is to speed-up - /// memory allocations, as well as to reduce memory - /// fragmentation in situations where the same blocks - /// are allocated all over again, such as in server - /// applications. - /// - /// All allocated blocks are retained for future use. - /// A limit on the number of blocks can be specified. - /// Blocks can be preallocated. -{ -public: - MemoryPool(size_t blockSize, int preAlloc = 0, int maxAlloc = 0); - /// Creates a MemoryPool for blocks with the given blockSize. - /// The number of blocks given in preAlloc are preallocated. - - ~MemoryPool(); - - void* get(); - /// Returns a memory block. If there are no more blocks - /// in the pool, a new block will be allocated. - /// - /// If maxAlloc blocks are already allocated, an - /// OutOfMemoryException is thrown. - - void release(void* ptr); - /// Releases a memory block and returns it to the pool. - - size_t blockSize() const; - /// Returns the block size. - - int allocated() const; - /// Returns the number of allocated blocks. - - int available() const; - /// Returns the number of available blocks in the pool. - -private: - MemoryPool(); - MemoryPool(const MemoryPool&); - MemoryPool& operator = (const MemoryPool&); - - enum - { - BLOCK_RESERVE = 128 - }; - - typedef std::vector BlockVec; - - size_t _blockSize; - int _maxAlloc; - int _allocated; - BlockVec _blocks; - FastMutex _mutex; -}; - - -// -// inlines -// -inline size_t MemoryPool::blockSize() const -{ - return _blockSize; -} - - -inline int MemoryPool::allocated() const -{ - return _allocated; -} - - -inline int MemoryPool::available() const -{ - return (int) _blocks.size(); -} - - -} // namespace Poco - - -#endif // Foundation_MemoryPool_INCLUDED +// +// MemoryPool.h +// +// $Id: //poco/1.2/Foundation/include/Poco/MemoryPool.h#1 $ +// +// Library: Foundation +// Package: Core +// Module: MemoryPool +// +// Definition of the MemoryPool class. +// +// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_MemoryPool_INCLUDED +#define Foundation_MemoryPool_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Mutex.h" +#include + + +namespace Poco { + + +class Foundation_API MemoryPool + /// A simple pool for fixed-size memory blocks. + /// + /// The main purpose of this class is to speed-up + /// memory allocations, as well as to reduce memory + /// fragmentation in situations where the same blocks + /// are allocated all over again, such as in server + /// applications. + /// + /// All allocated blocks are retained for future use. + /// A limit on the number of blocks can be specified. + /// Blocks can be preallocated. +{ +public: + MemoryPool(size_t blockSize, int preAlloc = 0, int maxAlloc = 0); + /// Creates a MemoryPool for blocks with the given blockSize. + /// The number of blocks given in preAlloc are preallocated. + + ~MemoryPool(); + + void* get(); + /// Returns a memory block. If there are no more blocks + /// in the pool, a new block will be allocated. + /// + /// If maxAlloc blocks are already allocated, an + /// OutOfMemoryException is thrown. + + void release(void* ptr); + /// Releases a memory block and returns it to the pool. + + size_t blockSize() const; + /// Returns the block size. + + int allocated() const; + /// Returns the number of allocated blocks. + + int available() const; + /// Returns the number of available blocks in the pool. + +private: + MemoryPool(); + MemoryPool(const MemoryPool&); + MemoryPool& operator = (const MemoryPool&); + + enum + { + BLOCK_RESERVE = 128 + }; + + typedef std::vector BlockVec; + + size_t _blockSize; + int _maxAlloc; + int _allocated; + BlockVec _blocks; + FastMutex _mutex; +}; + + +// +// inlines +// +inline size_t MemoryPool::blockSize() const +{ + return _blockSize; +} + + +inline int MemoryPool::allocated() const +{ + return _allocated; +} + + +inline int MemoryPool::available() const +{ + return (int) _blocks.size(); +} + + +} // namespace Poco + + +#endif // Foundation_MemoryPool_INCLUDED diff --git a/Foundation/include/Poco/Message.h b/Foundation/include/Poco/Message.h index d7d8eb68f..50c553b93 100644 --- a/Foundation/include/Poco/Message.h +++ b/Foundation/include/Poco/Message.h @@ -1,208 +1,208 @@ -// -// Message.h -// -// $Id: //poco/1.2/Foundation/include/Poco/Message.h#1 $ -// -// Library: Foundation -// Package: Logging -// Module: Message -// -// Definition of the Message class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_Message_INCLUDED -#define Foundation_Message_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/Timestamp.h" -#include - - -namespace Poco { - - -class Foundation_API Message - /// This class represents a log message that is sent through a - /// chain of log channels. - /// - /// A Message contains a priority denoting the severity of the - /// message, a source describing its origin, a text describing - /// its meaning, the time of its creation, and an identifier of - /// the process and thread that created the message. - /// - /// A Message can also contain any number of named parameters - /// that contain additional information about the event that - /// caused the message. -{ -public: - enum Priority - { - PRIO_FATAL = 1, /// A fatal error. The application will most likely terminate. This is the highest priority. - PRIO_CRITICAL, /// A critical error. The application might not be able to continue running successfully. - PRIO_ERROR, /// An error. An operation did not complete successfully, but the application as a whole is not affected. - PRIO_WARNING, /// A warning. An operation completed with an unexpected result. - PRIO_NOTICE, /// A notice, which is an information with just a higher priority. - PRIO_INFORMATION, /// An informational message, usually denoting the successful completion of an operation. - PRIO_DEBUG, /// A debugging message. - PRIO_TRACE /// A tracing message. This is the lowest priority. - }; - - Message(); - /// Creates an empty Message. - /// The thread and process ids are set. - - Message(const std::string& source, const std::string& text, Priority prio); - /// Creates a Message with the given source, text and priority. - /// The thread and process ids are set. - - Message(const Message& msg); - /// Creates a Message by copying another one. - - Message(const Message& msg, const std::string& text); - /// Creates a Message by copying all but the text from another message. - - ~Message(); - /// Destroys the Message. - - Message& operator = (const Message& msg); - /// Assignment operator. - - void setSource(const std::string& src); - /// Sets the source of the message. - - const std::string& getSource() const; - /// Returns the source of the message. - - void setText(const std::string& text); - /// Sets the text of the message. - - const std::string& getText() const; - /// Returns the text of the message. - - void setPriority(Priority prio); - /// Sets the priority of the message. - - Priority getPriority() const; - /// Returns the priority of the message. - - void setTime(const Timestamp& time); - /// Sets the time of the message. - - const Timestamp& getTime() const; - /// Returns the time of the message. - - void setThread(const std::string& thread); - /// Sets the thread identifier for the message. - - const std::string& getThread() const; - /// Returns the thread identifier for the message. - - void setTid(long pid); - /// Sets the numeric thread identifier for the message. - - long getTid() const; - /// Returns the numeric thread identifier for the message. - - void setPid(long pid); - /// Sets the process identifier for the message. - - long getPid() const; - /// Returns the process identifier for the message. - - const std::string& operator [] (const std::string& param) const; - /// Returns a const reference to the value of the parameter - /// with the given name. Throws a NotFoundException if the - /// parameter does not exist. - - std::string& operator [] (const std::string& param); - /// Returns a reference to the value of the parameter with the - /// given name. This can be used to set the parameter's value. - /// If the parameter does not exist, it is created with an - /// empty string value. - -protected: - void init(); - typedef std::map StringMap; - -private: - std::string _source; - std::string _text; - Priority _prio; - Timestamp _time; - int _tid; - std::string _thread; - long _pid; - StringMap* _pMap; -}; - - -// -// inlines -// -inline const std::string& Message::getSource() const -{ - return _source; -} - - -inline const std::string& Message::getText() const -{ - return _text; -} - - -inline Message::Priority Message::getPriority() const -{ - return _prio; -} - - -inline const std::string& Message::getThread() const -{ - return _thread; -} - - -inline long Message::getTid() const -{ - return _tid; -} - - -inline long Message::getPid() const -{ - return _pid; -} - - -} // namespace Poco - - -#endif // Foundation_Message_INCLUDED +// +// Message.h +// +// $Id: //poco/1.2/Foundation/include/Poco/Message.h#1 $ +// +// Library: Foundation +// Package: Logging +// Module: Message +// +// Definition of the Message class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_Message_INCLUDED +#define Foundation_Message_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Timestamp.h" +#include + + +namespace Poco { + + +class Foundation_API Message + /// This class represents a log message that is sent through a + /// chain of log channels. + /// + /// A Message contains a priority denoting the severity of the + /// message, a source describing its origin, a text describing + /// its meaning, the time of its creation, and an identifier of + /// the process and thread that created the message. + /// + /// A Message can also contain any number of named parameters + /// that contain additional information about the event that + /// caused the message. +{ +public: + enum Priority + { + PRIO_FATAL = 1, /// A fatal error. The application will most likely terminate. This is the highest priority. + PRIO_CRITICAL, /// A critical error. The application might not be able to continue running successfully. + PRIO_ERROR, /// An error. An operation did not complete successfully, but the application as a whole is not affected. + PRIO_WARNING, /// A warning. An operation completed with an unexpected result. + PRIO_NOTICE, /// A notice, which is an information with just a higher priority. + PRIO_INFORMATION, /// An informational message, usually denoting the successful completion of an operation. + PRIO_DEBUG, /// A debugging message. + PRIO_TRACE /// A tracing message. This is the lowest priority. + }; + + Message(); + /// Creates an empty Message. + /// The thread and process ids are set. + + Message(const std::string& source, const std::string& text, Priority prio); + /// Creates a Message with the given source, text and priority. + /// The thread and process ids are set. + + Message(const Message& msg); + /// Creates a Message by copying another one. + + Message(const Message& msg, const std::string& text); + /// Creates a Message by copying all but the text from another message. + + ~Message(); + /// Destroys the Message. + + Message& operator = (const Message& msg); + /// Assignment operator. + + void setSource(const std::string& src); + /// Sets the source of the message. + + const std::string& getSource() const; + /// Returns the source of the message. + + void setText(const std::string& text); + /// Sets the text of the message. + + const std::string& getText() const; + /// Returns the text of the message. + + void setPriority(Priority prio); + /// Sets the priority of the message. + + Priority getPriority() const; + /// Returns the priority of the message. + + void setTime(const Timestamp& time); + /// Sets the time of the message. + + const Timestamp& getTime() const; + /// Returns the time of the message. + + void setThread(const std::string& thread); + /// Sets the thread identifier for the message. + + const std::string& getThread() const; + /// Returns the thread identifier for the message. + + void setTid(long pid); + /// Sets the numeric thread identifier for the message. + + long getTid() const; + /// Returns the numeric thread identifier for the message. + + void setPid(long pid); + /// Sets the process identifier for the message. + + long getPid() const; + /// Returns the process identifier for the message. + + const std::string& operator [] (const std::string& param) const; + /// Returns a const reference to the value of the parameter + /// with the given name. Throws a NotFoundException if the + /// parameter does not exist. + + std::string& operator [] (const std::string& param); + /// Returns a reference to the value of the parameter with the + /// given name. This can be used to set the parameter's value. + /// If the parameter does not exist, it is created with an + /// empty string value. + +protected: + void init(); + typedef std::map StringMap; + +private: + std::string _source; + std::string _text; + Priority _prio; + Timestamp _time; + int _tid; + std::string _thread; + long _pid; + StringMap* _pMap; +}; + + +// +// inlines +// +inline const std::string& Message::getSource() const +{ + return _source; +} + + +inline const std::string& Message::getText() const +{ + return _text; +} + + +inline Message::Priority Message::getPriority() const +{ + return _prio; +} + + +inline const std::string& Message::getThread() const +{ + return _thread; +} + + +inline long Message::getTid() const +{ + return _tid; +} + + +inline long Message::getPid() const +{ + return _pid; +} + + +} // namespace Poco + + +#endif // Foundation_Message_INCLUDED diff --git a/Foundation/include/Poco/MetaObject.h b/Foundation/include/Poco/MetaObject.h index 78309c326..db67e5ced 100644 --- a/Foundation/include/Poco/MetaObject.h +++ b/Foundation/include/Poco/MetaObject.h @@ -1,223 +1,223 @@ -// -// MetaObject.h -// -// $Id: //poco/1.2/Foundation/include/Poco/MetaObject.h#1 $ -// -// Library: Foundation -// Package: SharedLibrary -// Module: ClassLoader -// -// Definition of the MetaObject class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_MetaObject_INCLUDED -#define Foundation_MetaObject_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/Exception.h" -#include "Poco/SingletonHolder.h" -#include - - -namespace Poco { - - -template -class AbstractMetaObject - /// A MetaObject stores some information - /// about a C++ class. The MetaObject class - /// is used by the Manifest class. - /// AbstractMetaObject is a common base class - /// for all MetaObject in a rooted class hierarchy. - /// A MetaObject can also be used as an object - /// factory for its class. -{ -public: - AbstractMetaObject(const char* name): _name(name) - { - } - - virtual ~AbstractMetaObject() - { - for (typename ObjectSet::iterator it = _deleteSet.begin(); it != _deleteSet.end(); ++it) - { - delete *it; - } - } - - const char* name() const - { - return _name; - } - - virtual B* create() const = 0; - /// Create a new instance of a class. - /// Cannot be used for singletons. - - virtual B& instance() const = 0; - /// Returns a reference to the only instance - /// of the class. Used for singletons only. - - virtual bool canCreate() const = 0; - /// Returns true iff the create method can be used - /// to create instances of the class. - /// Returns false if the class is a singleton. - - virtual void destroy(B* pObject) const - /// If pObject was owned by meta object, the - /// ownership of the deleted object is removed - /// and the object is deleted. - { - typename ObjectSet::iterator it = _deleteSet.find(pObject); - - if (it != _deleteSet.end()) - { - _deleteSet.erase(pObject); - delete pObject; - } - } - - B* autoDelete(B* pObject) const - /// Give ownership of pObject to the meta object. - /// The meta object will delete all objects it owns - /// when it is destroyed. - /// - /// Returns pObject. - { - if (this->canCreate()) // guard against singleton - { - poco_check_ptr (pObject); - _deleteSet.insert(pObject); - } - else throw InvalidAccessException("Cannot take ownership of", this->name()); - - return pObject; - } - - virtual bool isAutoDelete(B* pObject) const - /// Returns true if the object is owned - /// by meta object. - /// - /// Overloaded in MetaSingleton - returns true - /// if the class is a singleton. - { - return _deleteSet.find(pObject) != _deleteSet.end(); - } - -private: - AbstractMetaObject(); - AbstractMetaObject(const AbstractMetaObject&); - AbstractMetaObject& operator = (const AbstractMetaObject&); - - typedef std::set ObjectSet; - - const char* _name; - mutable ObjectSet _deleteSet; -}; - - -template -class MetaObject: public AbstractMetaObject - /// A MetaObject stores some information - /// about a C++ class. The MetaObject class - /// is used by the Manifest class. - /// A MetaObject can also be used as an object - /// factory for its class. -{ -public: - MetaObject(const char* name): AbstractMetaObject(name) - { - } - - ~MetaObject() - { - } - - B* create() const - { - return new C; - } - - B& instance() const - { - throw InvalidAccessException("Not a singleton. Use create() to create instances of", this->name()); - } - - bool canCreate() const - { - return true; - } -}; - - -template -class MetaSingleton: public AbstractMetaObject - /// A SingletonMetaObject disables the create() method - /// and instead offers an instance() method to access - /// the single instance of its class. -{ -public: - MetaSingleton(const char* name): AbstractMetaObject(name) - { - } - - ~MetaSingleton() - { - } - - B* create() const - { - throw InvalidAccessException("Cannot create instances of a singleton class. Use instance() to obtain a", this->name()); - } - - bool canCreate() const - { - return false; - } - - B& instance() const - { - return *_object.get(); - } - - bool isAutoDelete(B* pObject) const - { - return true; - } - -private: - mutable SingletonHolder _object; -}; - - -} // namespace Poco - - -#endif // Foundation_MetaObject_INCLUDED +// +// MetaObject.h +// +// $Id: //poco/1.2/Foundation/include/Poco/MetaObject.h#1 $ +// +// Library: Foundation +// Package: SharedLibrary +// Module: ClassLoader +// +// Definition of the MetaObject class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_MetaObject_INCLUDED +#define Foundation_MetaObject_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Exception.h" +#include "Poco/SingletonHolder.h" +#include + + +namespace Poco { + + +template +class AbstractMetaObject + /// A MetaObject stores some information + /// about a C++ class. The MetaObject class + /// is used by the Manifest class. + /// AbstractMetaObject is a common base class + /// for all MetaObject in a rooted class hierarchy. + /// A MetaObject can also be used as an object + /// factory for its class. +{ +public: + AbstractMetaObject(const char* name): _name(name) + { + } + + virtual ~AbstractMetaObject() + { + for (typename ObjectSet::iterator it = _deleteSet.begin(); it != _deleteSet.end(); ++it) + { + delete *it; + } + } + + const char* name() const + { + return _name; + } + + virtual B* create() const = 0; + /// Create a new instance of a class. + /// Cannot be used for singletons. + + virtual B& instance() const = 0; + /// Returns a reference to the only instance + /// of the class. Used for singletons only. + + virtual bool canCreate() const = 0; + /// Returns true iff the create method can be used + /// to create instances of the class. + /// Returns false if the class is a singleton. + + virtual void destroy(B* pObject) const + /// If pObject was owned by meta object, the + /// ownership of the deleted object is removed + /// and the object is deleted. + { + typename ObjectSet::iterator it = _deleteSet.find(pObject); + + if (it != _deleteSet.end()) + { + _deleteSet.erase(pObject); + delete pObject; + } + } + + B* autoDelete(B* pObject) const + /// Give ownership of pObject to the meta object. + /// The meta object will delete all objects it owns + /// when it is destroyed. + /// + /// Returns pObject. + { + if (this->canCreate()) // guard against singleton + { + poco_check_ptr (pObject); + _deleteSet.insert(pObject); + } + else throw InvalidAccessException("Cannot take ownership of", this->name()); + + return pObject; + } + + virtual bool isAutoDelete(B* pObject) const + /// Returns true if the object is owned + /// by meta object. + /// + /// Overloaded in MetaSingleton - returns true + /// if the class is a singleton. + { + return _deleteSet.find(pObject) != _deleteSet.end(); + } + +private: + AbstractMetaObject(); + AbstractMetaObject(const AbstractMetaObject&); + AbstractMetaObject& operator = (const AbstractMetaObject&); + + typedef std::set ObjectSet; + + const char* _name; + mutable ObjectSet _deleteSet; +}; + + +template +class MetaObject: public AbstractMetaObject + /// A MetaObject stores some information + /// about a C++ class. The MetaObject class + /// is used by the Manifest class. + /// A MetaObject can also be used as an object + /// factory for its class. +{ +public: + MetaObject(const char* name): AbstractMetaObject(name) + { + } + + ~MetaObject() + { + } + + B* create() const + { + return new C; + } + + B& instance() const + { + throw InvalidAccessException("Not a singleton. Use create() to create instances of", this->name()); + } + + bool canCreate() const + { + return true; + } +}; + + +template +class MetaSingleton: public AbstractMetaObject + /// A SingletonMetaObject disables the create() method + /// and instead offers an instance() method to access + /// the single instance of its class. +{ +public: + MetaSingleton(const char* name): AbstractMetaObject(name) + { + } + + ~MetaSingleton() + { + } + + B* create() const + { + throw InvalidAccessException("Cannot create instances of a singleton class. Use instance() to obtain a", this->name()); + } + + bool canCreate() const + { + return false; + } + + B& instance() const + { + return *_object.get(); + } + + bool isAutoDelete(B* pObject) const + { + return true; + } + +private: + mutable SingletonHolder _object; +}; + + +} // namespace Poco + + +#endif // Foundation_MetaObject_INCLUDED diff --git a/Foundation/include/Poco/Mutex.h b/Foundation/include/Poco/Mutex.h index ceb293ea8..034711f8c 100644 --- a/Foundation/include/Poco/Mutex.h +++ b/Foundation/include/Poco/Mutex.h @@ -1,174 +1,174 @@ -// -// Mutex.h -// -// $Id: //poco/1.2/Foundation/include/Poco/Mutex.h#1 $ -// -// Library: Foundation -// Package: Threading -// Module: Mutex -// -// Definition of the Mutex and FastMutex classes. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_Mutex_INCLUDED -#define Foundation_Mutex_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/ScopedLock.h" - - -#if defined(POCO_OS_FAMILY_WINDOWS) -#include "Poco/Mutex_WIN32.h" -#else -#include "Poco/Mutex_POSIX.h" -#endif - - -namespace Poco { - - -class Foundation_API Mutex: private MutexImpl - /// A Mutex (mutual exclusion) is a synchronization - /// mechanism used to control access to a shared resource - /// in a concurrent (multithreaded) scenario. - /// Mutexes are recursive, that is, the same mutex can be - /// locked multiple times by the same thread (but, of course, - /// not by other threads). - /// Using the ScopedLock class is the preferred way to automatically - /// lock and unlock a mutex. -{ -public: - typedef Poco::ScopedLock ScopedLock; - - Mutex(); - /// creates the Mutex. - - ~Mutex(); - /// destroys the Mutex. - - void lock(); - /// Locks the mutex. Blocks if the mutex - /// is held by another thread. - - bool tryLock(); - /// Tries to lock the mutex. Returns false immediately - /// if the mutex is already held by another thread. - /// Returns true if the mutex was successfully locked. - - void unlock(); - /// Unlocks the mutex so that it can be acquired by - /// other threads. - -private: - Mutex(const Mutex&); - Mutex& operator = (const Mutex&); -}; - - -class Foundation_API FastMutex: private FastMutexImpl - /// A FastMutex (mutual exclusion) is similar to a Mutex. - /// Unlike a Mutex, however, a FastMutex is not recursive, - /// which means that a deadlock will occur if the same - /// thread tries to lock a mutex it has already locked again. - /// Locking a FastMutex is faster than locking a recursive Mutex. - /// Using the ScopedLock class is the preferred way to automatically - /// lock and unlock a mutex. -{ -public: - typedef Poco::ScopedLock ScopedLock; - - FastMutex(); - /// creates the Mutex. - - ~FastMutex(); - /// destroys the Mutex. - - void lock(); - /// Locks the mutex. Blocks if the mutex - /// is held by another thread. - - bool tryLock(); - /// Tries to lock the mutex. Returns false immediately - /// if the mutex is already held by another thread. - /// Returns true if the mutex was successfully locked. - - void unlock(); - /// Unlocks the mutex so that it can be acquired by - /// other threads. - -private: - FastMutex(const FastMutex&); - FastMutex& operator = (const FastMutex&); -}; - - -// -// inlines -// -inline void Mutex::lock() -{ - lockImpl(); -} - - -inline bool Mutex::tryLock() -{ - return tryLockImpl(); -} - - -inline void Mutex::unlock() -{ - unlockImpl(); -} - - -inline void FastMutex::lock() -{ - lockImpl(); -} - - -inline bool FastMutex::tryLock() -{ - return tryLockImpl(); -} - - -inline void FastMutex::unlock() -{ - unlockImpl(); -} - - -} // namespace Poco - - -#endif // Foundation_Mutex_INCLUDED +// +// Mutex.h +// +// $Id: //poco/1.2/Foundation/include/Poco/Mutex.h#1 $ +// +// Library: Foundation +// Package: Threading +// Module: Mutex +// +// Definition of the Mutex and FastMutex classes. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_Mutex_INCLUDED +#define Foundation_Mutex_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/ScopedLock.h" + + +#if defined(POCO_OS_FAMILY_WINDOWS) +#include "Poco/Mutex_WIN32.h" +#else +#include "Poco/Mutex_POSIX.h" +#endif + + +namespace Poco { + + +class Foundation_API Mutex: private MutexImpl + /// A Mutex (mutual exclusion) is a synchronization + /// mechanism used to control access to a shared resource + /// in a concurrent (multithreaded) scenario. + /// Mutexes are recursive, that is, the same mutex can be + /// locked multiple times by the same thread (but, of course, + /// not by other threads). + /// Using the ScopedLock class is the preferred way to automatically + /// lock and unlock a mutex. +{ +public: + typedef Poco::ScopedLock ScopedLock; + + Mutex(); + /// creates the Mutex. + + ~Mutex(); + /// destroys the Mutex. + + void lock(); + /// Locks the mutex. Blocks if the mutex + /// is held by another thread. + + bool tryLock(); + /// Tries to lock the mutex. Returns false immediately + /// if the mutex is already held by another thread. + /// Returns true if the mutex was successfully locked. + + void unlock(); + /// Unlocks the mutex so that it can be acquired by + /// other threads. + +private: + Mutex(const Mutex&); + Mutex& operator = (const Mutex&); +}; + + +class Foundation_API FastMutex: private FastMutexImpl + /// A FastMutex (mutual exclusion) is similar to a Mutex. + /// Unlike a Mutex, however, a FastMutex is not recursive, + /// which means that a deadlock will occur if the same + /// thread tries to lock a mutex it has already locked again. + /// Locking a FastMutex is faster than locking a recursive Mutex. + /// Using the ScopedLock class is the preferred way to automatically + /// lock and unlock a mutex. +{ +public: + typedef Poco::ScopedLock ScopedLock; + + FastMutex(); + /// creates the Mutex. + + ~FastMutex(); + /// destroys the Mutex. + + void lock(); + /// Locks the mutex. Blocks if the mutex + /// is held by another thread. + + bool tryLock(); + /// Tries to lock the mutex. Returns false immediately + /// if the mutex is already held by another thread. + /// Returns true if the mutex was successfully locked. + + void unlock(); + /// Unlocks the mutex so that it can be acquired by + /// other threads. + +private: + FastMutex(const FastMutex&); + FastMutex& operator = (const FastMutex&); +}; + + +// +// inlines +// +inline void Mutex::lock() +{ + lockImpl(); +} + + +inline bool Mutex::tryLock() +{ + return tryLockImpl(); +} + + +inline void Mutex::unlock() +{ + unlockImpl(); +} + + +inline void FastMutex::lock() +{ + lockImpl(); +} + + +inline bool FastMutex::tryLock() +{ + return tryLockImpl(); +} + + +inline void FastMutex::unlock() +{ + unlockImpl(); +} + + +} // namespace Poco + + +#endif // Foundation_Mutex_INCLUDED diff --git a/Foundation/include/Poco/Mutex_POSIX.h b/Foundation/include/Poco/Mutex_POSIX.h index a9084bf57..a88a2f2f9 100644 --- a/Foundation/include/Poco/Mutex_POSIX.h +++ b/Foundation/include/Poco/Mutex_POSIX.h @@ -1,108 +1,108 @@ -// -// Mutex_POSIX.h -// -// $Id: //poco/1.2/Foundation/include/Poco/Mutex_POSIX.h#1 $ -// -// Library: Foundation -// Package: Threading -// Module: Mutex -// -// Definition of the MutexImpl and FastMutexImpl classes for POSIX Threads. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_Mutex_POSIX_INCLUDED -#define Foundation_Mutex_POSIX_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/Exception.h" -#include -#include - - -namespace Poco { - - -class Foundation_API MutexImpl -{ -protected: - MutexImpl(); - MutexImpl(bool fast); - ~MutexImpl(); - void lockImpl(); - bool tryLockImpl(); - void unlockImpl(); - -private: - pthread_mutex_t _mutex; -}; - - -class Foundation_API FastMutexImpl: public MutexImpl -{ -protected: - FastMutexImpl(); - ~FastMutexImpl(); -}; - - -// -// inlines -// -inline void MutexImpl::lockImpl() -{ - if (pthread_mutex_lock(&_mutex)) - throw SystemException("cannot lock mutex"); -} - - -inline bool MutexImpl::tryLockImpl() -{ - int rc = pthread_mutex_trylock(&_mutex); - if (rc == 0) - return true; - else if (rc == EBUSY) - return false; - else - throw SystemException("cannot lock mutex"); - -} - - -inline void MutexImpl::unlockImpl() -{ - if (pthread_mutex_unlock(&_mutex)) - throw SystemException("cannot unlock mutex"); -} - - -} // namespace Poco - - -#endif // Foundation_Mutex_POSIX_INCLUDED +// +// Mutex_POSIX.h +// +// $Id: //poco/1.2/Foundation/include/Poco/Mutex_POSIX.h#1 $ +// +// Library: Foundation +// Package: Threading +// Module: Mutex +// +// Definition of the MutexImpl and FastMutexImpl classes for POSIX Threads. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_Mutex_POSIX_INCLUDED +#define Foundation_Mutex_POSIX_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Exception.h" +#include +#include + + +namespace Poco { + + +class Foundation_API MutexImpl +{ +protected: + MutexImpl(); + MutexImpl(bool fast); + ~MutexImpl(); + void lockImpl(); + bool tryLockImpl(); + void unlockImpl(); + +private: + pthread_mutex_t _mutex; +}; + + +class Foundation_API FastMutexImpl: public MutexImpl +{ +protected: + FastMutexImpl(); + ~FastMutexImpl(); +}; + + +// +// inlines +// +inline void MutexImpl::lockImpl() +{ + if (pthread_mutex_lock(&_mutex)) + throw SystemException("cannot lock mutex"); +} + + +inline bool MutexImpl::tryLockImpl() +{ + int rc = pthread_mutex_trylock(&_mutex); + if (rc == 0) + return true; + else if (rc == EBUSY) + return false; + else + throw SystemException("cannot lock mutex"); + +} + + +inline void MutexImpl::unlockImpl() +{ + if (pthread_mutex_unlock(&_mutex)) + throw SystemException("cannot unlock mutex"); +} + + +} // namespace Poco + + +#endif // Foundation_Mutex_POSIX_INCLUDED diff --git a/Foundation/include/Poco/Mutex_WIN32.h b/Foundation/include/Poco/Mutex_WIN32.h index 7dfbd270e..a55d51ac7 100644 --- a/Foundation/include/Poco/Mutex_WIN32.h +++ b/Foundation/include/Poco/Mutex_WIN32.h @@ -1,106 +1,106 @@ -// -// Mutex_WIN32.h -// -// $Id: //poco/1.2/Foundation/include/Poco/Mutex_WIN32.h#1 $ -// -// Library: Foundation -// Package: Threading -// Module: Mutex -// -// Definition of the MutexImpl and FastMutexImpl classes for WIN32. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_Mutex_WIN32_INCLUDED -#define Foundation_Mutex_WIN32_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/Exception.h" -#include - - -namespace Poco { - - -class Foundation_API MutexImpl -{ -protected: - MutexImpl(); - ~MutexImpl(); - void lockImpl(); - bool tryLockImpl(); - void unlockImpl(); - -private: - CRITICAL_SECTION _cs; -}; - - -typedef MutexImpl FastMutexImpl; - - -// -// inlines -// -inline void MutexImpl::lockImpl() -{ - try - { - EnterCriticalSection(&_cs); - } - catch (...) - { - throw SystemException("cannot lock mutex"); - } -} - - -inline bool MutexImpl::tryLockImpl() -{ - try - { - return TryEnterCriticalSection(&_cs) == TRUE; - } - catch (...) - { - } - throw SystemException("cannot lock mutex"); -} - - -inline void MutexImpl::unlockImpl() -{ - LeaveCriticalSection(&_cs); -} - - -} // namespace Poco - - -#endif // Foundation_Mutex_WIN32_INCLUDED +// +// Mutex_WIN32.h +// +// $Id: //poco/1.2/Foundation/include/Poco/Mutex_WIN32.h#1 $ +// +// Library: Foundation +// Package: Threading +// Module: Mutex +// +// Definition of the MutexImpl and FastMutexImpl classes for WIN32. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_Mutex_WIN32_INCLUDED +#define Foundation_Mutex_WIN32_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Exception.h" +#include + + +namespace Poco { + + +class Foundation_API MutexImpl +{ +protected: + MutexImpl(); + ~MutexImpl(); + void lockImpl(); + bool tryLockImpl(); + void unlockImpl(); + +private: + CRITICAL_SECTION _cs; +}; + + +typedef MutexImpl FastMutexImpl; + + +// +// inlines +// +inline void MutexImpl::lockImpl() +{ + try + { + EnterCriticalSection(&_cs); + } + catch (...) + { + throw SystemException("cannot lock mutex"); + } +} + + +inline bool MutexImpl::tryLockImpl() +{ + try + { + return TryEnterCriticalSection(&_cs) == TRUE; + } + catch (...) + { + } + throw SystemException("cannot lock mutex"); +} + + +inline void MutexImpl::unlockImpl() +{ + LeaveCriticalSection(&_cs); +} + + +} // namespace Poco + + +#endif // Foundation_Mutex_WIN32_INCLUDED diff --git a/Foundation/include/Poco/NObserver.h b/Foundation/include/Poco/NObserver.h index 7f2f02410..bf2063aff 100644 --- a/Foundation/include/Poco/NObserver.h +++ b/Foundation/include/Poco/NObserver.h @@ -1,135 +1,135 @@ -// -// NObserver.h -// -// $Id: //poco/1.2/Foundation/include/Poco/NObserver.h#1 $ -// -// Library: Foundation -// Package: Notifications -// Module: NotificationCenter -// -// Definition of the NObserver class template. -// -// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_NObserver_INCLUDED -#define Foundation_NObserver_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/AbstractObserver.h" -#include "Poco/AutoPtr.h" - - -namespace Poco { - - -template -class NObserver: public AbstractObserver - /// This template class implements an adapter that sits between - /// a NotificationCenter and an object receiving notifications - /// from it. It is quite similar in concept to the - /// RunnableAdapter, but provides some NotificationCenter - /// specific additional methods. - /// See the NotificationCenter class for information on how - /// to use this template class. - /// - /// This class template is quite similar to the Observer class - /// template. The only difference is that the NObserver - /// expects the callback function to accept a const AutoPtr& - /// instead of a plain pointer as argument, thus simplifying memory - /// management. -{ -public: - typedef AutoPtr NotificationPtr; - typedef void (C::*Callback)(const NotificationPtr&); - - NObserver(C& object, Callback method): - _pObject(&object), - _method(method) - { - } - - NObserver(const NObserver& observer): - AbstractObserver(observer), - _pObject(observer._pObject), - _method(observer._method) - { - } - - ~NObserver() - { - } - - NObserver& operator = (const NObserver& observer) - { - if (&observer != this) - { - _pObject = observer._pObject; - _method = observer._method; - } - return *this; - } - - void notify(Notification* pNf) const - { - N* pCastNf = dynamic_cast(pNf); - if (pCastNf) - { - NotificationPtr ptr(pCastNf, true); - (_pObject->*_method)(ptr); - } - } - - bool equals(const AbstractObserver& abstractObserver) const - { - const NObserver* pObs = dynamic_cast(&abstractObserver); - return pObs && pObs->_pObject == _pObject && pObs->_method == _method; - } - - bool accepts(Notification* pNf) const - { - return dynamic_cast(pNf) != 0; - } - - AbstractObserver* clone() const - { - return new NObserver(*this); - } - -private: - NObserver(); - - C* _pObject; - Callback _method; -}; - - -} // namespace Poco - - -#endif // Foundation_NObserver_INCLUDED +// +// NObserver.h +// +// $Id: //poco/1.2/Foundation/include/Poco/NObserver.h#1 $ +// +// Library: Foundation +// Package: Notifications +// Module: NotificationCenter +// +// Definition of the NObserver class template. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_NObserver_INCLUDED +#define Foundation_NObserver_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/AbstractObserver.h" +#include "Poco/AutoPtr.h" + + +namespace Poco { + + +template +class NObserver: public AbstractObserver + /// This template class implements an adapter that sits between + /// a NotificationCenter and an object receiving notifications + /// from it. It is quite similar in concept to the + /// RunnableAdapter, but provides some NotificationCenter + /// specific additional methods. + /// See the NotificationCenter class for information on how + /// to use this template class. + /// + /// This class template is quite similar to the Observer class + /// template. The only difference is that the NObserver + /// expects the callback function to accept a const AutoPtr& + /// instead of a plain pointer as argument, thus simplifying memory + /// management. +{ +public: + typedef AutoPtr NotificationPtr; + typedef void (C::*Callback)(const NotificationPtr&); + + NObserver(C& object, Callback method): + _pObject(&object), + _method(method) + { + } + + NObserver(const NObserver& observer): + AbstractObserver(observer), + _pObject(observer._pObject), + _method(observer._method) + { + } + + ~NObserver() + { + } + + NObserver& operator = (const NObserver& observer) + { + if (&observer != this) + { + _pObject = observer._pObject; + _method = observer._method; + } + return *this; + } + + void notify(Notification* pNf) const + { + N* pCastNf = dynamic_cast(pNf); + if (pCastNf) + { + NotificationPtr ptr(pCastNf, true); + (_pObject->*_method)(ptr); + } + } + + bool equals(const AbstractObserver& abstractObserver) const + { + const NObserver* pObs = dynamic_cast(&abstractObserver); + return pObs && pObs->_pObject == _pObject && pObs->_method == _method; + } + + bool accepts(Notification* pNf) const + { + return dynamic_cast(pNf) != 0; + } + + AbstractObserver* clone() const + { + return new NObserver(*this); + } + +private: + NObserver(); + + C* _pObject; + Callback _method; +}; + + +} // namespace Poco + + +#endif // Foundation_NObserver_INCLUDED diff --git a/Foundation/include/Poco/NamedEvent.h b/Foundation/include/Poco/NamedEvent.h index 9d66d7a46..4969481ef 100644 --- a/Foundation/include/Poco/NamedEvent.h +++ b/Foundation/include/Poco/NamedEvent.h @@ -1,118 +1,118 @@ -// -// NamedEvent.h -// -// $Id: //poco/1.2/Foundation/include/Poco/NamedEvent.h#1 $ -// -// Library: Foundation -// Package: Processes -// Module: NamedEvent -// -// Definition of the NamedEvent class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_NamedEvent_INCLUDED -#define Foundation_NamedEvent_INCLUDED - - -#include "Poco/Foundation.h" - - -#if defined(POCO_OS_FAMILY_WINDOWS) && defined(POCO_WIN32_UTF8) -#include "Poco/NamedEvent_WIN32U.h" -#elif defined(POCO_OS_FAMILY_WINDOWS) -#include "Poco/NamedEvent_WIN32.h" -#elif defined(POCO_OS_FAMILY_UNIX) -#include "Poco/NamedEvent_UNIX.h" -#else -#include "Poco/NamedEvent_VMS.h" -#endif - - -namespace Poco { - - -class Foundation_API NamedEvent: public NamedEventImpl - /// An NamedEvent is a global synchronization object - /// that allows one process or thread to signal an - /// other process or thread that a certain event - /// has happened. - /// - /// Unlike an Event, which itself is the unit of synchronization, - /// a NamedEvent refers to a named operating system resource being the - /// unit of synchronization. - /// In other words, there can be multiple instances of NamedEvent referring - /// to the same actual synchronization object. - /// - /// NamedEvents are always autoresetting. - /// - /// There should not be more than one instance of NamedEvent for - /// a given name in a process. Otherwise, the instances may - /// interfere with each other. -{ -public: - NamedEvent(const std::string& name); - /// Creates the event. - - ~NamedEvent(); - /// Destroys the event. - - void set(); - /// Signals the event. - /// The one thread or process waiting for the event - /// can resume execution. - - void wait(); - /// Waits for the event to become signalled. - -private: - NamedEvent(); - NamedEvent(const NamedEvent&); - NamedEvent& operator = (const NamedEvent&); -}; - - -// -// inlines -// -inline void NamedEvent::set() -{ - setImpl(); -} - - -inline void NamedEvent::wait() -{ - waitImpl(); -} - - -} // namespace Poco - - -#endif // Foundation_NamedEvent_INCLUDED +// +// NamedEvent.h +// +// $Id: //poco/1.2/Foundation/include/Poco/NamedEvent.h#1 $ +// +// Library: Foundation +// Package: Processes +// Module: NamedEvent +// +// Definition of the NamedEvent class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_NamedEvent_INCLUDED +#define Foundation_NamedEvent_INCLUDED + + +#include "Poco/Foundation.h" + + +#if defined(POCO_OS_FAMILY_WINDOWS) && defined(POCO_WIN32_UTF8) +#include "Poco/NamedEvent_WIN32U.h" +#elif defined(POCO_OS_FAMILY_WINDOWS) +#include "Poco/NamedEvent_WIN32.h" +#elif defined(POCO_OS_FAMILY_UNIX) +#include "Poco/NamedEvent_UNIX.h" +#else +#include "Poco/NamedEvent_VMS.h" +#endif + + +namespace Poco { + + +class Foundation_API NamedEvent: public NamedEventImpl + /// An NamedEvent is a global synchronization object + /// that allows one process or thread to signal an + /// other process or thread that a certain event + /// has happened. + /// + /// Unlike an Event, which itself is the unit of synchronization, + /// a NamedEvent refers to a named operating system resource being the + /// unit of synchronization. + /// In other words, there can be multiple instances of NamedEvent referring + /// to the same actual synchronization object. + /// + /// NamedEvents are always autoresetting. + /// + /// There should not be more than one instance of NamedEvent for + /// a given name in a process. Otherwise, the instances may + /// interfere with each other. +{ +public: + NamedEvent(const std::string& name); + /// Creates the event. + + ~NamedEvent(); + /// Destroys the event. + + void set(); + /// Signals the event. + /// The one thread or process waiting for the event + /// can resume execution. + + void wait(); + /// Waits for the event to become signalled. + +private: + NamedEvent(); + NamedEvent(const NamedEvent&); + NamedEvent& operator = (const NamedEvent&); +}; + + +// +// inlines +// +inline void NamedEvent::set() +{ + setImpl(); +} + + +inline void NamedEvent::wait() +{ + waitImpl(); +} + + +} // namespace Poco + + +#endif // Foundation_NamedEvent_INCLUDED diff --git a/Foundation/include/Poco/NamedEvent_UNIX.h b/Foundation/include/Poco/NamedEvent_UNIX.h index c824e24ce..a8aa0ad93 100644 --- a/Foundation/include/Poco/NamedEvent_UNIX.h +++ b/Foundation/include/Poco/NamedEvent_UNIX.h @@ -1,77 +1,77 @@ -// -// NamedEvent_UNIX.h -// -// $Id: //poco/1.2/Foundation/include/Poco/NamedEvent_UNIX.h#1 $ -// -// Library: Foundation -// Package: Processes -// Module: NamedEvent -// -// Definition of the NamedEventImpl class for Unix. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_NamedEvent_UNIX_INCLUDED -#define Foundation_NamedEvent_UNIX_INCLUDED - - -#include "Poco/Foundation.h" -#if defined(sun) || defined(__APPLE__) || defined(__osf__) || defined(__QNX__) -#include -#endif - - -namespace Poco { - - -class Foundation_API NamedEventImpl -{ -protected: - NamedEventImpl(const std::string& name); - ~NamedEventImpl(); - void setImpl(); - void waitImpl(); - -private: - std::string getFileName(); - - std::string _name; -#if defined(sun) || defined(__APPLE__) || defined(__osf__) || defined(__QNX__) - sem_t* _sem; -#else - int _lockfd; // lock file descriptor - int _semfd; // file used to identify semaphore - int _semid; // semaphore id -#endif -}; - - -} // namespace Poco - - -#endif // Foundation_NamedEvent_UNIX_INCLUDED +// +// NamedEvent_UNIX.h +// +// $Id: //poco/1.2/Foundation/include/Poco/NamedEvent_UNIX.h#1 $ +// +// Library: Foundation +// Package: Processes +// Module: NamedEvent +// +// Definition of the NamedEventImpl class for Unix. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_NamedEvent_UNIX_INCLUDED +#define Foundation_NamedEvent_UNIX_INCLUDED + + +#include "Poco/Foundation.h" +#if defined(sun) || defined(__APPLE__) || defined(__osf__) || defined(__QNX__) +#include +#endif + + +namespace Poco { + + +class Foundation_API NamedEventImpl +{ +protected: + NamedEventImpl(const std::string& name); + ~NamedEventImpl(); + void setImpl(); + void waitImpl(); + +private: + std::string getFileName(); + + std::string _name; +#if defined(sun) || defined(__APPLE__) || defined(__osf__) || defined(__QNX__) + sem_t* _sem; +#else + int _lockfd; // lock file descriptor + int _semfd; // file used to identify semaphore + int _semid; // semaphore id +#endif +}; + + +} // namespace Poco + + +#endif // Foundation_NamedEvent_UNIX_INCLUDED diff --git a/Foundation/include/Poco/NamedEvent_VMS.h b/Foundation/include/Poco/NamedEvent_VMS.h index 314e0fc1b..48c73b147 100644 --- a/Foundation/include/Poco/NamedEvent_VMS.h +++ b/Foundation/include/Poco/NamedEvent_VMS.h @@ -1,66 +1,66 @@ -// -// NamedEvent_VMS.h -// -// $Id: //poco/1.2/Foundation/include/Poco/NamedEvent_VMS.h#1 $ -// -// Library: Foundation -// Package: Processes -// Module: NamedEvent -// -// Definition of the NamedEventImpl class for OpenVMS. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_NamedEvent_VMS_INCLUDED -#define Foundation_NamedEvent_VMS_INCLUDED - - -#include "Poco/Foundation.h" - - -namespace Poco { - - -class Foundation_API NamedEventImpl -{ -protected: - NamedEventImpl(const std::string& name); - ~NamedEventImpl(); - void setImpl(); - void waitImpl(); - -private: - std::string _name; - unsigned short _mbxChan; -}; - - -} // namespace Poco - - -#endif // Foundation_NamedEvent_VMS_INCLUDED +// +// NamedEvent_VMS.h +// +// $Id: //poco/1.2/Foundation/include/Poco/NamedEvent_VMS.h#1 $ +// +// Library: Foundation +// Package: Processes +// Module: NamedEvent +// +// Definition of the NamedEventImpl class for OpenVMS. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_NamedEvent_VMS_INCLUDED +#define Foundation_NamedEvent_VMS_INCLUDED + + +#include "Poco/Foundation.h" + + +namespace Poco { + + +class Foundation_API NamedEventImpl +{ +protected: + NamedEventImpl(const std::string& name); + ~NamedEventImpl(); + void setImpl(); + void waitImpl(); + +private: + std::string _name; + unsigned short _mbxChan; +}; + + +} // namespace Poco + + +#endif // Foundation_NamedEvent_VMS_INCLUDED diff --git a/Foundation/include/Poco/NamedEvent_WIN32.h b/Foundation/include/Poco/NamedEvent_WIN32.h index 09cd3e75b..c8646483f 100644 --- a/Foundation/include/Poco/NamedEvent_WIN32.h +++ b/Foundation/include/Poco/NamedEvent_WIN32.h @@ -1,67 +1,67 @@ -// -// NamedEvent_WIN32.h -// -// $Id: //poco/1.2/Foundation/include/Poco/NamedEvent_WIN32.h#1 $ -// -// Library: Foundation -// Package: Processes -// Module: NamedEvent -// -// Definition of the NamedEventImpl class for Windows. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_NamedEvent_WIN32_INCLUDED -#define Foundation_NamedEvent_WIN32_INCLUDED - - -#include "Poco/Foundation.h" -#include - - -namespace Poco { - - -class Foundation_API NamedEventImpl -{ -protected: - NamedEventImpl(const std::string& name); - ~NamedEventImpl(); - void setImpl(); - void waitImpl(); - -private: - std::string _name; - HANDLE _event; -}; - - -} // namespace Poco - - -#endif // Foundation_NamedEvent_WIN32_INCLUDED +// +// NamedEvent_WIN32.h +// +// $Id: //poco/1.2/Foundation/include/Poco/NamedEvent_WIN32.h#1 $ +// +// Library: Foundation +// Package: Processes +// Module: NamedEvent +// +// Definition of the NamedEventImpl class for Windows. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_NamedEvent_WIN32_INCLUDED +#define Foundation_NamedEvent_WIN32_INCLUDED + + +#include "Poco/Foundation.h" +#include + + +namespace Poco { + + +class Foundation_API NamedEventImpl +{ +protected: + NamedEventImpl(const std::string& name); + ~NamedEventImpl(); + void setImpl(); + void waitImpl(); + +private: + std::string _name; + HANDLE _event; +}; + + +} // namespace Poco + + +#endif // Foundation_NamedEvent_WIN32_INCLUDED diff --git a/Foundation/include/Poco/NamedEvent_WIN32U.h b/Foundation/include/Poco/NamedEvent_WIN32U.h index a12f55773..bf522c577 100644 --- a/Foundation/include/Poco/NamedEvent_WIN32U.h +++ b/Foundation/include/Poco/NamedEvent_WIN32U.h @@ -1,68 +1,68 @@ -// -// NamedEvent_WIN32U.h -// -// $Id: //poco/1.2/Foundation/include/Poco/NamedEvent_WIN32U.h#1 $ -// -// Library: Foundation -// Package: Processes -// Module: NamedEvent -// -// Definition of the NamedEventImpl class for Windows. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_NamedEvent_WIN32U_INCLUDED -#define Foundation_NamedEvent_WIN32U_INCLUDED - - -#include "Poco/Foundation.h" -#include - - -namespace Poco { - - -class Foundation_API NamedEventImpl -{ -protected: - NamedEventImpl(const std::string& name); - ~NamedEventImpl(); - void setImpl(); - void waitImpl(); - -private: - std::string _name; - std::wstring _uname; - HANDLE _event; -}; - - -} // namespace Poco - - -#endif // Foundation_NamedEvent_WIN32U_INCLUDED +// +// NamedEvent_WIN32U.h +// +// $Id: //poco/1.2/Foundation/include/Poco/NamedEvent_WIN32U.h#1 $ +// +// Library: Foundation +// Package: Processes +// Module: NamedEvent +// +// Definition of the NamedEventImpl class for Windows. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_NamedEvent_WIN32U_INCLUDED +#define Foundation_NamedEvent_WIN32U_INCLUDED + + +#include "Poco/Foundation.h" +#include + + +namespace Poco { + + +class Foundation_API NamedEventImpl +{ +protected: + NamedEventImpl(const std::string& name); + ~NamedEventImpl(); + void setImpl(); + void waitImpl(); + +private: + std::string _name; + std::wstring _uname; + HANDLE _event; +}; + + +} // namespace Poco + + +#endif // Foundation_NamedEvent_WIN32U_INCLUDED diff --git a/Foundation/include/Poco/NamedMutex.h b/Foundation/include/Poco/NamedMutex.h index 48da8b971..737fadc71 100644 --- a/Foundation/include/Poco/NamedMutex.h +++ b/Foundation/include/Poco/NamedMutex.h @@ -1,132 +1,132 @@ -// -// NamedMutex.h -// -// $Id: //poco/1.2/Foundation/include/Poco/NamedMutex.h#1 $ -// -// Library: Foundation -// Package: Processes -// Module: NamedMutex -// -// Definition of the NamedMutex class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_NamedMutex_INCLUDED -#define Foundation_NamedMutex_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/ScopedLock.h" - - -#if defined(POCO_OS_FAMILY_WINDOWS) && defined(POCO_WIN32_UTF8) -#include "Poco/NamedMutex_WIN32U.h" -#elif defined(POCO_OS_FAMILY_WINDOWS) -#include "Poco/NamedMutex_WIN32.h" -#elif defined(POCO_OS_FAMILY_UNIX) -#include "Poco/NamedMutex_UNIX.h" -#else -#include "Poco/NamedMutex_VMS.h" -#endif - - -namespace Poco { - - -class Foundation_API NamedMutex: private NamedMutexImpl - /// A NamedMutex (mutual exclusion) is a global synchronization - /// mechanism used to control access to a shared resource - /// in a concurrent (multi process) scenario. - /// Using the ScopedLock class is the preferred way to automatically - /// lock and unlock a mutex. - /// - /// Unlike a Mutex or a FastMutex, which itself is the unit of synchronization, - /// a NamedMutex refers to a named operating system resource being the - /// unit of synchronization. - /// In other words, there can be multiple instances of NamedMutex referring - /// to the same actual synchronization object. - /// - /// - /// There should not be more than one instance of NamedMutex for - /// a given name in a process. Otherwise, the instances may - /// interfere with each other. -{ -public: - typedef Poco::ScopedLock ScopedLock; - - NamedMutex(const std::string& name); - /// creates the Mutex. - - ~NamedMutex(); - /// destroys the Mutex. - - void lock(); - /// Locks the mutex. Blocks if the mutex - /// is held by another process or thread. - - bool tryLock(); - /// Tries to lock the mutex. Returns false immediately - /// if the mutex is already held by another process or thread. - /// Returns true if the mutex was successfully locked. - - void unlock(); - /// Unlocks the mutex so that it can be acquired by - /// other threads. - -private: - NamedMutex(); - NamedMutex(const NamedMutex&); - NamedMutex& operator = (const NamedMutex&); -}; - - -// -// inlines -// -inline void NamedMutex::lock() -{ - lockImpl(); -} - - -inline bool NamedMutex::tryLock() -{ - return tryLockImpl(); -} - - -inline void NamedMutex::unlock() -{ - unlockImpl(); -} - - -} // namespace Poco - - -#endif // Foundation_NamedMutex_INCLUDED +// +// NamedMutex.h +// +// $Id: //poco/1.2/Foundation/include/Poco/NamedMutex.h#1 $ +// +// Library: Foundation +// Package: Processes +// Module: NamedMutex +// +// Definition of the NamedMutex class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_NamedMutex_INCLUDED +#define Foundation_NamedMutex_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/ScopedLock.h" + + +#if defined(POCO_OS_FAMILY_WINDOWS) && defined(POCO_WIN32_UTF8) +#include "Poco/NamedMutex_WIN32U.h" +#elif defined(POCO_OS_FAMILY_WINDOWS) +#include "Poco/NamedMutex_WIN32.h" +#elif defined(POCO_OS_FAMILY_UNIX) +#include "Poco/NamedMutex_UNIX.h" +#else +#include "Poco/NamedMutex_VMS.h" +#endif + + +namespace Poco { + + +class Foundation_API NamedMutex: private NamedMutexImpl + /// A NamedMutex (mutual exclusion) is a global synchronization + /// mechanism used to control access to a shared resource + /// in a concurrent (multi process) scenario. + /// Using the ScopedLock class is the preferred way to automatically + /// lock and unlock a mutex. + /// + /// Unlike a Mutex or a FastMutex, which itself is the unit of synchronization, + /// a NamedMutex refers to a named operating system resource being the + /// unit of synchronization. + /// In other words, there can be multiple instances of NamedMutex referring + /// to the same actual synchronization object. + /// + /// + /// There should not be more than one instance of NamedMutex for + /// a given name in a process. Otherwise, the instances may + /// interfere with each other. +{ +public: + typedef Poco::ScopedLock ScopedLock; + + NamedMutex(const std::string& name); + /// creates the Mutex. + + ~NamedMutex(); + /// destroys the Mutex. + + void lock(); + /// Locks the mutex. Blocks if the mutex + /// is held by another process or thread. + + bool tryLock(); + /// Tries to lock the mutex. Returns false immediately + /// if the mutex is already held by another process or thread. + /// Returns true if the mutex was successfully locked. + + void unlock(); + /// Unlocks the mutex so that it can be acquired by + /// other threads. + +private: + NamedMutex(); + NamedMutex(const NamedMutex&); + NamedMutex& operator = (const NamedMutex&); +}; + + +// +// inlines +// +inline void NamedMutex::lock() +{ + lockImpl(); +} + + +inline bool NamedMutex::tryLock() +{ + return tryLockImpl(); +} + + +inline void NamedMutex::unlock() +{ + unlockImpl(); +} + + +} // namespace Poco + + +#endif // Foundation_NamedMutex_INCLUDED diff --git a/Foundation/include/Poco/NamedMutex_UNIX.h b/Foundation/include/Poco/NamedMutex_UNIX.h index 3f7631c1a..1fc799f7c 100644 --- a/Foundation/include/Poco/NamedMutex_UNIX.h +++ b/Foundation/include/Poco/NamedMutex_UNIX.h @@ -1,80 +1,80 @@ -// -// NamedMutex_UNIX.h -// -// $Id: //poco/1.2/Foundation/include/Poco/NamedMutex_UNIX.h#1 $ -// -// Library: Foundation -// Package: Processes -// Module: NamedMutex -// -// Definition of the NamedMutexImpl class for Unix. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_NamedMutex_UNIX_INCLUDED -#define Foundation_NamedMutex_UNIX_INCLUDED - - -#include "Poco/Foundation.h" -#include -#include -#if defined(sun) || defined(__APPLE__) || defined(__osf__) || defined(__QNX__) -#include -#endif - - -namespace Poco { - - -class Foundation_API NamedMutexImpl -{ -protected: - NamedMutexImpl(const std::string& name); - ~NamedMutexImpl(); - void lockImpl(); - bool tryLockImpl(); - void unlockImpl(); - -private: - std::string getFileName(); - - std::string _name; -#if defined(sun) || defined(__APPLE__) || defined(__osf__) || defined(__QNX__) - sem_t* _sem; -#else - int _lockfd; // lock file descriptor - int _semfd; // file used to identify semaphore - int _semid; // semaphore id -#endif -}; - - -} // namespace Poco - - -#endif // Foundation_NamedMutex_UNIX_INCLUDED +// +// NamedMutex_UNIX.h +// +// $Id: //poco/1.2/Foundation/include/Poco/NamedMutex_UNIX.h#1 $ +// +// Library: Foundation +// Package: Processes +// Module: NamedMutex +// +// Definition of the NamedMutexImpl class for Unix. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_NamedMutex_UNIX_INCLUDED +#define Foundation_NamedMutex_UNIX_INCLUDED + + +#include "Poco/Foundation.h" +#include +#include +#if defined(sun) || defined(__APPLE__) || defined(__osf__) || defined(__QNX__) +#include +#endif + + +namespace Poco { + + +class Foundation_API NamedMutexImpl +{ +protected: + NamedMutexImpl(const std::string& name); + ~NamedMutexImpl(); + void lockImpl(); + bool tryLockImpl(); + void unlockImpl(); + +private: + std::string getFileName(); + + std::string _name; +#if defined(sun) || defined(__APPLE__) || defined(__osf__) || defined(__QNX__) + sem_t* _sem; +#else + int _lockfd; // lock file descriptor + int _semfd; // file used to identify semaphore + int _semid; // semaphore id +#endif +}; + + +} // namespace Poco + + +#endif // Foundation_NamedMutex_UNIX_INCLUDED diff --git a/Foundation/include/Poco/NamedMutex_VMS.h b/Foundation/include/Poco/NamedMutex_VMS.h index 4dde0a069..8e8f14703 100644 --- a/Foundation/include/Poco/NamedMutex_VMS.h +++ b/Foundation/include/Poco/NamedMutex_VMS.h @@ -1,70 +1,70 @@ -// -// NamedMutex_VMS.h -// -// $Id: //poco/1.2/Foundation/include/Poco/NamedMutex_VMS.h#1 $ -// -// Library: Foundation -// Package: Processes -// Module: NamedMutex -// -// Definition of the NamedMutexImpl class for OpenVMS. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_NamedMutex_VMS_INCLUDED -#define Foundation_NamedMutex_VMS_INCLUDED - - -#include "Poco/Foundation.h" -#include -#include - - -namespace Poco { - - -class Foundation_API NamedMutexImpl -{ -protected: - NamedMutexImpl(const std::string& name); - ~NamedMutexImpl(); - void lockImpl(); - bool tryLockImpl(); - void unlockImpl(); - -private: - std::string _name; - struct dsc$descriptor_s _nameDesc; - int _lksb[4]; -}; - - -} // namespace Poco - - -#endif // Foundation_NamedMutex_VMS_INCLUDED +// +// NamedMutex_VMS.h +// +// $Id: //poco/1.2/Foundation/include/Poco/NamedMutex_VMS.h#1 $ +// +// Library: Foundation +// Package: Processes +// Module: NamedMutex +// +// Definition of the NamedMutexImpl class for OpenVMS. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_NamedMutex_VMS_INCLUDED +#define Foundation_NamedMutex_VMS_INCLUDED + + +#include "Poco/Foundation.h" +#include +#include + + +namespace Poco { + + +class Foundation_API NamedMutexImpl +{ +protected: + NamedMutexImpl(const std::string& name); + ~NamedMutexImpl(); + void lockImpl(); + bool tryLockImpl(); + void unlockImpl(); + +private: + std::string _name; + struct dsc$descriptor_s _nameDesc; + int _lksb[4]; +}; + + +} // namespace Poco + + +#endif // Foundation_NamedMutex_VMS_INCLUDED diff --git a/Foundation/include/Poco/NamedMutex_WIN32.h b/Foundation/include/Poco/NamedMutex_WIN32.h index 260ea1cdb..eca88c142 100644 --- a/Foundation/include/Poco/NamedMutex_WIN32.h +++ b/Foundation/include/Poco/NamedMutex_WIN32.h @@ -1,68 +1,68 @@ -// -// NamedMutex_WIN32.h -// -// $Id: //poco/1.2/Foundation/include/Poco/NamedMutex_WIN32.h#1 $ -// -// Library: Foundation -// Package: Processes -// Module: NamedMutex -// -// Definition of the NamedMutexImpl class for Windows. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_NamedMutex_WIN32_INCLUDED -#define Foundation_NamedMutex_WIN32_INCLUDED - - -#include "Poco/Foundation.h" -#include - - -namespace Poco { - - -class Foundation_API NamedMutexImpl -{ -protected: - NamedMutexImpl(const std::string& name); - ~NamedMutexImpl(); - void lockImpl(); - bool tryLockImpl(); - void unlockImpl(); - -private: - std::string _name; - HANDLE _mutex; -}; - - -} // namespace Poco - - -#endif // Foundation_NamedMutex_WIN32_INCLUDED +// +// NamedMutex_WIN32.h +// +// $Id: //poco/1.2/Foundation/include/Poco/NamedMutex_WIN32.h#1 $ +// +// Library: Foundation +// Package: Processes +// Module: NamedMutex +// +// Definition of the NamedMutexImpl class for Windows. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_NamedMutex_WIN32_INCLUDED +#define Foundation_NamedMutex_WIN32_INCLUDED + + +#include "Poco/Foundation.h" +#include + + +namespace Poco { + + +class Foundation_API NamedMutexImpl +{ +protected: + NamedMutexImpl(const std::string& name); + ~NamedMutexImpl(); + void lockImpl(); + bool tryLockImpl(); + void unlockImpl(); + +private: + std::string _name; + HANDLE _mutex; +}; + + +} // namespace Poco + + +#endif // Foundation_NamedMutex_WIN32_INCLUDED diff --git a/Foundation/include/Poco/NamedMutex_WIN32U.h b/Foundation/include/Poco/NamedMutex_WIN32U.h index 576a059d1..ec428f463 100644 --- a/Foundation/include/Poco/NamedMutex_WIN32U.h +++ b/Foundation/include/Poco/NamedMutex_WIN32U.h @@ -1,69 +1,69 @@ -// -// NamedMutex_WIN32U.h -// -// $Id: //poco/1.2/Foundation/include/Poco/NamedMutex_WIN32U.h#1 $ -// -// Library: Foundation -// Package: Processes -// Module: NamedMutex -// -// Definition of the NamedMutexImpl class for Windows. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_NamedMutex_WIN32U_INCLUDED -#define Foundation_NamedMutex_WIN32U_INCLUDED - - -#include "Poco/Foundation.h" -#include - - -namespace Poco { - - -class Foundation_API NamedMutexImpl -{ -protected: - NamedMutexImpl(const std::string& name); - ~NamedMutexImpl(); - void lockImpl(); - bool tryLockImpl(); - void unlockImpl(); - -private: - std::string _name; - std::wstring _uname; - HANDLE _mutex; -}; - - -} // namespace Poco - - -#endif // Foundation_NamedMutex_WIN32U_INCLUDED +// +// NamedMutex_WIN32U.h +// +// $Id: //poco/1.2/Foundation/include/Poco/NamedMutex_WIN32U.h#1 $ +// +// Library: Foundation +// Package: Processes +// Module: NamedMutex +// +// Definition of the NamedMutexImpl class for Windows. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_NamedMutex_WIN32U_INCLUDED +#define Foundation_NamedMutex_WIN32U_INCLUDED + + +#include "Poco/Foundation.h" +#include + + +namespace Poco { + + +class Foundation_API NamedMutexImpl +{ +protected: + NamedMutexImpl(const std::string& name); + ~NamedMutexImpl(); + void lockImpl(); + bool tryLockImpl(); + void unlockImpl(); + +private: + std::string _name; + std::wstring _uname; + HANDLE _mutex; +}; + + +} // namespace Poco + + +#endif // Foundation_NamedMutex_WIN32U_INCLUDED diff --git a/Foundation/include/Poco/NestedDiagnosticContext.h b/Foundation/include/Poco/NestedDiagnosticContext.h index 86599cdf0..786a6ca99 100644 --- a/Foundation/include/Poco/NestedDiagnosticContext.h +++ b/Foundation/include/Poco/NestedDiagnosticContext.h @@ -1,188 +1,188 @@ -// -// NestedDiagnosticContext.h -// -// $Id: //poco/1.2/Foundation/include/Poco/NestedDiagnosticContext.h#1 $ -// -// Library: Foundation -// Package: Core -// Module: NestedDiagnosticContext -// -// Definition of the NestedDiagnosticContext class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_NestedDiagnosticContext_INCLUDED -#define Foundation_NestedDiagnosticContext_INCLUDED - - -#include "Poco/Foundation.h" -#include -#include - - -namespace Poco { - - -class NDCScope; - - -class Foundation_API NestedDiagnosticContext - /// This class implements a Nested Diagnostic Context (NDC), - /// as described in Neil Harrison's article "Patterns for Logging - /// Diagnostic Messages" in "Pattern Languages of Program Design 3" - /// (Addison-Wesley). - /// - /// A NDC maintains a stack of context information, consisting of - /// an informational string (e.g., a method name), as well as an - /// optional source code line number and file name. - /// NDCs are especially useful for tagging log messages with - /// context information which is very helpful in a multithreaded - /// server scenario. - /// Every thread has its own private NDC, which is automatically - /// created when needed and destroyed when the thread terminates. - /// - /// The NDCScope (or NDC::Scope) class can be used to automatically - /// push information at the beginning of a scope, and to pop it - /// at the end. - /// The poco_ndc(info) macro augments the information with a - /// source code line number and file name. -{ -public: - typedef NDCScope Scope; - - NestedDiagnosticContext(); - /// Creates the NestedDiagnosticContext. - - NestedDiagnosticContext(const NestedDiagnosticContext& ctx); - /// Copy constructor. - - ~NestedDiagnosticContext(); - /// Destroys the NestedDiagnosticContext. - - NestedDiagnosticContext& operator = (const NestedDiagnosticContext& ctx); - /// Assignment operator. - - void push(const std::string& info); - /// Pushes a context (without line number and filename) onto the stack. - - void push(const std::string& info, int line, const char* filename); - /// Pushes a context (including line number and filename) - /// onto the stack. Filename must be a static string, such as the - /// one produced by the __FILE__ preprocessor macro. - - void pop(); - /// Pops the top-most context off the stack. - - int depth() const; - /// Returns the depth (number of contexts) of the stack. - - std::string toString() const; - /// Returns the stack as a string with entries - /// delimited by colons. The string does not contain - /// line numbers and filenames. - - void dump(std::ostream& ostr) const; - /// Dumps the stack (including line number and filenames) - /// to the given stream. The entries are delimited by - /// a newline. - - void dump(std::ostream& ostr, const std::string& delimiter) const; - /// Dumps the stack (including line number and filenames) - /// to the given stream. - - void clear(); - /// Clears the NDC stack. - - static NestedDiagnosticContext& current(); - /// Returns the current thread's NDC. - -private: - struct Context - { - std::string info; - const char* file; - int line; - }; - typedef std::vector Stack; - - Stack _stack; -}; - - -typedef NestedDiagnosticContext NDC; - - -class Foundation_API NDCScope - /// This class can be used to automatically push a context onto - /// the NDC stack at the beginning of a scope, and to pop - /// the context at the end of the scope. -{ -public: - NDCScope(const std::string& info); - /// Pushes a context on the stack. - - NDCScope(const std::string& info, int line, const char* filename); - /// Pushes a context on the stack. - - ~NDCScope(); - /// Pops the top-most context off the stack. -}; - - -// -// inlines -// -inline NDCScope::NDCScope(const std::string& info) -{ - NestedDiagnosticContext::current().push(info); -} - - -inline NDCScope::NDCScope(const std::string& info, int line, const char* filename) -{ - NestedDiagnosticContext::current().push(info, line, filename); -} - - -inline NDCScope::~NDCScope() -{ - NestedDiagnosticContext::current().pop(); -} - - -// -// helper macros -// -#define poco_ndc(msg) \ - Poco::NDCScope _theNdcScope(msg, __LINE__, __FILE__) - - -} // namespace Poco - - -#endif // Foundation_NestedDiagnosticContext_INCLUDED +// +// NestedDiagnosticContext.h +// +// $Id: //poco/1.2/Foundation/include/Poco/NestedDiagnosticContext.h#1 $ +// +// Library: Foundation +// Package: Core +// Module: NestedDiagnosticContext +// +// Definition of the NestedDiagnosticContext class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_NestedDiagnosticContext_INCLUDED +#define Foundation_NestedDiagnosticContext_INCLUDED + + +#include "Poco/Foundation.h" +#include +#include + + +namespace Poco { + + +class NDCScope; + + +class Foundation_API NestedDiagnosticContext + /// This class implements a Nested Diagnostic Context (NDC), + /// as described in Neil Harrison's article "Patterns for Logging + /// Diagnostic Messages" in "Pattern Languages of Program Design 3" + /// (Addison-Wesley). + /// + /// A NDC maintains a stack of context information, consisting of + /// an informational string (e.g., a method name), as well as an + /// optional source code line number and file name. + /// NDCs are especially useful for tagging log messages with + /// context information which is very helpful in a multithreaded + /// server scenario. + /// Every thread has its own private NDC, which is automatically + /// created when needed and destroyed when the thread terminates. + /// + /// The NDCScope (or NDC::Scope) class can be used to automatically + /// push information at the beginning of a scope, and to pop it + /// at the end. + /// The poco_ndc(info) macro augments the information with a + /// source code line number and file name. +{ +public: + typedef NDCScope Scope; + + NestedDiagnosticContext(); + /// Creates the NestedDiagnosticContext. + + NestedDiagnosticContext(const NestedDiagnosticContext& ctx); + /// Copy constructor. + + ~NestedDiagnosticContext(); + /// Destroys the NestedDiagnosticContext. + + NestedDiagnosticContext& operator = (const NestedDiagnosticContext& ctx); + /// Assignment operator. + + void push(const std::string& info); + /// Pushes a context (without line number and filename) onto the stack. + + void push(const std::string& info, int line, const char* filename); + /// Pushes a context (including line number and filename) + /// onto the stack. Filename must be a static string, such as the + /// one produced by the __FILE__ preprocessor macro. + + void pop(); + /// Pops the top-most context off the stack. + + int depth() const; + /// Returns the depth (number of contexts) of the stack. + + std::string toString() const; + /// Returns the stack as a string with entries + /// delimited by colons. The string does not contain + /// line numbers and filenames. + + void dump(std::ostream& ostr) const; + /// Dumps the stack (including line number and filenames) + /// to the given stream. The entries are delimited by + /// a newline. + + void dump(std::ostream& ostr, const std::string& delimiter) const; + /// Dumps the stack (including line number and filenames) + /// to the given stream. + + void clear(); + /// Clears the NDC stack. + + static NestedDiagnosticContext& current(); + /// Returns the current thread's NDC. + +private: + struct Context + { + std::string info; + const char* file; + int line; + }; + typedef std::vector Stack; + + Stack _stack; +}; + + +typedef NestedDiagnosticContext NDC; + + +class Foundation_API NDCScope + /// This class can be used to automatically push a context onto + /// the NDC stack at the beginning of a scope, and to pop + /// the context at the end of the scope. +{ +public: + NDCScope(const std::string& info); + /// Pushes a context on the stack. + + NDCScope(const std::string& info, int line, const char* filename); + /// Pushes a context on the stack. + + ~NDCScope(); + /// Pops the top-most context off the stack. +}; + + +// +// inlines +// +inline NDCScope::NDCScope(const std::string& info) +{ + NestedDiagnosticContext::current().push(info); +} + + +inline NDCScope::NDCScope(const std::string& info, int line, const char* filename) +{ + NestedDiagnosticContext::current().push(info, line, filename); +} + + +inline NDCScope::~NDCScope() +{ + NestedDiagnosticContext::current().pop(); +} + + +// +// helper macros +// +#define poco_ndc(msg) \ + Poco::NDCScope _theNdcScope(msg, __LINE__, __FILE__) + + +} // namespace Poco + + +#endif // Foundation_NestedDiagnosticContext_INCLUDED diff --git a/Foundation/include/Poco/Notification.h b/Foundation/include/Poco/Notification.h index 6961a3c72..07584bf6f 100644 --- a/Foundation/include/Poco/Notification.h +++ b/Foundation/include/Poco/Notification.h @@ -1,74 +1,74 @@ -// -// Notification.h -// -// $Id: //poco/1.2/Foundation/include/Poco/Notification.h#1 $ -// -// Library: Foundation -// Package: Notifications -// Module: Notification -// -// Definition of the Notification class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_Notification_INCLUDED -#define Foundation_Notification_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/Mutex.h" -#include "Poco/RefCountedObject.h" - - -namespace Poco { - - -class Foundation_API Notification: public RefCountedObject - /// The base class for all notification classes used - /// with the NotificationCenter and the NotificationQueue - /// classes. - /// The Notification class can be used with the AutoPtr - /// template class. -{ -public: - Notification(); - /// Creates the notification. - - virtual std::string name() const; - /// Returns the name of the notification. - /// The default implementation returns the class name. - -protected: - virtual ~Notification(); -}; - - -} // namespace Poco - - -#endif // Foundation_Notification_INCLUDED +// +// Notification.h +// +// $Id: //poco/1.2/Foundation/include/Poco/Notification.h#1 $ +// +// Library: Foundation +// Package: Notifications +// Module: Notification +// +// Definition of the Notification class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_Notification_INCLUDED +#define Foundation_Notification_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Mutex.h" +#include "Poco/RefCountedObject.h" + + +namespace Poco { + + +class Foundation_API Notification: public RefCountedObject + /// The base class for all notification classes used + /// with the NotificationCenter and the NotificationQueue + /// classes. + /// The Notification class can be used with the AutoPtr + /// template class. +{ +public: + Notification(); + /// Creates the notification. + + virtual std::string name() const; + /// Returns the name of the notification. + /// The default implementation returns the class name. + +protected: + virtual ~Notification(); +}; + + +} // namespace Poco + + +#endif // Foundation_Notification_INCLUDED diff --git a/Foundation/include/Poco/NotificationCenter.h b/Foundation/include/Poco/NotificationCenter.h index f0b91f0bc..3854071cd 100644 --- a/Foundation/include/Poco/NotificationCenter.h +++ b/Foundation/include/Poco/NotificationCenter.h @@ -1,152 +1,152 @@ -// -// NotificationCenter.h -// -// $Id: //poco/1.2/Foundation/include/Poco/NotificationCenter.h#2 $ -// -// Library: Foundation -// Package: Notifications -// Module: NotificationCenter -// -// Definition of the NotificationCenter class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_NotificationCenter_INCLUDED -#define Foundation_NotificationCenter_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/Mutex.h" -#include - - -namespace Poco { - - -class Notification; -class AbstractObserver; - - -class Foundation_API NotificationCenter - /// A NotificationCenter is essentially a notification dispatcher. - /// It notifies all observers of notifications meeting specific criteria. - /// This information is encapsulated in Notification objects. - /// Client objects register themselves with the notification center as observers of - /// specific notifications posted by other objects. When an event occurs, an object - /// posts an appropriate notification to the notification center. The notification - /// center invokes the registered method on each matching observer, passing the notification - /// as argument. - /// - /// The order in which observers receive notifications is undefined. - /// It is possible for the posting object and the observing object to be the same. - /// The NotificationCenter delivers notifications to observers synchronously. - /// In other words the postNotification() method does not return until all observers have - /// received and processed the notification. - /// If an observer throws an exception while handling a notification, the NotificationCenter - /// stops dispatching the notification and postNotification() rethrows the exception. - /// - /// In a multithreaded scenario, notifications are always delivered in the thread in which the - /// notification was posted, which may not be the same thread in which an observer registered itself. - /// - /// The NotificationCenter class is basically a C++ implementation of the NSNotificationCenter class - /// found in Apple's Cocoa (or OpenStep). - /// - /// While handling a notification, an observer can unregister itself from the notification center, - /// or it can register or unregister other observers. Observers added during a dispatch cycle - /// will not receive the current notification. - /// - /// The method receiving the notification must be implemented as - /// void handleNotification(MyNotification* pNf); - /// The handler method gets co-ownership of the Notification object - /// and must release it when done. This is best done with an AutoPtr: - /// void MyClass::handleNotification(MyNotification* pNf) - /// { - /// AutoPtr nf(pNf); - /// ... - /// } - /// - /// Alternatively, the NObserver class template can be used to register a callback - /// method. In this case, the callback method receives the Notification in an - /// AutoPtr and thus does not have to deal with object ownership issues: - /// void MyClass::handleNotification(const AutoPtr& pNf) - /// { - /// ... - /// } -{ -public: - NotificationCenter(); - /// Creates the NotificationCenter. - - ~NotificationCenter(); - /// Destroys the NotificationCenter. - - void addObserver(const AbstractObserver& observer); - /// Registers an observer with the NotificationCenter. - /// Usage: - /// Observer obs(*this, &MyClass::handleNotification); - /// notificationCenter.addObserver(obs); - /// - /// Alternatively, the NObserver template class can be used instead of Observer. - - void removeObserver(const AbstractObserver& observer); - /// Unregisters an observer with the NotificationCenter. - - void postNotification(Notification* pNotification); - /// Posts a notification to the NotificationCenter. - /// The NotificationCenter then delivers the notification - /// to all interested observers. - /// If an observer throws an exception, dispatching terminates - /// and the exception is rethrown to the caller. - /// Ownership of the notification object is claimed and the - /// notification is released before returning. Therefore, - /// a call like - /// notificationCenter.postNotification(new MyNotification); - /// does not result in a memory leak. - - bool hasObservers() const; - /// Returns true iff there is at least one registered observer. - /// - /// Can be used to improve performance if an expensive notification - /// shall only be created and posted if there are any observers. - - static NotificationCenter& defaultCenter(); - /// Returns a reference to the default - /// NotificationCenter. - -private: - typedef std::list ObserverList; - - ObserverList _observers; - mutable Mutex _mutex; -}; - - -} // namespace Poco - - -#endif // Foundation_NotificationCenter_INCLUDED +// +// NotificationCenter.h +// +// $Id: //poco/1.2/Foundation/include/Poco/NotificationCenter.h#2 $ +// +// Library: Foundation +// Package: Notifications +// Module: NotificationCenter +// +// Definition of the NotificationCenter class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_NotificationCenter_INCLUDED +#define Foundation_NotificationCenter_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Mutex.h" +#include + + +namespace Poco { + + +class Notification; +class AbstractObserver; + + +class Foundation_API NotificationCenter + /// A NotificationCenter is essentially a notification dispatcher. + /// It notifies all observers of notifications meeting specific criteria. + /// This information is encapsulated in Notification objects. + /// Client objects register themselves with the notification center as observers of + /// specific notifications posted by other objects. When an event occurs, an object + /// posts an appropriate notification to the notification center. The notification + /// center invokes the registered method on each matching observer, passing the notification + /// as argument. + /// + /// The order in which observers receive notifications is undefined. + /// It is possible for the posting object and the observing object to be the same. + /// The NotificationCenter delivers notifications to observers synchronously. + /// In other words the postNotification() method does not return until all observers have + /// received and processed the notification. + /// If an observer throws an exception while handling a notification, the NotificationCenter + /// stops dispatching the notification and postNotification() rethrows the exception. + /// + /// In a multithreaded scenario, notifications are always delivered in the thread in which the + /// notification was posted, which may not be the same thread in which an observer registered itself. + /// + /// The NotificationCenter class is basically a C++ implementation of the NSNotificationCenter class + /// found in Apple's Cocoa (or OpenStep). + /// + /// While handling a notification, an observer can unregister itself from the notification center, + /// or it can register or unregister other observers. Observers added during a dispatch cycle + /// will not receive the current notification. + /// + /// The method receiving the notification must be implemented as + /// void handleNotification(MyNotification* pNf); + /// The handler method gets co-ownership of the Notification object + /// and must release it when done. This is best done with an AutoPtr: + /// void MyClass::handleNotification(MyNotification* pNf) + /// { + /// AutoPtr nf(pNf); + /// ... + /// } + /// + /// Alternatively, the NObserver class template can be used to register a callback + /// method. In this case, the callback method receives the Notification in an + /// AutoPtr and thus does not have to deal with object ownership issues: + /// void MyClass::handleNotification(const AutoPtr& pNf) + /// { + /// ... + /// } +{ +public: + NotificationCenter(); + /// Creates the NotificationCenter. + + ~NotificationCenter(); + /// Destroys the NotificationCenter. + + void addObserver(const AbstractObserver& observer); + /// Registers an observer with the NotificationCenter. + /// Usage: + /// Observer obs(*this, &MyClass::handleNotification); + /// notificationCenter.addObserver(obs); + /// + /// Alternatively, the NObserver template class can be used instead of Observer. + + void removeObserver(const AbstractObserver& observer); + /// Unregisters an observer with the NotificationCenter. + + void postNotification(Notification* pNotification); + /// Posts a notification to the NotificationCenter. + /// The NotificationCenter then delivers the notification + /// to all interested observers. + /// If an observer throws an exception, dispatching terminates + /// and the exception is rethrown to the caller. + /// Ownership of the notification object is claimed and the + /// notification is released before returning. Therefore, + /// a call like + /// notificationCenter.postNotification(new MyNotification); + /// does not result in a memory leak. + + bool hasObservers() const; + /// Returns true iff there is at least one registered observer. + /// + /// Can be used to improve performance if an expensive notification + /// shall only be created and posted if there are any observers. + + static NotificationCenter& defaultCenter(); + /// Returns a reference to the default + /// NotificationCenter. + +private: + typedef std::list ObserverList; + + ObserverList _observers; + mutable Mutex _mutex; +}; + + +} // namespace Poco + + +#endif // Foundation_NotificationCenter_INCLUDED diff --git a/Foundation/include/Poco/NotificationQueue.h b/Foundation/include/Poco/NotificationQueue.h index d9034b5fc..bf8e030d8 100644 --- a/Foundation/include/Poco/NotificationQueue.h +++ b/Foundation/include/Poco/NotificationQueue.h @@ -1,165 +1,165 @@ -// -// NotificationQueue.h -// -// $Id: //poco/1.2/Foundation/include/Poco/NotificationQueue.h#1 $ -// -// Library: Foundation -// Package: Notifications -// Module: NotificationQueue -// -// Definition of the NotificationQueue class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_NotificationQueue_INCLUDED -#define Foundation_NotificationQueue_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/Mutex.h" -#include "Poco/Event.h" -#include - - -namespace Poco { - - -class Notification; -class NotificationCenter; - - -class Foundation_API NotificationQueue - /// A NotificationQueue object provides a way to implement asynchronous - /// notifications. This is especially useful for sending notifications - /// from one thread to another, for example from a background thread to - /// the main (user interface) thread. - /// - /// The NotificationQueue can also be used to distribute work from - /// a controlling thread to one or more worker threads. Each worker thread - /// repeatedly calls waitDequeueNotification() and processes the - /// returned notification. Special care must be taken when shutting - /// down a queue with worker threads waiting for notifications. - /// The recommended sequence to shut down and destroy the queue is to - /// 1. set a termination flag for every worker thread - /// 2. call the wakeUpAll() method - /// 3. join each worker thread - /// 4. destroy the notification queue. -{ -public: - NotificationQueue(); - /// Creates the NotificationQueue. - - ~NotificationQueue(); - /// Destroys the NotificationQueue. - - void enqueueNotification(Notification* pNotification); - /// Enqueues the given notification by adding it to - /// the end of the queue (FIFO). - /// The queue takes ownership of the notification, thus - /// a call like - /// notificationQueue.enqueueNotification(new MyNotification); - /// does not result in a memory leak. - - void enqueueUrgentNotification(Notification* pNotification); - /// Enqueues the given notification by adding it to - /// the front of the queue (LIFO). The event therefore gets processed - /// before all other events already in the queue. - /// The queue takes ownership of the notification, thus - /// a call like - /// notificationQueue.enqueueUrgentNotification(new MyNotification); - /// does not result in a memory leak. - - Notification* dequeueNotification(); - /// Dequeues the next pending notification. - /// Returns 0 (null) if no notification is available. - /// The caller gains ownership of the notification and - /// is expected to release it when done with it. - - Notification* waitDequeueNotification(); - /// Dequeues the next pending notification. - /// If no notification is available, waits for a notification - /// to be enqueued. - /// The caller gains ownership of the notification and - /// is expected to release it when done with it. - /// This method returns 0 (null) if wakeUpWaitingThreads() - /// has been called by another thread. - - Notification* waitDequeueNotification(long milliseconds); - /// Dequeues the next pending notification. - /// If no notification is available, waits for a notification - /// to be enqueued up to the specified time. - /// Returns 0 (null) if no notification is available. - /// The caller gains ownership of the notification and - /// is expected to release it when done with it. - - void dispatch(NotificationCenter& notificationCenter); - /// Dispatches all queued notifications to the given - /// notification center. - - void wakeUpAll(); - /// Wakes up all threads that wait for a notification. - - bool empty() const; - /// Returns true iff the queue is empty. - - int size() const; - /// Returns the number of notifications in the queue. - - void clear(); - /// Removes all notifications from the queue. - - bool hasIdleThreads() const; - /// Returns true if the queue has at least one thread waiting - /// for a notification. - - static NotificationQueue& defaultQueue(); - /// Returns a reference to the default - /// NotificationQueue. - -protected: - Notification* dequeueOne(); - -private: - typedef std::deque NfQueue; - struct WaitInfo - { - Notification* pNf; - Event nfAvailable; - }; - typedef std::deque WaitQueue; - - NfQueue _nfQueue; - WaitQueue _waitQueue; - mutable FastMutex _mutex; -}; - - -} // namespace Poco - - -#endif // Foundation_NotificationQueue_INCLUDED +// +// NotificationQueue.h +// +// $Id: //poco/1.2/Foundation/include/Poco/NotificationQueue.h#1 $ +// +// Library: Foundation +// Package: Notifications +// Module: NotificationQueue +// +// Definition of the NotificationQueue class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_NotificationQueue_INCLUDED +#define Foundation_NotificationQueue_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Mutex.h" +#include "Poco/Event.h" +#include + + +namespace Poco { + + +class Notification; +class NotificationCenter; + + +class Foundation_API NotificationQueue + /// A NotificationQueue object provides a way to implement asynchronous + /// notifications. This is especially useful for sending notifications + /// from one thread to another, for example from a background thread to + /// the main (user interface) thread. + /// + /// The NotificationQueue can also be used to distribute work from + /// a controlling thread to one or more worker threads. Each worker thread + /// repeatedly calls waitDequeueNotification() and processes the + /// returned notification. Special care must be taken when shutting + /// down a queue with worker threads waiting for notifications. + /// The recommended sequence to shut down and destroy the queue is to + /// 1. set a termination flag for every worker thread + /// 2. call the wakeUpAll() method + /// 3. join each worker thread + /// 4. destroy the notification queue. +{ +public: + NotificationQueue(); + /// Creates the NotificationQueue. + + ~NotificationQueue(); + /// Destroys the NotificationQueue. + + void enqueueNotification(Notification* pNotification); + /// Enqueues the given notification by adding it to + /// the end of the queue (FIFO). + /// The queue takes ownership of the notification, thus + /// a call like + /// notificationQueue.enqueueNotification(new MyNotification); + /// does not result in a memory leak. + + void enqueueUrgentNotification(Notification* pNotification); + /// Enqueues the given notification by adding it to + /// the front of the queue (LIFO). The event therefore gets processed + /// before all other events already in the queue. + /// The queue takes ownership of the notification, thus + /// a call like + /// notificationQueue.enqueueUrgentNotification(new MyNotification); + /// does not result in a memory leak. + + Notification* dequeueNotification(); + /// Dequeues the next pending notification. + /// Returns 0 (null) if no notification is available. + /// The caller gains ownership of the notification and + /// is expected to release it when done with it. + + Notification* waitDequeueNotification(); + /// Dequeues the next pending notification. + /// If no notification is available, waits for a notification + /// to be enqueued. + /// The caller gains ownership of the notification and + /// is expected to release it when done with it. + /// This method returns 0 (null) if wakeUpWaitingThreads() + /// has been called by another thread. + + Notification* waitDequeueNotification(long milliseconds); + /// Dequeues the next pending notification. + /// If no notification is available, waits for a notification + /// to be enqueued up to the specified time. + /// Returns 0 (null) if no notification is available. + /// The caller gains ownership of the notification and + /// is expected to release it when done with it. + + void dispatch(NotificationCenter& notificationCenter); + /// Dispatches all queued notifications to the given + /// notification center. + + void wakeUpAll(); + /// Wakes up all threads that wait for a notification. + + bool empty() const; + /// Returns true iff the queue is empty. + + int size() const; + /// Returns the number of notifications in the queue. + + void clear(); + /// Removes all notifications from the queue. + + bool hasIdleThreads() const; + /// Returns true if the queue has at least one thread waiting + /// for a notification. + + static NotificationQueue& defaultQueue(); + /// Returns a reference to the default + /// NotificationQueue. + +protected: + Notification* dequeueOne(); + +private: + typedef std::deque NfQueue; + struct WaitInfo + { + Notification* pNf; + Event nfAvailable; + }; + typedef std::deque WaitQueue; + + NfQueue _nfQueue; + WaitQueue _waitQueue; + mutable FastMutex _mutex; +}; + + +} // namespace Poco + + +#endif // Foundation_NotificationQueue_INCLUDED diff --git a/Foundation/include/Poco/NotificationStrategy.h b/Foundation/include/Poco/NotificationStrategy.h index ef8ceaad8..60d9324cf 100644 --- a/Foundation/include/Poco/NotificationStrategy.h +++ b/Foundation/include/Poco/NotificationStrategy.h @@ -1,79 +1,79 @@ -// -// NotificationStrategy.h -// -// $Id: //poco/1.2/Foundation/include/Poco/NotificationStrategy.h#1 $ -// -// Library: Foundation -// Package: Events -// Module: NotificationStrategy -// -// Definition of the NotificationStrategy interface. -// -// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_NotificationStrategy_INCLUDED -#define Foundation_NotificationStrategy_INCLUDED - - -#include "Poco/Foundation.h" - - -namespace Poco { - - -template -class NotificationStrategy - /// The interface that all notification strategies must implement. -{ -public: - NotificationStrategy() - { - } - - virtual ~NotificationStrategy() - { - } - - virtual void notify(const void* sender, TArgs& arguments) = 0; - /// Sends a notification to all registered delegates, - - virtual void add(const TDelegate& pDelegate) = 0; - /// Adds a delegate to the strategy, if the delegate is not yet present - - virtual void remove(const TDelegate& pDelegate) = 0; - /// Removes a delegate from the strategy if found. - - virtual void clear() = 0; - /// Removes all delegates from the strategy. -}; - - -} // namespace Poco - - -#endif +// +// NotificationStrategy.h +// +// $Id: //poco/1.2/Foundation/include/Poco/NotificationStrategy.h#1 $ +// +// Library: Foundation +// Package: Events +// Module: NotificationStrategy +// +// Definition of the NotificationStrategy interface. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_NotificationStrategy_INCLUDED +#define Foundation_NotificationStrategy_INCLUDED + + +#include "Poco/Foundation.h" + + +namespace Poco { + + +template +class NotificationStrategy + /// The interface that all notification strategies must implement. +{ +public: + NotificationStrategy() + { + } + + virtual ~NotificationStrategy() + { + } + + virtual void notify(const void* sender, TArgs& arguments) = 0; + /// Sends a notification to all registered delegates, + + virtual void add(const TDelegate& pDelegate) = 0; + /// Adds a delegate to the strategy, if the delegate is not yet present + + virtual void remove(const TDelegate& pDelegate) = 0; + /// Removes a delegate from the strategy if found. + + virtual void clear() = 0; + /// Removes all delegates from the strategy. +}; + + +} // namespace Poco + + +#endif diff --git a/Foundation/include/Poco/NullChannel.h b/Foundation/include/Poco/NullChannel.h index 55acc269d..0b3ec2e3e 100644 --- a/Foundation/include/Poco/NullChannel.h +++ b/Foundation/include/Poco/NullChannel.h @@ -1,77 +1,77 @@ -// -// NullChannel.h -// -// $Id: //poco/1.2/Foundation/include/Poco/NullChannel.h#1 $ -// -// Library: Foundation -// Package: Logging -// Module: NullChannel -// -// Definition of the NullChannel class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_NullChannel_INCLUDED -#define Foundation_NullChannel_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/Channel.h" - - -namespace Poco { - - -class Foundation_API NullChannel: public Channel - /// The NullChannel is the /dev/null of Channels. - /// - /// A NullChannel discards all information sent to it. - /// Furthermore, its setProperty() method ignores - /// all properties, so it the NullChannel has the - /// nice feature that it can stand in for any - /// other channel class in a logging configuration. -{ -public: - NullChannel(); - /// Creates the NullChannel. - - ~NullChannel(); - /// Destroys the NullChannel. - - void log(const Message& msg); - /// Does nothing. - - void setProperty(const std::string& name, const std::string& value); - /// Ignores both name and value. -}; - - -} // namespace Poco - - -#endif // Foundation_NullChannel_INCLUDED +// +// NullChannel.h +// +// $Id: //poco/1.2/Foundation/include/Poco/NullChannel.h#1 $ +// +// Library: Foundation +// Package: Logging +// Module: NullChannel +// +// Definition of the NullChannel class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_NullChannel_INCLUDED +#define Foundation_NullChannel_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Channel.h" + + +namespace Poco { + + +class Foundation_API NullChannel: public Channel + /// The NullChannel is the /dev/null of Channels. + /// + /// A NullChannel discards all information sent to it. + /// Furthermore, its setProperty() method ignores + /// all properties, so it the NullChannel has the + /// nice feature that it can stand in for any + /// other channel class in a logging configuration. +{ +public: + NullChannel(); + /// Creates the NullChannel. + + ~NullChannel(); + /// Destroys the NullChannel. + + void log(const Message& msg); + /// Does nothing. + + void setProperty(const std::string& name, const std::string& value); + /// Ignores both name and value. +}; + + +} // namespace Poco + + +#endif // Foundation_NullChannel_INCLUDED diff --git a/Foundation/include/Poco/NullStream.h b/Foundation/include/Poco/NullStream.h index 541eff638..2b5c5a8eb 100644 --- a/Foundation/include/Poco/NullStream.h +++ b/Foundation/include/Poco/NullStream.h @@ -1,112 +1,112 @@ -// -// NullStream.h -// -// $Id: //poco/1.2/Foundation/include/Poco/NullStream.h#1 $ -// -// Library: Foundation -// Package: Streams -// Module: NullStream -// -// Definition of the NullStreamBuf, NullInputStream and NullOutputStream classes. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_NullStream_INCLUDED -#define Foundation_NullStream_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/UnbufferedStreamBuf.h" -#include -#include - - -namespace Poco { - - -class Foundation_API NullStreamBuf: public UnbufferedStreamBuf - /// This stream buffer discards all characters written to it. - /// Any read operation immediately yields EOF. -{ -public: - NullStreamBuf(); - /// Creates a NullStreamBuf. - - ~NullStreamBuf(); - /// Destroys the NullStreamBuf. - -protected: - int readFromDevice(); - int writeToDevice(char c); -}; - - -class Foundation_API NullIOS: public virtual std::ios - /// The base class for NullInputStream and NullOutputStream. - /// - /// This class is needed to ensure the correct initialization - /// order of the stream buffer and base classes. -{ -public: - NullIOS(); - ~NullIOS(); - -protected: - NullStreamBuf _buf; -}; - - -class Foundation_API NullInputStream: public NullIOS, public std::istream - /// Any read operation from this stream immediately - /// yields EOF. -{ -public: - NullInputStream(); - /// Creates the NullInputStream. - - ~NullInputStream(); - /// Destroys the NullInputStream. -}; - - -class Foundation_API NullOutputStream: public NullIOS, public std::ostream - /// This stream discards all characters written to it. -{ -public: - NullOutputStream(); - /// Creates the NullOutputStream. - - ~NullOutputStream(); - /// Destroys the NullOutputStream. -}; - - -} // namespace Poco - - -#endif // Foundation_NullStream_INCLUDED +// +// NullStream.h +// +// $Id: //poco/1.2/Foundation/include/Poco/NullStream.h#1 $ +// +// Library: Foundation +// Package: Streams +// Module: NullStream +// +// Definition of the NullStreamBuf, NullInputStream and NullOutputStream classes. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_NullStream_INCLUDED +#define Foundation_NullStream_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/UnbufferedStreamBuf.h" +#include +#include + + +namespace Poco { + + +class Foundation_API NullStreamBuf: public UnbufferedStreamBuf + /// This stream buffer discards all characters written to it. + /// Any read operation immediately yields EOF. +{ +public: + NullStreamBuf(); + /// Creates a NullStreamBuf. + + ~NullStreamBuf(); + /// Destroys the NullStreamBuf. + +protected: + int readFromDevice(); + int writeToDevice(char c); +}; + + +class Foundation_API NullIOS: public virtual std::ios + /// The base class for NullInputStream and NullOutputStream. + /// + /// This class is needed to ensure the correct initialization + /// order of the stream buffer and base classes. +{ +public: + NullIOS(); + ~NullIOS(); + +protected: + NullStreamBuf _buf; +}; + + +class Foundation_API NullInputStream: public NullIOS, public std::istream + /// Any read operation from this stream immediately + /// yields EOF. +{ +public: + NullInputStream(); + /// Creates the NullInputStream. + + ~NullInputStream(); + /// Destroys the NullInputStream. +}; + + +class Foundation_API NullOutputStream: public NullIOS, public std::ostream + /// This stream discards all characters written to it. +{ +public: + NullOutputStream(); + /// Creates the NullOutputStream. + + ~NullOutputStream(); + /// Destroys the NullOutputStream. +}; + + +} // namespace Poco + + +#endif // Foundation_NullStream_INCLUDED diff --git a/Foundation/include/Poco/NumberFormatter.h b/Foundation/include/Poco/NumberFormatter.h index d9baf5e3f..0719002ba 100644 --- a/Foundation/include/Poco/NumberFormatter.h +++ b/Foundation/include/Poco/NumberFormatter.h @@ -1,215 +1,215 @@ -// -// NumberFormatter.h -// -// $Id: //poco/1.2/Foundation/include/Poco/NumberFormatter.h#1 $ -// -// Library: Foundation -// Package: Core -// Module: NumberFormatter -// -// Definition of the NumberFormatter class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_NumberFormatter_INCLUDED -#define Foundation_NumberFormatter_INCLUDED - - -#include "Poco/Foundation.h" - - -namespace Poco { - - -class Foundation_API NumberFormatter - /// The NumberFormatter class provides static methods - /// for formatting numeric values into strings. -{ -public: - static std::string format(int value); - /// Formats an integer value in decimal notation. - - static std::string format(int value, int width); - /// Formats an integer value in decimal notation, - /// right justified in a field having at least - /// the specified width. - - static std::string format0(int value, int width); - /// Formats an integer value in decimal notation, - /// right justified and zero-padded in a field - /// having at least the specified width. - - static std::string formatHex(int value); - /// Formats an int value in hexadecimal notation. - /// The value is treated as unsigned. - - static std::string formatHex(int value, int width); - /// Formats a int value in hexadecimal notation, - /// right justified and zero-padded in - /// a field having at least the specified width. - /// The value is treated as unsigned. - - static std::string format(unsigned value); - /// Formats an unsigned int value in decimal notation. - - static std::string format(unsigned value, int width); - /// Formats an unsigned long int in decimal notation, - /// right justified in a field having at least the - /// specified width. - - static std::string format0(unsigned int value, int width); - /// Formats an unsigned int value in decimal notation, - /// right justified and zero-padded in a field having at - /// least the specified width. - - static std::string formatHex(unsigned value); - /// Formats an unsigned int value in hexadecimal notation. - - static std::string formatHex(unsigned value, int width); - /// Formats a int value in hexadecimal notation, - /// right justified and zero-padded in - /// a field having at least the specified width. - - static std::string format(long value); - /// Formats a long value in decimal notation. - - static std::string format(long value, int width); - /// Formats a long value in decimal notation, - /// right justified in a field having at least the - /// specified width. - - static std::string format0(long value, int width); - /// Formats a long value in decimal notation, - /// right justified and zero-padded in a field - /// having at least the specified width. - - static std::string formatHex(long value); - /// Formats an unsigned long value in hexadecimal notation. - /// The value is treated as unsigned. - - static std::string formatHex(long value, int width); - /// Formats an unsigned long value in hexadecimal notation, - /// right justified and zero-padded in a field having at least the - /// specified width. - /// The value is treated as unsigned. - - static std::string format(unsigned long value); - /// Formats an unsigned long value in decimal notation. - - static std::string format(unsigned long value, int width); - /// Formats an unsigned long value in decimal notation, - /// right justified in a field having at least the specified - /// width. - - static std::string format0(unsigned long value, int width); - /// Formats an unsigned long value in decimal notation, - /// right justified and zero-padded - /// in a field having at least the specified width. - - static std::string formatHex(unsigned long value); - /// Formats an unsigned long value in hexadecimal notation. - - static std::string formatHex(unsigned long value, int width); - /// Formats an unsigned long value in hexadecimal notation, - /// right justified and zero-padded in a field having at least the - /// specified width. - -#if defined(POCO_HAVE_INT64) && !defined(POCO_LONG_IS_64_BIT) - - static std::string format(Int64 value); - /// Formats a 64-bit integer value in decimal notation. - - static std::string format(Int64 value, int width); - /// Formats a 64-bit integer value in decimal notation, - /// right justified in a field having at least the specified width. - - static std::string format0(Int64 value, int width); - /// Formats a 64-bit integer value in decimal notation, - /// right justified and zero-padded in a field having at least - /// the specified width. - - static std::string formatHex(Int64 value); - /// Formats a 64-bit integer value in hexadecimal notation. - /// The value is treated as unsigned. - - static std::string formatHex(Int64 value, int width); - /// Formats a 64-bit integer value in hexadecimal notation, - /// right justified and zero-padded in a field having at least - /// the specified width. - /// The value is treated as unsigned. - - static std::string format(UInt64 value); - /// Formats an unsigned 64-bit integer value in decimal notation. - - static std::string format(UInt64 value, int width); - /// Formats an unsigned 64-bit integer value in decimal notation, - /// right justified in a field having at least the specified width. - - static std::string format0(UInt64 value, int width); - /// Formats an unsigned 64-bit integer value in decimal notation, - /// right justified and zero-padded in a field having at least the - /// specified width. - - static std::string formatHex(UInt64 value); - /// Formats a 64-bit integer value in hexadecimal notation. - - static std::string formatHex(UInt64 value, int width); - /// Formats a 64-bit integer value in hexadecimal notation, - /// right justified and zero-padded in a field having at least - /// the specified width. - -#endif // defined(POCO_HAVE_INT64) && !defined(POCO_LONG_IS_64_BIT) - - static std::string format(float value); - /// Formats a float value in decimal floating-point notation, - /// according to printf's %g format with a precision of 8 fractional digits. - - static std::string format(double value); - /// Formats a double value in decimal floating-point notation, - /// according to printf's %g format with a precision of 16 fractional digits. - - static std::string format(double value, int precision); - /// Formats a double value in decimal floating-point notation, - /// according to printf's %f format with the given precision. - - static std::string format(double value, int width, int precision); - /// Formats a double value in decimal floating-point notation, - /// right justified in a field of the specified width, - /// with the number of fractional digits given in precision. - - static std::string format(const void* ptr); - /// Formats a pointer in an eight (32-bit architectures) or - /// sixteen (64-bit architectures) characters wide - /// field in hexadecimal notation. -}; - - -} // namespace Poco - - -#endif // Foundation_NumberFormatter_INCLUDED +// +// NumberFormatter.h +// +// $Id: //poco/1.2/Foundation/include/Poco/NumberFormatter.h#1 $ +// +// Library: Foundation +// Package: Core +// Module: NumberFormatter +// +// Definition of the NumberFormatter class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_NumberFormatter_INCLUDED +#define Foundation_NumberFormatter_INCLUDED + + +#include "Poco/Foundation.h" + + +namespace Poco { + + +class Foundation_API NumberFormatter + /// The NumberFormatter class provides static methods + /// for formatting numeric values into strings. +{ +public: + static std::string format(int value); + /// Formats an integer value in decimal notation. + + static std::string format(int value, int width); + /// Formats an integer value in decimal notation, + /// right justified in a field having at least + /// the specified width. + + static std::string format0(int value, int width); + /// Formats an integer value in decimal notation, + /// right justified and zero-padded in a field + /// having at least the specified width. + + static std::string formatHex(int value); + /// Formats an int value in hexadecimal notation. + /// The value is treated as unsigned. + + static std::string formatHex(int value, int width); + /// Formats a int value in hexadecimal notation, + /// right justified and zero-padded in + /// a field having at least the specified width. + /// The value is treated as unsigned. + + static std::string format(unsigned value); + /// Formats an unsigned int value in decimal notation. + + static std::string format(unsigned value, int width); + /// Formats an unsigned long int in decimal notation, + /// right justified in a field having at least the + /// specified width. + + static std::string format0(unsigned int value, int width); + /// Formats an unsigned int value in decimal notation, + /// right justified and zero-padded in a field having at + /// least the specified width. + + static std::string formatHex(unsigned value); + /// Formats an unsigned int value in hexadecimal notation. + + static std::string formatHex(unsigned value, int width); + /// Formats a int value in hexadecimal notation, + /// right justified and zero-padded in + /// a field having at least the specified width. + + static std::string format(long value); + /// Formats a long value in decimal notation. + + static std::string format(long value, int width); + /// Formats a long value in decimal notation, + /// right justified in a field having at least the + /// specified width. + + static std::string format0(long value, int width); + /// Formats a long value in decimal notation, + /// right justified and zero-padded in a field + /// having at least the specified width. + + static std::string formatHex(long value); + /// Formats an unsigned long value in hexadecimal notation. + /// The value is treated as unsigned. + + static std::string formatHex(long value, int width); + /// Formats an unsigned long value in hexadecimal notation, + /// right justified and zero-padded in a field having at least the + /// specified width. + /// The value is treated as unsigned. + + static std::string format(unsigned long value); + /// Formats an unsigned long value in decimal notation. + + static std::string format(unsigned long value, int width); + /// Formats an unsigned long value in decimal notation, + /// right justified in a field having at least the specified + /// width. + + static std::string format0(unsigned long value, int width); + /// Formats an unsigned long value in decimal notation, + /// right justified and zero-padded + /// in a field having at least the specified width. + + static std::string formatHex(unsigned long value); + /// Formats an unsigned long value in hexadecimal notation. + + static std::string formatHex(unsigned long value, int width); + /// Formats an unsigned long value in hexadecimal notation, + /// right justified and zero-padded in a field having at least the + /// specified width. + +#if defined(POCO_HAVE_INT64) && !defined(POCO_LONG_IS_64_BIT) + + static std::string format(Int64 value); + /// Formats a 64-bit integer value in decimal notation. + + static std::string format(Int64 value, int width); + /// Formats a 64-bit integer value in decimal notation, + /// right justified in a field having at least the specified width. + + static std::string format0(Int64 value, int width); + /// Formats a 64-bit integer value in decimal notation, + /// right justified and zero-padded in a field having at least + /// the specified width. + + static std::string formatHex(Int64 value); + /// Formats a 64-bit integer value in hexadecimal notation. + /// The value is treated as unsigned. + + static std::string formatHex(Int64 value, int width); + /// Formats a 64-bit integer value in hexadecimal notation, + /// right justified and zero-padded in a field having at least + /// the specified width. + /// The value is treated as unsigned. + + static std::string format(UInt64 value); + /// Formats an unsigned 64-bit integer value in decimal notation. + + static std::string format(UInt64 value, int width); + /// Formats an unsigned 64-bit integer value in decimal notation, + /// right justified in a field having at least the specified width. + + static std::string format0(UInt64 value, int width); + /// Formats an unsigned 64-bit integer value in decimal notation, + /// right justified and zero-padded in a field having at least the + /// specified width. + + static std::string formatHex(UInt64 value); + /// Formats a 64-bit integer value in hexadecimal notation. + + static std::string formatHex(UInt64 value, int width); + /// Formats a 64-bit integer value in hexadecimal notation, + /// right justified and zero-padded in a field having at least + /// the specified width. + +#endif // defined(POCO_HAVE_INT64) && !defined(POCO_LONG_IS_64_BIT) + + static std::string format(float value); + /// Formats a float value in decimal floating-point notation, + /// according to printf's %g format with a precision of 8 fractional digits. + + static std::string format(double value); + /// Formats a double value in decimal floating-point notation, + /// according to printf's %g format with a precision of 16 fractional digits. + + static std::string format(double value, int precision); + /// Formats a double value in decimal floating-point notation, + /// according to printf's %f format with the given precision. + + static std::string format(double value, int width, int precision); + /// Formats a double value in decimal floating-point notation, + /// right justified in a field of the specified width, + /// with the number of fractional digits given in precision. + + static std::string format(const void* ptr); + /// Formats a pointer in an eight (32-bit architectures) or + /// sixteen (64-bit architectures) characters wide + /// field in hexadecimal notation. +}; + + +} // namespace Poco + + +#endif // Foundation_NumberFormatter_INCLUDED diff --git a/Foundation/include/Poco/NumberParser.h b/Foundation/include/Poco/NumberParser.h index 15b3b1d50..f956aed3a 100644 --- a/Foundation/include/Poco/NumberParser.h +++ b/Foundation/include/Poco/NumberParser.h @@ -1,124 +1,124 @@ -// -// NumberParser.h -// -// $Id: //poco/1.2/Foundation/include/Poco/NumberParser.h#1 $ -// -// Library: Foundation -// Package: Core -// Module: NumberParser -// -// Definition of the NumberParser class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_NumberParser_INCLUDED -#define Foundation_NumberParser_INCLUDED - - -#include "Poco/Foundation.h" - - -namespace Poco { - - -class Foundation_API NumberParser - /// The NumberParser class provides static methods - /// for parsing numbers out of strings. -{ -public: - static int parse(const std::string& s); - /// Parses an integer value in decimal notation from the given string. - /// Throws a SyntaxException if the string does not hold a number in decimal notation. - - static bool tryParse(const std::string& s, int& value); - /// Parses an integer value in decimal notation from the given string. - /// Returns true if a valid integer has been found, false otherwise. - - static unsigned parseUnsigned(const std::string& s); - /// Parses an unsigned integer value in decimal notation from the given string. - /// Throws a SyntaxException if the string does not hold a number in decimal notation. - - static bool tryParseUnsigned(const std::string& s, unsigned& value); - /// Parses an unsigned integer value in decimal notation from the given string. - /// Returns true if a valid integer has been found, false otherwise. - - static unsigned parseHex(const std::string& s); - /// Parses an integer value in hexadecimal notation from the given string. - /// Throws a SyntaxException if the string does not hold a number in - /// hexadecimal notation. - - static bool tryParseHex(const std::string& s, unsigned& value); - /// Parses an unsigned integer value in hexadecimal notation from the given string. - /// Returns true if a valid integer has been found, false otherwise. - -#if defined(POCO_HAVE_INT64) - - static Int64 parse64(const std::string& s); - /// Parses a 64-bit integer value in decimal notation from the given string. - /// Throws a SyntaxException if the string does not hold a number in decimal notation. - - static bool tryParse64(const std::string& s, Int64& value); - /// Parses a 64-bit integer value in decimal notation from the given string. - /// Returns true if a valid integer has been found, false otherwise. - - static UInt64 parseUnsigned64(const std::string& s); - /// Parses an unsigned 64-bit integer value in decimal notation from the given string. - /// Throws a SyntaxException if the string does not hold a number in decimal notation. - - static bool tryParseUnsigned64(const std::string& s, UInt64& value); - /// Parses an unsigned 64-bit integer value in decimal notation from the given string. - /// Returns true if a valid integer has been found, false otherwise. - - static UInt64 parseHex64(const std::string& s); - /// Parses a 64 bit-integer value in hexadecimal notation from the given string. - /// Throws a SyntaxException if the string does not hold a number in hexadecimal notation. - - static bool tryParseHex64(const std::string& s, UInt64& value); - /// Parses an unsigned 64-bit integer value in hexadecimal notation from the given string. - /// Returns true if a valid integer has been found, false otherwise. - -#endif // defined(POCO_HAVE_INT64) - - static double parseFloat(const std::string& s); - /// Parses a double value in decimal floating point notation - /// from the given string. - /// Throws a SyntaxException if the string does not hold a floating-point - /// number in hexadecimal notation. - - static bool tryParseFloat(const std::string& s, double& value); - /// Parses a double value in decimal floating point notation - /// from the given string. - /// Returns true if a valid floating point number has been found, - /// false otherwise. -}; - - -} // namespace Poco - - -#endif // Foundation_NumberParser_INCLUDED +// +// NumberParser.h +// +// $Id: //poco/1.2/Foundation/include/Poco/NumberParser.h#1 $ +// +// Library: Foundation +// Package: Core +// Module: NumberParser +// +// Definition of the NumberParser class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_NumberParser_INCLUDED +#define Foundation_NumberParser_INCLUDED + + +#include "Poco/Foundation.h" + + +namespace Poco { + + +class Foundation_API NumberParser + /// The NumberParser class provides static methods + /// for parsing numbers out of strings. +{ +public: + static int parse(const std::string& s); + /// Parses an integer value in decimal notation from the given string. + /// Throws a SyntaxException if the string does not hold a number in decimal notation. + + static bool tryParse(const std::string& s, int& value); + /// Parses an integer value in decimal notation from the given string. + /// Returns true if a valid integer has been found, false otherwise. + + static unsigned parseUnsigned(const std::string& s); + /// Parses an unsigned integer value in decimal notation from the given string. + /// Throws a SyntaxException if the string does not hold a number in decimal notation. + + static bool tryParseUnsigned(const std::string& s, unsigned& value); + /// Parses an unsigned integer value in decimal notation from the given string. + /// Returns true if a valid integer has been found, false otherwise. + + static unsigned parseHex(const std::string& s); + /// Parses an integer value in hexadecimal notation from the given string. + /// Throws a SyntaxException if the string does not hold a number in + /// hexadecimal notation. + + static bool tryParseHex(const std::string& s, unsigned& value); + /// Parses an unsigned integer value in hexadecimal notation from the given string. + /// Returns true if a valid integer has been found, false otherwise. + +#if defined(POCO_HAVE_INT64) + + static Int64 parse64(const std::string& s); + /// Parses a 64-bit integer value in decimal notation from the given string. + /// Throws a SyntaxException if the string does not hold a number in decimal notation. + + static bool tryParse64(const std::string& s, Int64& value); + /// Parses a 64-bit integer value in decimal notation from the given string. + /// Returns true if a valid integer has been found, false otherwise. + + static UInt64 parseUnsigned64(const std::string& s); + /// Parses an unsigned 64-bit integer value in decimal notation from the given string. + /// Throws a SyntaxException if the string does not hold a number in decimal notation. + + static bool tryParseUnsigned64(const std::string& s, UInt64& value); + /// Parses an unsigned 64-bit integer value in decimal notation from the given string. + /// Returns true if a valid integer has been found, false otherwise. + + static UInt64 parseHex64(const std::string& s); + /// Parses a 64 bit-integer value in hexadecimal notation from the given string. + /// Throws a SyntaxException if the string does not hold a number in hexadecimal notation. + + static bool tryParseHex64(const std::string& s, UInt64& value); + /// Parses an unsigned 64-bit integer value in hexadecimal notation from the given string. + /// Returns true if a valid integer has been found, false otherwise. + +#endif // defined(POCO_HAVE_INT64) + + static double parseFloat(const std::string& s); + /// Parses a double value in decimal floating point notation + /// from the given string. + /// Throws a SyntaxException if the string does not hold a floating-point + /// number in hexadecimal notation. + + static bool tryParseFloat(const std::string& s, double& value); + /// Parses a double value in decimal floating point notation + /// from the given string. + /// Returns true if a valid floating point number has been found, + /// false otherwise. +}; + + +} // namespace Poco + + +#endif // Foundation_NumberParser_INCLUDED diff --git a/Foundation/include/Poco/Observer.h b/Foundation/include/Poco/Observer.h index 496a19ed1..35bab2c4a 100644 --- a/Foundation/include/Poco/Observer.h +++ b/Foundation/include/Poco/Observer.h @@ -1,132 +1,132 @@ -// -// Observer.h -// -// $Id: //poco/1.2/Foundation/include/Poco/Observer.h#2 $ -// -// Library: Foundation -// Package: Notifications -// Module: NotificationCenter -// -// Definition of the Observer class template. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_Observer_INCLUDED -#define Foundation_Observer_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/AbstractObserver.h" - - -namespace Poco { - - -template -class Observer: public AbstractObserver - /// This template class implements an adapter that sits between - /// a NotificationCenter and an object receiving notifications - /// from it. It is quite similar in concept to the - /// RunnableAdapter, but provides some NotificationCenter - /// specific additional methods. - /// See the NotificationCenter class for information on how - /// to use this template class. - /// - /// Instead of the Observer class template, you might want to - /// use the NObserver class template, which uses an AutoPtr to - /// pass the Notification to the callback function, thus freeing - /// you from memory management issues. -{ -public: - typedef void (C::*Callback)(N*); - - Observer(C& object, Callback method): - _pObject(&object), - _method(method) - { - } - - Observer(const Observer& observer): - AbstractObserver(observer), - _pObject(observer._pObject), - _method(observer._method) - { - } - - ~Observer() - { - } - - Observer& operator = (const Observer& observer) - { - if (&observer != this) - { - _pObject = observer._pObject; - _method = observer._method; - } - return *this; - } - - void notify(Notification* pNf) const - { - N* pCastNf = dynamic_cast(pNf); - if (pCastNf) - { - pCastNf->duplicate(); - (_pObject->*_method)(pCastNf); - } - } - - bool equals(const AbstractObserver& abstractObserver) const - { - const Observer* pObs = dynamic_cast(&abstractObserver); - return pObs && pObs->_pObject == _pObject && pObs->_method == _method; - } - - bool accepts(Notification* pNf) const - { - return dynamic_cast(pNf) != 0; - } - - AbstractObserver* clone() const - { - return new Observer(*this); - } - -private: - Observer(); - - C* _pObject; - Callback _method; -}; - - -} // namespace Poco - - -#endif // Foundation_Observer_INCLUDED +// +// Observer.h +// +// $Id: //poco/1.2/Foundation/include/Poco/Observer.h#2 $ +// +// Library: Foundation +// Package: Notifications +// Module: NotificationCenter +// +// Definition of the Observer class template. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_Observer_INCLUDED +#define Foundation_Observer_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/AbstractObserver.h" + + +namespace Poco { + + +template +class Observer: public AbstractObserver + /// This template class implements an adapter that sits between + /// a NotificationCenter and an object receiving notifications + /// from it. It is quite similar in concept to the + /// RunnableAdapter, but provides some NotificationCenter + /// specific additional methods. + /// See the NotificationCenter class for information on how + /// to use this template class. + /// + /// Instead of the Observer class template, you might want to + /// use the NObserver class template, which uses an AutoPtr to + /// pass the Notification to the callback function, thus freeing + /// you from memory management issues. +{ +public: + typedef void (C::*Callback)(N*); + + Observer(C& object, Callback method): + _pObject(&object), + _method(method) + { + } + + Observer(const Observer& observer): + AbstractObserver(observer), + _pObject(observer._pObject), + _method(observer._method) + { + } + + ~Observer() + { + } + + Observer& operator = (const Observer& observer) + { + if (&observer != this) + { + _pObject = observer._pObject; + _method = observer._method; + } + return *this; + } + + void notify(Notification* pNf) const + { + N* pCastNf = dynamic_cast(pNf); + if (pCastNf) + { + pCastNf->duplicate(); + (_pObject->*_method)(pCastNf); + } + } + + bool equals(const AbstractObserver& abstractObserver) const + { + const Observer* pObs = dynamic_cast(&abstractObserver); + return pObs && pObs->_pObject == _pObject && pObs->_method == _method; + } + + bool accepts(Notification* pNf) const + { + return dynamic_cast(pNf) != 0; + } + + AbstractObserver* clone() const + { + return new Observer(*this); + } + +private: + Observer(); + + C* _pObject; + Callback _method; +}; + + +} // namespace Poco + + +#endif // Foundation_Observer_INCLUDED diff --git a/Foundation/include/Poco/OpcomChannel.h b/Foundation/include/Poco/OpcomChannel.h index 13e997d17..4cfb97c25 100644 --- a/Foundation/include/Poco/OpcomChannel.h +++ b/Foundation/include/Poco/OpcomChannel.h @@ -1,102 +1,102 @@ -// -// OpcomChannel.h -// -// $Id: //poco/1.2/Foundation/include/Poco/OpcomChannel.h#1 $ -// -// Library: Foundation -// Package: Logging -// Module: OpcomChannel -// -// Definition of the OpcomChannel class specific to OpenVMS. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_OpcomChannel_INCLUDED -#define Foundation_OpcomChannel_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/Channel.h" - - -namespace Poco { - - -class Foundation_API OpcomChannel: public Channel - /// A OpenVMS-only channel that uses the OpenVMS OPCOM service. -{ -public: - OpcomChannel(); - /// Creates an OpcomChannel that uses the OPC$M_NM_CENTRL - /// target. - - OpcomChannel(int target); - /// Creates an OpcomChannel that uses the given target. - /// Specify one of the OPC$M_NM_* values. - /// See also setProperty(). - - void log(const Message& msg); - /// Logs the given message using the OpenVMS OPCOM service. - - void setProperty(const std::string& name, const std::string& value); - /// Sets the property with the given name. - /// - /// The only supported property is "target", which must - /// be set to one of the following values: - /// - /// * CARDS: Card device operator - /// * CENTRL: Central operator - /// * SECURITY: Security operator - /// * CLUSTER: OpenVMS Cluster operator - /// * DEVICE: Device status information - /// * DISKS: Disks operator - /// * NTWORK: Network operator - /// * TAPES: Tapes operator - /// * PRINT: Printer operator - /// * OPER1 .. - /// * OPER12: System-manager-defined operator functions - - std::string getProperty(const std::string& name) const; - /// Returns the value of the property with the given name. - /// See setProperty() for a description of the supported - /// properties. - - static const std::string PROP_TARGET; - -protected: - ~OpcomChannel(); - -private: - int _target; -}; - - -} // namespace Poco - - -#endif // Foundation_OpcomChannel_INCLUDED +// +// OpcomChannel.h +// +// $Id: //poco/1.2/Foundation/include/Poco/OpcomChannel.h#1 $ +// +// Library: Foundation +// Package: Logging +// Module: OpcomChannel +// +// Definition of the OpcomChannel class specific to OpenVMS. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_OpcomChannel_INCLUDED +#define Foundation_OpcomChannel_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Channel.h" + + +namespace Poco { + + +class Foundation_API OpcomChannel: public Channel + /// A OpenVMS-only channel that uses the OpenVMS OPCOM service. +{ +public: + OpcomChannel(); + /// Creates an OpcomChannel that uses the OPC$M_NM_CENTRL + /// target. + + OpcomChannel(int target); + /// Creates an OpcomChannel that uses the given target. + /// Specify one of the OPC$M_NM_* values. + /// See also setProperty(). + + void log(const Message& msg); + /// Logs the given message using the OpenVMS OPCOM service. + + void setProperty(const std::string& name, const std::string& value); + /// Sets the property with the given name. + /// + /// The only supported property is "target", which must + /// be set to one of the following values: + /// + /// * CARDS: Card device operator + /// * CENTRL: Central operator + /// * SECURITY: Security operator + /// * CLUSTER: OpenVMS Cluster operator + /// * DEVICE: Device status information + /// * DISKS: Disks operator + /// * NTWORK: Network operator + /// * TAPES: Tapes operator + /// * PRINT: Printer operator + /// * OPER1 .. + /// * OPER12: System-manager-defined operator functions + + std::string getProperty(const std::string& name) const; + /// Returns the value of the property with the given name. + /// See setProperty() for a description of the supported + /// properties. + + static const std::string PROP_TARGET; + +protected: + ~OpcomChannel(); + +private: + int _target; +}; + + +} // namespace Poco + + +#endif // Foundation_OpcomChannel_INCLUDED diff --git a/Foundation/include/Poco/Path.h b/Foundation/include/Poco/Path.h index a231acc0e..04bbe0e75 100644 --- a/Foundation/include/Poco/Path.h +++ b/Foundation/include/Poco/Path.h @@ -1,476 +1,476 @@ -// -// Path.h -// -// $Id: //poco/1.2/Foundation/include/Poco/Path.h#1 $ -// -// Library: Foundation -// Package: Filesystem -// Module: Path -// -// Definition of the Path class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_Path_INCLUDED -#define Foundation_Path_INCLUDED - - -#include "Poco/Foundation.h" -#include - - -namespace Poco { - - -class Foundation_API Path - /// This class represents filesystem paths in a - /// platform-independent manner. - /// Unix, Windows and OpenVMS all use a different - /// syntax for filesystem paths. - /// This class can work with all three formats. - /// A path is made up of an optional node name - /// (only Windows and OpenVMS), an optional - /// device name (also only Windows and OpenVMS), - /// a list of directory names and an optional - /// filename. -{ -public: - enum Style - { - PATH_UNIX, /// Unix-style path - PATH_WINDOWS, /// Windows-style path - PATH_VMS, /// VMS-style path - PATH_NATIVE, /// The current platform's native style - PATH_GUESS /// Guess the style by examining the path - }; - - typedef std::vector StringVec; - - Path(); - /// Creates an empty relative path. - - Path(bool absolute); - /// Creates an empty absolute or relative path. - - Path(const char* path); - /// Creates a path from a string. - - Path(const char* path, Style style); - /// Creates a path from a string. - - Path(const std::string& path); - /// Creates a path from a string. - - Path(const std::string& path, Style style); - /// Creates a path from a string. - - Path(const Path& path); - /// Copy constructor - - Path(const Path& parent, const std::string& fileName); - /// Creates a path from a parent path and a filename. - /// The parent path is expected to reference a directory. - - Path(const Path& parent, const Path& relative); - /// Creates a path from a parent path and a relative path. - /// The parent path is expected to reference a directory. - /// The relative path is appended to the parent path. - - ~Path(); - /// Destroys the Path. - - Path& operator = (const Path& path); - /// Assignment operator. - - Path& operator = (const std::string& path); - /// Assigns a string containing a path. - - Path& operator = (const char* path); - /// Assigns a string containing a path. - - void swap(Path& path); - /// Swaps the path with another one. - - Path& assign(const std::string& path); - /// Assigns a string containing a path. - - Path& assign(const std::string& path, Style style); - /// Assigns a string containing a path. - - Path& assign(const Path& path); - /// Assigns the given path. - - Path& assign(const char* path); - /// Assigns a string containing a path. - - std::string toString() const; - /// Returns a string containing the path in native format. - - std::string toString(Style style) const; - /// Returns a string containing the path in the given format. - - Path& parse(const std::string& path); - /// Same as assign(). - - Path& parse(const std::string& path, Style style); - /// Assigns a string containing a path. - - bool tryParse(const std::string& path); - /// Tries to interpret the given string as a path. - /// If the path is syntactically valid, assigns the - /// path and returns true. Otherwise leaves the - /// object unchanged and returns false. - - bool tryParse(const std::string& path, Style style); - /// Tries to interpret the given string as a path, - /// according to the given style. - /// If the path is syntactically valid, assigns the - /// path and returns true. Otherwise leaves the - /// object unchanged and returns false. - - Path& parseDirectory(const std::string& path); - /// The resulting path always refers to a directory and - /// the filename part is empty. - - Path& parseDirectory(const std::string& path, Style style); - /// The resulting path always refers to a directory and - /// the filename part is empty. - - Path& makeDirectory(); - /// If the path contains a filename, the filename is appended - /// to the directory list and cleared. Thus the resulting path - /// always refers to a directory. - - Path& makeFile(); - /// If the path contains no filename, the last directory - /// becomes the filename. - - Path& makeParent(); - /// Makes the path refer to its parent. - - Path& makeAbsolute(); - /// Makes the path absolute if it is relative. - /// The current working directory is taken as base directory. - - Path& makeAbsolute(const Path& base); - /// Makes the path absolute if it is relative. - /// The given path is taken as base. - - Path& append(const Path& path); - /// Appends the given path. - - Path& resolve(const Path& path); - /// Resolves the given path agains the current one. - /// - /// If the given path is absolute, it replaces the current one. - /// Otherwise, the relative path is appended to the current path. - - bool isAbsolute() const; - /// Returns true iff the path is absolute. - - bool isRelative() const; - /// Returns true iff the path is relative. - - bool isDirectory() const; - /// Returns true iff the path references a directory - /// (the filename part is empty). - - bool isFile() const; - /// Returns true iff the path references a file - /// (the filename part is not empty). - - void setNode(const std::string& node); - /// Sets the node name. - /// Setting a non-empty node automatically makes - /// the path an absolute one. - - const std::string& getNode() const; - /// Returns the node name. - - void setDevice(const std::string& device); - /// Sets the device name. - /// Setting a non-empty device automatically makes - /// the path an absolute one. - - const std::string& getDevice() const; - /// Returns the device name. - - int depth() const; - /// Returns the number of directories in the directory list. - - const std::string& directory(int n) const; - /// Returns the n'th directory in the directory list. - /// If n == depth(), returns the filename. - - const std::string& operator [] (int n) const; - /// Returns the n'th directory in the directory list. - /// If n == depth(), returns the filename. - - void pushDirectory(const std::string& dir); - /// Adds a directory to the directory list. - - void popDirectory(); - /// Removes the last directory from the directory list. - - void setFileName(const std::string& name); - /// Sets the filename. - - const std::string& getFileName() const; - /// Returns the filename. - - void setBaseName(const std::string& name); - /// Sets the basename part of the filename and - /// does not change the extension. - - std::string getBaseName() const; - /// Returns the basename (the filename sans - /// extension) of the path. - - void setExtension(const std::string& extension); - /// Sets the filename extension. - - std::string getExtension() const; - /// Returns the filename extension. - - const std::string& version() const; - /// Returns the file version. VMS only. - - void clear(); - /// Clears all components. - - Path parent() const; - /// Returns a path referring to the path's - /// directory. - - Path absolute() const; - /// Returns an absolute variant of the path, - /// taking the current working directory as base. - - Path absolute(const Path& base) const; - /// Returns an absolute variant of the path, - /// taking the given path as base. - - static Path forDirectory(const std::string& path); - /// Creates a path referring to a directory. - - static Path forDirectory(const std::string& path, Style style); - /// Creates a path referring to a directory. - - static char separator(); - /// Returns the platform's path name separator, which separates - /// the components (names) in a path. - /// - /// On Unix systems, this is the slash '/'. On Windows systems, - /// this is the backslash '\'. On OpenVMS systems, this is the - /// period '.'. - - static char pathSeparator(); - /// Returns the platform's path separator, which separates - /// single paths in a list of paths. - /// - /// On Unix systems, this is the colon ':'. Opn Windows systems, - /// this is the semicolon ';'. On OpenVMS systems, this is the - /// comma ','. - - static std::string current(); - /// Returns the current working directory. - - static std::string home(); - /// Returns the user's home directory. - - static std::string temp(); - /// Returns the temporary directory. - - static std::string null(); - /// Returns the name of the null device. - - static std::string expand(const std::string& path); - /// Expands all environment variables contained in the path. - /// - /// On Unix, a tilde as first character in the path is - /// replaced with the path to user's home directory. - - static void listRoots(std::vector& roots); - /// Fills the vector with all filesystem roots available on the - /// system. On Unix, there is exactly one root, "/". - /// On Windows, the roots are the drive letters. - /// On OpenVMS, the roots are the mounted disks. - - static bool find(StringVec::const_iterator it, StringVec::const_iterator end, const std::string& name, Path& path); - /// Searches the file with the given name in the locations (paths) specified - /// by it and end. A relative path may be given in name. - /// - /// If the file is found in one of the locations, the complete - /// path of the file is stored in the path given as argument and true is returned. - /// Otherwise false is returned and the path argument remains unchanged. - - static bool find(const std::string& pathList, const std::string& name, Path& path); - /// Searches the file with the given name in the locations (paths) specified - /// in pathList. The paths in pathList must be delimited by the platform's - /// path separator (see pathSeparator()). A relative path may be given in name. - /// - /// If the file is found in one of the locations, the complete - /// path of the file is stored in the path given as argument and true is returned. - /// Otherwise false is returned and the path argument remains unchanged. - -protected: - void parseUnix(const std::string& path); - void parseWindows(const std::string& path); - void parseVMS(const std::string& path); - void parseGuess(const std::string& path); - std::string buildUnix() const; - std::string buildWindows() const; - std::string buildVMS() const; - -private: - std::string _node; - std::string _device; - std::string _name; - std::string _version; - StringVec _dirs; - bool _absolute; -}; - - -// -// inlines -// -inline bool Path::isAbsolute() const -{ - return _absolute; -} - - -inline bool Path::isRelative() const -{ - return !_absolute; -} - - -inline bool Path::isDirectory() const -{ - return _name.empty(); -} - - -inline bool Path::isFile() const -{ - return !_name.empty(); -} - - -inline Path& Path::parse(const std::string& path) -{ - return assign(path); -} - - -inline Path& Path::parse(const std::string& path, Style style) -{ - return assign(path, style); -} - - -inline const std::string& Path::getNode() const -{ - return _node; -} - - -inline const std::string& Path::getDevice() const -{ - return _device; -} - - -inline const std::string& Path::getFileName() const -{ - return _name; -} - - -inline int Path::depth() const -{ - return int(_dirs.size()); -} - - -inline const std::string& Path::version() const -{ - return _version; -} - - -inline Path Path::forDirectory(const std::string& path) -{ - Path p; - return p.parseDirectory(path); -} - - -inline Path Path::forDirectory(const std::string& path, Style style) -{ - Path p; - return p.parseDirectory(path, style); -} - - -inline char Path::separator() -{ -#if defined(POCO_OS_FAMILY_VMS) - return '.'; -#elif defined(POCO_OS_FAMILY_WINDOWS) - return '\\'; -#else - return '/'; -#endif -} - - -inline char Path::pathSeparator() -{ -#if defined(POCO_OS_FAMILY_VMS) - return ','; -#elif defined(POCO_OS_FAMILY_WINDOWS) - return ';'; -#else - return ':'; -#endif -} - - -inline void swap(Path& p1, Path& p2) -{ - p1.swap(p2); -} - - -} // namespace Poco - - -#endif // Foundation_Path_INCLUDED +// +// Path.h +// +// $Id: //poco/1.2/Foundation/include/Poco/Path.h#1 $ +// +// Library: Foundation +// Package: Filesystem +// Module: Path +// +// Definition of the Path class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_Path_INCLUDED +#define Foundation_Path_INCLUDED + + +#include "Poco/Foundation.h" +#include + + +namespace Poco { + + +class Foundation_API Path + /// This class represents filesystem paths in a + /// platform-independent manner. + /// Unix, Windows and OpenVMS all use a different + /// syntax for filesystem paths. + /// This class can work with all three formats. + /// A path is made up of an optional node name + /// (only Windows and OpenVMS), an optional + /// device name (also only Windows and OpenVMS), + /// a list of directory names and an optional + /// filename. +{ +public: + enum Style + { + PATH_UNIX, /// Unix-style path + PATH_WINDOWS, /// Windows-style path + PATH_VMS, /// VMS-style path + PATH_NATIVE, /// The current platform's native style + PATH_GUESS /// Guess the style by examining the path + }; + + typedef std::vector StringVec; + + Path(); + /// Creates an empty relative path. + + Path(bool absolute); + /// Creates an empty absolute or relative path. + + Path(const char* path); + /// Creates a path from a string. + + Path(const char* path, Style style); + /// Creates a path from a string. + + Path(const std::string& path); + /// Creates a path from a string. + + Path(const std::string& path, Style style); + /// Creates a path from a string. + + Path(const Path& path); + /// Copy constructor + + Path(const Path& parent, const std::string& fileName); + /// Creates a path from a parent path and a filename. + /// The parent path is expected to reference a directory. + + Path(const Path& parent, const Path& relative); + /// Creates a path from a parent path and a relative path. + /// The parent path is expected to reference a directory. + /// The relative path is appended to the parent path. + + ~Path(); + /// Destroys the Path. + + Path& operator = (const Path& path); + /// Assignment operator. + + Path& operator = (const std::string& path); + /// Assigns a string containing a path. + + Path& operator = (const char* path); + /// Assigns a string containing a path. + + void swap(Path& path); + /// Swaps the path with another one. + + Path& assign(const std::string& path); + /// Assigns a string containing a path. + + Path& assign(const std::string& path, Style style); + /// Assigns a string containing a path. + + Path& assign(const Path& path); + /// Assigns the given path. + + Path& assign(const char* path); + /// Assigns a string containing a path. + + std::string toString() const; + /// Returns a string containing the path in native format. + + std::string toString(Style style) const; + /// Returns a string containing the path in the given format. + + Path& parse(const std::string& path); + /// Same as assign(). + + Path& parse(const std::string& path, Style style); + /// Assigns a string containing a path. + + bool tryParse(const std::string& path); + /// Tries to interpret the given string as a path. + /// If the path is syntactically valid, assigns the + /// path and returns true. Otherwise leaves the + /// object unchanged and returns false. + + bool tryParse(const std::string& path, Style style); + /// Tries to interpret the given string as a path, + /// according to the given style. + /// If the path is syntactically valid, assigns the + /// path and returns true. Otherwise leaves the + /// object unchanged and returns false. + + Path& parseDirectory(const std::string& path); + /// The resulting path always refers to a directory and + /// the filename part is empty. + + Path& parseDirectory(const std::string& path, Style style); + /// The resulting path always refers to a directory and + /// the filename part is empty. + + Path& makeDirectory(); + /// If the path contains a filename, the filename is appended + /// to the directory list and cleared. Thus the resulting path + /// always refers to a directory. + + Path& makeFile(); + /// If the path contains no filename, the last directory + /// becomes the filename. + + Path& makeParent(); + /// Makes the path refer to its parent. + + Path& makeAbsolute(); + /// Makes the path absolute if it is relative. + /// The current working directory is taken as base directory. + + Path& makeAbsolute(const Path& base); + /// Makes the path absolute if it is relative. + /// The given path is taken as base. + + Path& append(const Path& path); + /// Appends the given path. + + Path& resolve(const Path& path); + /// Resolves the given path agains the current one. + /// + /// If the given path is absolute, it replaces the current one. + /// Otherwise, the relative path is appended to the current path. + + bool isAbsolute() const; + /// Returns true iff the path is absolute. + + bool isRelative() const; + /// Returns true iff the path is relative. + + bool isDirectory() const; + /// Returns true iff the path references a directory + /// (the filename part is empty). + + bool isFile() const; + /// Returns true iff the path references a file + /// (the filename part is not empty). + + void setNode(const std::string& node); + /// Sets the node name. + /// Setting a non-empty node automatically makes + /// the path an absolute one. + + const std::string& getNode() const; + /// Returns the node name. + + void setDevice(const std::string& device); + /// Sets the device name. + /// Setting a non-empty device automatically makes + /// the path an absolute one. + + const std::string& getDevice() const; + /// Returns the device name. + + int depth() const; + /// Returns the number of directories in the directory list. + + const std::string& directory(int n) const; + /// Returns the n'th directory in the directory list. + /// If n == depth(), returns the filename. + + const std::string& operator [] (int n) const; + /// Returns the n'th directory in the directory list. + /// If n == depth(), returns the filename. + + void pushDirectory(const std::string& dir); + /// Adds a directory to the directory list. + + void popDirectory(); + /// Removes the last directory from the directory list. + + void setFileName(const std::string& name); + /// Sets the filename. + + const std::string& getFileName() const; + /// Returns the filename. + + void setBaseName(const std::string& name); + /// Sets the basename part of the filename and + /// does not change the extension. + + std::string getBaseName() const; + /// Returns the basename (the filename sans + /// extension) of the path. + + void setExtension(const std::string& extension); + /// Sets the filename extension. + + std::string getExtension() const; + /// Returns the filename extension. + + const std::string& version() const; + /// Returns the file version. VMS only. + + void clear(); + /// Clears all components. + + Path parent() const; + /// Returns a path referring to the path's + /// directory. + + Path absolute() const; + /// Returns an absolute variant of the path, + /// taking the current working directory as base. + + Path absolute(const Path& base) const; + /// Returns an absolute variant of the path, + /// taking the given path as base. + + static Path forDirectory(const std::string& path); + /// Creates a path referring to a directory. + + static Path forDirectory(const std::string& path, Style style); + /// Creates a path referring to a directory. + + static char separator(); + /// Returns the platform's path name separator, which separates + /// the components (names) in a path. + /// + /// On Unix systems, this is the slash '/'. On Windows systems, + /// this is the backslash '\'. On OpenVMS systems, this is the + /// period '.'. + + static char pathSeparator(); + /// Returns the platform's path separator, which separates + /// single paths in a list of paths. + /// + /// On Unix systems, this is the colon ':'. Opn Windows systems, + /// this is the semicolon ';'. On OpenVMS systems, this is the + /// comma ','. + + static std::string current(); + /// Returns the current working directory. + + static std::string home(); + /// Returns the user's home directory. + + static std::string temp(); + /// Returns the temporary directory. + + static std::string null(); + /// Returns the name of the null device. + + static std::string expand(const std::string& path); + /// Expands all environment variables contained in the path. + /// + /// On Unix, a tilde as first character in the path is + /// replaced with the path to user's home directory. + + static void listRoots(std::vector& roots); + /// Fills the vector with all filesystem roots available on the + /// system. On Unix, there is exactly one root, "/". + /// On Windows, the roots are the drive letters. + /// On OpenVMS, the roots are the mounted disks. + + static bool find(StringVec::const_iterator it, StringVec::const_iterator end, const std::string& name, Path& path); + /// Searches the file with the given name in the locations (paths) specified + /// by it and end. A relative path may be given in name. + /// + /// If the file is found in one of the locations, the complete + /// path of the file is stored in the path given as argument and true is returned. + /// Otherwise false is returned and the path argument remains unchanged. + + static bool find(const std::string& pathList, const std::string& name, Path& path); + /// Searches the file with the given name in the locations (paths) specified + /// in pathList. The paths in pathList must be delimited by the platform's + /// path separator (see pathSeparator()). A relative path may be given in name. + /// + /// If the file is found in one of the locations, the complete + /// path of the file is stored in the path given as argument and true is returned. + /// Otherwise false is returned and the path argument remains unchanged. + +protected: + void parseUnix(const std::string& path); + void parseWindows(const std::string& path); + void parseVMS(const std::string& path); + void parseGuess(const std::string& path); + std::string buildUnix() const; + std::string buildWindows() const; + std::string buildVMS() const; + +private: + std::string _node; + std::string _device; + std::string _name; + std::string _version; + StringVec _dirs; + bool _absolute; +}; + + +// +// inlines +// +inline bool Path::isAbsolute() const +{ + return _absolute; +} + + +inline bool Path::isRelative() const +{ + return !_absolute; +} + + +inline bool Path::isDirectory() const +{ + return _name.empty(); +} + + +inline bool Path::isFile() const +{ + return !_name.empty(); +} + + +inline Path& Path::parse(const std::string& path) +{ + return assign(path); +} + + +inline Path& Path::parse(const std::string& path, Style style) +{ + return assign(path, style); +} + + +inline const std::string& Path::getNode() const +{ + return _node; +} + + +inline const std::string& Path::getDevice() const +{ + return _device; +} + + +inline const std::string& Path::getFileName() const +{ + return _name; +} + + +inline int Path::depth() const +{ + return int(_dirs.size()); +} + + +inline const std::string& Path::version() const +{ + return _version; +} + + +inline Path Path::forDirectory(const std::string& path) +{ + Path p; + return p.parseDirectory(path); +} + + +inline Path Path::forDirectory(const std::string& path, Style style) +{ + Path p; + return p.parseDirectory(path, style); +} + + +inline char Path::separator() +{ +#if defined(POCO_OS_FAMILY_VMS) + return '.'; +#elif defined(POCO_OS_FAMILY_WINDOWS) + return '\\'; +#else + return '/'; +#endif +} + + +inline char Path::pathSeparator() +{ +#if defined(POCO_OS_FAMILY_VMS) + return ','; +#elif defined(POCO_OS_FAMILY_WINDOWS) + return ';'; +#else + return ':'; +#endif +} + + +inline void swap(Path& p1, Path& p2) +{ + p1.swap(p2); +} + + +} // namespace Poco + + +#endif // Foundation_Path_INCLUDED diff --git a/Foundation/include/Poco/Path_UNIX.h b/Foundation/include/Poco/Path_UNIX.h index 60320f47b..5eac17cf1 100644 --- a/Foundation/include/Poco/Path_UNIX.h +++ b/Foundation/include/Poco/Path_UNIX.h @@ -1,65 +1,65 @@ -// -// Path_UNIX.h -// -// $Id: //poco/1.2/Foundation/include/Poco/Path_UNIX.h#1 $ -// -// Library: Foundation -// Package: Filesystem -// Module: Path -// -// Definition of the PathImpl class fo rUnix. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_Path_UNIX_INCLUDED -#define Foundation_Path_UNIX_INCLUDED - - -#include "Poco/Foundation.h" -#include - - -namespace Poco { - - -class PathImpl -{ -public: - static std::string currentImpl(); - static std::string homeImpl(); - static std::string tempImpl(); - static std::string nullImpl(); - static std::string expandImpl(const std::string& path); - static void listRootsImpl(std::vector& roots); -}; - - -} // namespace Poco - - -#endif // Foundation_Path_UNIX_INCLUDED +// +// Path_UNIX.h +// +// $Id: //poco/1.2/Foundation/include/Poco/Path_UNIX.h#1 $ +// +// Library: Foundation +// Package: Filesystem +// Module: Path +// +// Definition of the PathImpl class fo rUnix. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_Path_UNIX_INCLUDED +#define Foundation_Path_UNIX_INCLUDED + + +#include "Poco/Foundation.h" +#include + + +namespace Poco { + + +class PathImpl +{ +public: + static std::string currentImpl(); + static std::string homeImpl(); + static std::string tempImpl(); + static std::string nullImpl(); + static std::string expandImpl(const std::string& path); + static void listRootsImpl(std::vector& roots); +}; + + +} // namespace Poco + + +#endif // Foundation_Path_UNIX_INCLUDED diff --git a/Foundation/include/Poco/Path_VMS.h b/Foundation/include/Poco/Path_VMS.h index 3c0aa8454..27a70819e 100644 --- a/Foundation/include/Poco/Path_VMS.h +++ b/Foundation/include/Poco/Path_VMS.h @@ -1,65 +1,65 @@ -// -// Path_VMS.h -// -// $Id: //poco/1.2/Foundation/include/Poco/Path_VMS.h#1 $ -// -// Library: Foundation -// Package: Filesystem -// Module: Path -// -// Definition of the PathImpl class for OpenVMS. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_Path_VMS_INCLUDED -#define Foundation_Path_VMS_INCLUDED - - -#include "Poco/Foundation.h" -#include - - -namespace Poco { - - -class PathImpl -{ -public: - static std::string currentImpl(); - static std::string homeImpl(); - static std::string tempImpl(); - static std::string nullImpl(); - static std::string expandImpl(const std::string& path); - static void listRootsImpl(std::vector& roots); -}; - - -} // namespace Poco - - -#endif // Foundation_Path_VMS_INCLUDED +// +// Path_VMS.h +// +// $Id: //poco/1.2/Foundation/include/Poco/Path_VMS.h#1 $ +// +// Library: Foundation +// Package: Filesystem +// Module: Path +// +// Definition of the PathImpl class for OpenVMS. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_Path_VMS_INCLUDED +#define Foundation_Path_VMS_INCLUDED + + +#include "Poco/Foundation.h" +#include + + +namespace Poco { + + +class PathImpl +{ +public: + static std::string currentImpl(); + static std::string homeImpl(); + static std::string tempImpl(); + static std::string nullImpl(); + static std::string expandImpl(const std::string& path); + static void listRootsImpl(std::vector& roots); +}; + + +} // namespace Poco + + +#endif // Foundation_Path_VMS_INCLUDED diff --git a/Foundation/include/Poco/Path_WIN32.h b/Foundation/include/Poco/Path_WIN32.h index 196b4387c..d07fd1001 100644 --- a/Foundation/include/Poco/Path_WIN32.h +++ b/Foundation/include/Poco/Path_WIN32.h @@ -1,65 +1,65 @@ -// -// Path_WIN32.h -// -// $Id: //poco/1.2/Foundation/include/Poco/Path_WIN32.h#1 $ -// -// Library: Foundation -// Package: Filesystem -// Module: Path -// -// Definition of the PathImpl class for WIN32. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_Path_WIN32_INCLUDED -#define Foundation_Path_WIN32_INCLUDED - - -#include "Poco/Foundation.h" -#include - - -namespace Poco { - - -class Foundation_API PathImpl -{ -public: - static std::string currentImpl(); - static std::string homeImpl(); - static std::string tempImpl(); - static std::string nullImpl(); - static std::string expandImpl(const std::string& path); - static void listRootsImpl(std::vector& roots); -}; - - -} // namespace Poco - - -#endif // Foundation_Path_WIN32_INCLUDED +// +// Path_WIN32.h +// +// $Id: //poco/1.2/Foundation/include/Poco/Path_WIN32.h#1 $ +// +// Library: Foundation +// Package: Filesystem +// Module: Path +// +// Definition of the PathImpl class for WIN32. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_Path_WIN32_INCLUDED +#define Foundation_Path_WIN32_INCLUDED + + +#include "Poco/Foundation.h" +#include + + +namespace Poco { + + +class Foundation_API PathImpl +{ +public: + static std::string currentImpl(); + static std::string homeImpl(); + static std::string tempImpl(); + static std::string nullImpl(); + static std::string expandImpl(const std::string& path); + static void listRootsImpl(std::vector& roots); +}; + + +} // namespace Poco + + +#endif // Foundation_Path_WIN32_INCLUDED diff --git a/Foundation/include/Poco/Path_WIN32U.h b/Foundation/include/Poco/Path_WIN32U.h index abf5e4a7e..b4a57378c 100644 --- a/Foundation/include/Poco/Path_WIN32U.h +++ b/Foundation/include/Poco/Path_WIN32U.h @@ -1,70 +1,70 @@ -// -// Path_WIN32U.h -// -// $Id: //poco/1.2/Foundation/include/Poco/Path_WIN32U.h#1 $ -// -// Library: Foundation -// Package: Filesystem -// Module: Path -// -// Definition of the PathImpl class for WIN32. -// -// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_Path_WIN32U_INCLUDED -#define Foundation_Path_WIN32U_INCLUDED - - -#include "Poco/Foundation.h" -#include - - -namespace Poco { - - -class Foundation_API PathImpl -{ -public: - static std::string currentImpl(); - static std::string homeImpl(); - static std::string tempImpl(); - static std::string nullImpl(); - static std::string expandImpl(const std::string& path); - static void listRootsImpl(std::vector& roots); - - enum - { - MAX_PATH_LEN = 32767 - }; -}; - - -} // namespace Poco - - -#endif // Foundation_Path_WIN32U_INCLUDED +// +// Path_WIN32U.h +// +// $Id: //poco/1.2/Foundation/include/Poco/Path_WIN32U.h#1 $ +// +// Library: Foundation +// Package: Filesystem +// Module: Path +// +// Definition of the PathImpl class for WIN32. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_Path_WIN32U_INCLUDED +#define Foundation_Path_WIN32U_INCLUDED + + +#include "Poco/Foundation.h" +#include + + +namespace Poco { + + +class Foundation_API PathImpl +{ +public: + static std::string currentImpl(); + static std::string homeImpl(); + static std::string tempImpl(); + static std::string nullImpl(); + static std::string expandImpl(const std::string& path); + static void listRootsImpl(std::vector& roots); + + enum + { + MAX_PATH_LEN = 32767 + }; +}; + + +} // namespace Poco + + +#endif // Foundation_Path_WIN32U_INCLUDED diff --git a/Foundation/include/Poco/PatternFormatter.h b/Foundation/include/Poco/PatternFormatter.h index d59b918b4..c41c266aa 100644 --- a/Foundation/include/Poco/PatternFormatter.h +++ b/Foundation/include/Poco/PatternFormatter.h @@ -1,145 +1,145 @@ -// -// PatternFormatter.h -// -// $Id: //poco/1.2/Foundation/include/Poco/PatternFormatter.h#1 $ -// -// Library: Foundation -// Package: Logging -// Module: PatternFormatter -// -// Definition of the PatternFormatter class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_PatternFormatter_INCLUDED -#define Foundation_PatternFormatter_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/Formatter.h" -#include "Poco/Message.h" - - -namespace Poco { - - -class Foundation_API PatternFormatter: public Formatter - /// This Formatter allows for custom formatting of - /// log messages based on format patterns. - /// - /// The format pattern is used as a template to format the message and - /// is copied character by character except for the following special characters, - /// which are replaced by the corresponding value. - /// - /// * %s - message source - /// * %t - message text - /// * %l - message priority level (1 .. 7) - /// * %p - message priority (Fatal, Critical, Error, Warning, Notice, Information, Debug, Trace) - /// * %q - abbreviated message priority (F, C, E, W,N, I, D, T) - /// * %P - message process identifier - /// * %T - message thread name - /// * %I - message thread identifier (numeric) - /// * %N - node or host name - /// * %w - message date/time abbreviated weekday (Mon, Tue, ...) - /// * %W - message date/time full weekday (Monday, Tuesday, ...) - /// * %b - message date/time abbreviated month (Jan, Feb, ...) - /// * %B - message date/time full month (January, February, ...) - /// * %d - message date/time zero-padded day of month (01 .. 31) - /// * %e - message date/time day of month (1 .. 31) - /// * %f - message date/time space-padded day of month ( 1 .. 31) - /// * %m - message date/time zero-padded month (01 .. 12) - /// * %n - message date/time month (1 .. 12) - /// * %o - message date/time space-padded month ( 1 .. 12) - /// * %y - message date/time year without century (70) - /// * %Y - message date/time year with century (1970) - /// * %H - message date/time hour (00 .. 23) - /// * %h - message date/time hour (00 .. 12) - /// * %a - message date/time am/pm - /// * %A - message date/time AM/PM - /// * %M - message date/time minute (00 .. 59) - /// * %S - message date/time second (00 .. 59) - /// * %i - message date/time millisecond (000 .. 999) - /// * %c - message date/time centisecond (0 .. 9) - /// * %z - time zone differential in ISO 8601 format (Z or +NN.NN). - /// * %Z - time zone differential in RFC format (GMT or +NNNN) - /// * %[name] - the value of the message parameter with the given name - /// * %% - percent sign - -{ -public: - PatternFormatter(); - /// Creates a PatternFormatter. - /// The format pattern must be specified with - /// a call to setProperty. - - PatternFormatter(const std::string& format); - /// Creates a PatternFormatter that uses the - /// given format pattern. - - ~PatternFormatter(); - /// Destroys the PatternFormatter. - - void format(const Message& msg, std::string& text); - /// Formats the message according to the specified - /// format pattern and places the result in text. - - void setProperty(const std::string& name, const std::string& value); - /// Sets the property with the given name to the given value. - /// - /// The following properties are supported: - /// - /// * pattern: The format pattern. See the PatternFormatter class - /// for details. - /// * times: Specifies whether times are adjusted for local time - /// or taken as they are in UTC. Supported values are "local" and "UTC". - /// - /// If any other property name is given, a PropertyNotSupported - /// exception is thrown. - - std::string getProperty(const std::string& name) const; - /// Returns the value of the property with the given name or - /// throws a PropertyNotSupported exception if the given - /// name is not recognized. - - static const std::string PROP_PATTERN; - static const std::string PROP_TIMES; - -protected: - static const std::string& getPriorityName(int); - /// Returns a string for the given priority value. - -private: - bool _localTime; - std::string _pattern; -}; - - -} // namespace Poco - - -#endif // Foundation_PatternFormatter_INCLUDED +// +// PatternFormatter.h +// +// $Id: //poco/1.2/Foundation/include/Poco/PatternFormatter.h#1 $ +// +// Library: Foundation +// Package: Logging +// Module: PatternFormatter +// +// Definition of the PatternFormatter class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_PatternFormatter_INCLUDED +#define Foundation_PatternFormatter_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Formatter.h" +#include "Poco/Message.h" + + +namespace Poco { + + +class Foundation_API PatternFormatter: public Formatter + /// This Formatter allows for custom formatting of + /// log messages based on format patterns. + /// + /// The format pattern is used as a template to format the message and + /// is copied character by character except for the following special characters, + /// which are replaced by the corresponding value. + /// + /// * %s - message source + /// * %t - message text + /// * %l - message priority level (1 .. 7) + /// * %p - message priority (Fatal, Critical, Error, Warning, Notice, Information, Debug, Trace) + /// * %q - abbreviated message priority (F, C, E, W,N, I, D, T) + /// * %P - message process identifier + /// * %T - message thread name + /// * %I - message thread identifier (numeric) + /// * %N - node or host name + /// * %w - message date/time abbreviated weekday (Mon, Tue, ...) + /// * %W - message date/time full weekday (Monday, Tuesday, ...) + /// * %b - message date/time abbreviated month (Jan, Feb, ...) + /// * %B - message date/time full month (January, February, ...) + /// * %d - message date/time zero-padded day of month (01 .. 31) + /// * %e - message date/time day of month (1 .. 31) + /// * %f - message date/time space-padded day of month ( 1 .. 31) + /// * %m - message date/time zero-padded month (01 .. 12) + /// * %n - message date/time month (1 .. 12) + /// * %o - message date/time space-padded month ( 1 .. 12) + /// * %y - message date/time year without century (70) + /// * %Y - message date/time year with century (1970) + /// * %H - message date/time hour (00 .. 23) + /// * %h - message date/time hour (00 .. 12) + /// * %a - message date/time am/pm + /// * %A - message date/time AM/PM + /// * %M - message date/time minute (00 .. 59) + /// * %S - message date/time second (00 .. 59) + /// * %i - message date/time millisecond (000 .. 999) + /// * %c - message date/time centisecond (0 .. 9) + /// * %z - time zone differential in ISO 8601 format (Z or +NN.NN). + /// * %Z - time zone differential in RFC format (GMT or +NNNN) + /// * %[name] - the value of the message parameter with the given name + /// * %% - percent sign + +{ +public: + PatternFormatter(); + /// Creates a PatternFormatter. + /// The format pattern must be specified with + /// a call to setProperty. + + PatternFormatter(const std::string& format); + /// Creates a PatternFormatter that uses the + /// given format pattern. + + ~PatternFormatter(); + /// Destroys the PatternFormatter. + + void format(const Message& msg, std::string& text); + /// Formats the message according to the specified + /// format pattern and places the result in text. + + void setProperty(const std::string& name, const std::string& value); + /// Sets the property with the given name to the given value. + /// + /// The following properties are supported: + /// + /// * pattern: The format pattern. See the PatternFormatter class + /// for details. + /// * times: Specifies whether times are adjusted for local time + /// or taken as they are in UTC. Supported values are "local" and "UTC". + /// + /// If any other property name is given, a PropertyNotSupported + /// exception is thrown. + + std::string getProperty(const std::string& name) const; + /// Returns the value of the property with the given name or + /// throws a PropertyNotSupported exception if the given + /// name is not recognized. + + static const std::string PROP_PATTERN; + static const std::string PROP_TIMES; + +protected: + static const std::string& getPriorityName(int); + /// Returns a string for the given priority value. + +private: + bool _localTime; + std::string _pattern; +}; + + +} // namespace Poco + + +#endif // Foundation_PatternFormatter_INCLUDED diff --git a/Foundation/include/Poco/Pipe.h b/Foundation/include/Poco/Pipe.h index 36477932f..f3a389479 100644 --- a/Foundation/include/Poco/Pipe.h +++ b/Foundation/include/Poco/Pipe.h @@ -1,164 +1,164 @@ -// -// Pipe.h -// -// $Id: //poco/1.2/Foundation/include/Poco/Pipe.h#1 $ -// -// Library: Foundation -// Package: Processes -// Module: Pipe -// -// Definition of the Pipe class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_Pipe_INCLUDED -#define Foundation_Pipe_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/PipeImpl.h" - - -namespace Poco { - - -class Foundation_API Pipe - /// This class implements an anonymous pipe. - /// - /// Pipes are a common method of inter-process communication - - /// on Unix, pipes are the oldest form of IPC. - /// - /// A pipe is a half-duplex communication channel, which means - /// that data only flows in one direction. - /// Pipes have a read-end and a write-end. One process writes to - /// the pipe and another process reads the data written by - /// its peer. - /// Read and write operations are always synchronous. A read will - /// block until data is available and a write will block until - /// the reader reads the data. - /// - /// The sendBytes() and readBytes() methods of Pipe are usually - /// used through a PipeOutputStream or PipeInputStream and are - /// not called directly. - /// - /// Pipe objects have value semantics; the actual work is delegated - /// to a reference-counted PipeImpl object. -{ -public: - typedef PipeImpl::Handle Handle; /// The read/write handle or file descriptor. - - enum CloseMode /// used by close() - { - CLOSE_READ = 0x01, /// Close reading end of pipe. - CLOSE_WRITE = 0x02, /// Close writing end of pipe. - CLOSE_BOTH = 0x03 /// Close both ends of pipe. - }; - - Pipe(); - /// Creates the Pipe. - /// - /// Throws a CreateFileException if the pipe cannot be - /// created. - - Pipe(const Pipe& pipe); - /// Creates the Pipe using the PipeImpl from another one. - - ~Pipe(); - /// Closes and destroys the Pipe. - - Pipe& operator = (const Pipe& pipe); - /// Releases the Pipe's PipeImpl and assigns another one. - - int writeBytes(const void* buffer, int length); - /// Sends the contents of the given buffer through - /// the pipe. Blocks until the receiver is ready - /// to read the data. - /// - /// Returns the number of bytes sent. - /// - /// Throws a WriteFileException if the data cannot be written. - - int readBytes(void* buffer, int length); - /// Receives data from the pipe and stores it - /// in buffer. Up to length bytes are received. - /// Blocks until data becomes available. - /// - /// Returns the number of bytes received, or 0 - /// if the pipe has been closed. - /// - /// Throws a ReadFileException if nothing can be read. - - Handle readHandle() const; - /// Returns the read handle or file descriptor - /// for the Pipe. For internal use only. - - Handle writeHandle() const; - /// Returns the write handle or file descriptor - /// for the Pipe. For internal use only. - - void close(CloseMode mode = CLOSE_BOTH); - /// Depending on the argument, closes either the - /// reading end, the writing end, or both ends - /// of the Pipe. - -private: - PipeImpl* _pImpl; -}; - - -// -// inlines -// -inline int Pipe::writeBytes(const void* buffer, int length) -{ - return _pImpl->writeBytes(buffer, length); -} - - -inline int Pipe::readBytes(void* buffer, int length) -{ - return _pImpl->readBytes(buffer, length); -} - - -inline Pipe::Handle Pipe::readHandle() const -{ - return _pImpl->readHandle(); -} - - -inline Pipe::Handle Pipe::writeHandle() const -{ - return _pImpl->writeHandle(); -} - - -} // namespace Poco - - -#endif // Foundation_Pipe_INCLUDED +// +// Pipe.h +// +// $Id: //poco/1.2/Foundation/include/Poco/Pipe.h#1 $ +// +// Library: Foundation +// Package: Processes +// Module: Pipe +// +// Definition of the Pipe class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_Pipe_INCLUDED +#define Foundation_Pipe_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/PipeImpl.h" + + +namespace Poco { + + +class Foundation_API Pipe + /// This class implements an anonymous pipe. + /// + /// Pipes are a common method of inter-process communication - + /// on Unix, pipes are the oldest form of IPC. + /// + /// A pipe is a half-duplex communication channel, which means + /// that data only flows in one direction. + /// Pipes have a read-end and a write-end. One process writes to + /// the pipe and another process reads the data written by + /// its peer. + /// Read and write operations are always synchronous. A read will + /// block until data is available and a write will block until + /// the reader reads the data. + /// + /// The sendBytes() and readBytes() methods of Pipe are usually + /// used through a PipeOutputStream or PipeInputStream and are + /// not called directly. + /// + /// Pipe objects have value semantics; the actual work is delegated + /// to a reference-counted PipeImpl object. +{ +public: + typedef PipeImpl::Handle Handle; /// The read/write handle or file descriptor. + + enum CloseMode /// used by close() + { + CLOSE_READ = 0x01, /// Close reading end of pipe. + CLOSE_WRITE = 0x02, /// Close writing end of pipe. + CLOSE_BOTH = 0x03 /// Close both ends of pipe. + }; + + Pipe(); + /// Creates the Pipe. + /// + /// Throws a CreateFileException if the pipe cannot be + /// created. + + Pipe(const Pipe& pipe); + /// Creates the Pipe using the PipeImpl from another one. + + ~Pipe(); + /// Closes and destroys the Pipe. + + Pipe& operator = (const Pipe& pipe); + /// Releases the Pipe's PipeImpl and assigns another one. + + int writeBytes(const void* buffer, int length); + /// Sends the contents of the given buffer through + /// the pipe. Blocks until the receiver is ready + /// to read the data. + /// + /// Returns the number of bytes sent. + /// + /// Throws a WriteFileException if the data cannot be written. + + int readBytes(void* buffer, int length); + /// Receives data from the pipe and stores it + /// in buffer. Up to length bytes are received. + /// Blocks until data becomes available. + /// + /// Returns the number of bytes received, or 0 + /// if the pipe has been closed. + /// + /// Throws a ReadFileException if nothing can be read. + + Handle readHandle() const; + /// Returns the read handle or file descriptor + /// for the Pipe. For internal use only. + + Handle writeHandle() const; + /// Returns the write handle or file descriptor + /// for the Pipe. For internal use only. + + void close(CloseMode mode = CLOSE_BOTH); + /// Depending on the argument, closes either the + /// reading end, the writing end, or both ends + /// of the Pipe. + +private: + PipeImpl* _pImpl; +}; + + +// +// inlines +// +inline int Pipe::writeBytes(const void* buffer, int length) +{ + return _pImpl->writeBytes(buffer, length); +} + + +inline int Pipe::readBytes(void* buffer, int length) +{ + return _pImpl->readBytes(buffer, length); +} + + +inline Pipe::Handle Pipe::readHandle() const +{ + return _pImpl->readHandle(); +} + + +inline Pipe::Handle Pipe::writeHandle() const +{ + return _pImpl->writeHandle(); +} + + +} // namespace Poco + + +#endif // Foundation_Pipe_INCLUDED diff --git a/Foundation/include/Poco/PipeImpl.h b/Foundation/include/Poco/PipeImpl.h index fa9030dc5..355aeae5c 100644 --- a/Foundation/include/Poco/PipeImpl.h +++ b/Foundation/include/Poco/PipeImpl.h @@ -1,55 +1,55 @@ -// -// PipeImpl.h -// -// $Id: //poco/1.2/Foundation/include/Poco/PipeImpl.h#1 $ -// -// Library: Foundation -// Package: Processes -// Module: PipeImpl -// -// Definition of the PipeImpl class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_PipeImpl_INCLUDED -#define Foundation_PipeImpl_INCLUDED - - -#include "Poco/Foundation.h" - - -#if defined(POCO_OS_FAMILY_WINDOWS) -#include "Poco/PipeImpl_WIN32.h" -#elif defined(POCO_OS_FAMILY_UNIX) -#include "Poco/PipeImpl_POSIX.h" -#else -#include "Poco/PipeImpl_DUMMY.h" -#endif - - -#endif // Foundation_PipeImpl_INCLUDED +// +// PipeImpl.h +// +// $Id: //poco/1.2/Foundation/include/Poco/PipeImpl.h#1 $ +// +// Library: Foundation +// Package: Processes +// Module: PipeImpl +// +// Definition of the PipeImpl class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_PipeImpl_INCLUDED +#define Foundation_PipeImpl_INCLUDED + + +#include "Poco/Foundation.h" + + +#if defined(POCO_OS_FAMILY_WINDOWS) +#include "Poco/PipeImpl_WIN32.h" +#elif defined(POCO_OS_FAMILY_UNIX) +#include "Poco/PipeImpl_POSIX.h" +#else +#include "Poco/PipeImpl_DUMMY.h" +#endif + + +#endif // Foundation_PipeImpl_INCLUDED diff --git a/Foundation/include/Poco/PipeImpl_DUMMY.h b/Foundation/include/Poco/PipeImpl_DUMMY.h index b01e14b27..d5794c370 100644 --- a/Foundation/include/Poco/PipeImpl_DUMMY.h +++ b/Foundation/include/Poco/PipeImpl_DUMMY.h @@ -1,71 +1,71 @@ -// -// PipeImpl_DUMMY.h -// -// $Id: //poco/1.2/Foundation/include/Poco/PipeImpl_DUMMY.h#1 $ -// -// Library: Foundation -// Package: Processes -// Module: PipeImpl -// -// Definition of the PipeImpl_DUMMY class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_PipeImpl_DUMMY_INCLUDED -#define Foundation_PipeImpl_DUMMY_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/RefCountedObject.h" - - -namespace Poco { - - -class Foundation_API PipeImpl: public RefCountedObject - /// A dummy implementation of PipeImpl for platforms - /// that do not support pipes. -{ -public: - typedef int Handle; - - PipeImpl(); - ~PipeImpl(); - int writeBytes(const void* buffer, int length); - int readBytes(void* buffer, int length); - Handle readHandle() const; - Handle writeHandle() const; - void closeRead(); - void closeWrite(); -}; - - -} // namespace Poco - - -#endif // Foundation_PipeImpl_DUMMY_INCLUDED +// +// PipeImpl_DUMMY.h +// +// $Id: //poco/1.2/Foundation/include/Poco/PipeImpl_DUMMY.h#1 $ +// +// Library: Foundation +// Package: Processes +// Module: PipeImpl +// +// Definition of the PipeImpl_DUMMY class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_PipeImpl_DUMMY_INCLUDED +#define Foundation_PipeImpl_DUMMY_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/RefCountedObject.h" + + +namespace Poco { + + +class Foundation_API PipeImpl: public RefCountedObject + /// A dummy implementation of PipeImpl for platforms + /// that do not support pipes. +{ +public: + typedef int Handle; + + PipeImpl(); + ~PipeImpl(); + int writeBytes(const void* buffer, int length); + int readBytes(void* buffer, int length); + Handle readHandle() const; + Handle writeHandle() const; + void closeRead(); + void closeWrite(); +}; + + +} // namespace Poco + + +#endif // Foundation_PipeImpl_DUMMY_INCLUDED diff --git a/Foundation/include/Poco/PipeImpl_POSIX.h b/Foundation/include/Poco/PipeImpl_POSIX.h index b6b4bc455..22fa8dc32 100644 --- a/Foundation/include/Poco/PipeImpl_POSIX.h +++ b/Foundation/include/Poco/PipeImpl_POSIX.h @@ -1,75 +1,75 @@ -// -// PipeImpl_POSIX.h -// -// $Id: //poco/1.2/Foundation/include/Poco/PipeImpl_POSIX.h#1 $ -// -// Library: Foundation -// Package: Processes -// Module: PipeImpl -// -// Definition of the PipeImpl class for POSIX. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_PipeImpl_POSIX_INCLUDED -#define Foundation_PipeImpl_POSIX_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/RefCountedObject.h" - - -namespace Poco { - - -class Foundation_API PipeImpl: public RefCountedObject - /// A dummy implementation of PipeImpl for platforms - /// that do not support pipes. -{ -public: - typedef int Handle; - - PipeImpl(); - ~PipeImpl(); - int writeBytes(const void* buffer, int length); - int readBytes(void* buffer, int length); - Handle readHandle() const; - Handle writeHandle() const; - void closeRead(); - void closeWrite(); - -private: - int _readfd; - int _writefd; -}; - - -} // namespace Poco - - -#endif // Foundation_PipeImpl_POSIX_INCLUDED +// +// PipeImpl_POSIX.h +// +// $Id: //poco/1.2/Foundation/include/Poco/PipeImpl_POSIX.h#1 $ +// +// Library: Foundation +// Package: Processes +// Module: PipeImpl +// +// Definition of the PipeImpl class for POSIX. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_PipeImpl_POSIX_INCLUDED +#define Foundation_PipeImpl_POSIX_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/RefCountedObject.h" + + +namespace Poco { + + +class Foundation_API PipeImpl: public RefCountedObject + /// A dummy implementation of PipeImpl for platforms + /// that do not support pipes. +{ +public: + typedef int Handle; + + PipeImpl(); + ~PipeImpl(); + int writeBytes(const void* buffer, int length); + int readBytes(void* buffer, int length); + Handle readHandle() const; + Handle writeHandle() const; + void closeRead(); + void closeWrite(); + +private: + int _readfd; + int _writefd; +}; + + +} // namespace Poco + + +#endif // Foundation_PipeImpl_POSIX_INCLUDED diff --git a/Foundation/include/Poco/PipeImpl_WIN32.h b/Foundation/include/Poco/PipeImpl_WIN32.h index cb7d60318..777561413 100644 --- a/Foundation/include/Poco/PipeImpl_WIN32.h +++ b/Foundation/include/Poco/PipeImpl_WIN32.h @@ -1,76 +1,76 @@ -// -// PipeImpl_WIN32.h -// -// $Id: //poco/1.2/Foundation/include/Poco/PipeImpl_WIN32.h#1 $ -// -// Library: Foundation -// Package: Processes -// Module: PipeImpl -// -// Definition of the PipeImpl class for WIN32. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_PipeImpl_WIN32_INCLUDED -#define Foundation_PipeImpl_WIN32_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/RefCountedObject.h" -#include - - -namespace Poco { - - -class Foundation_API PipeImpl: public RefCountedObject - /// A dummy implementation of PipeImpl for platforms - /// that do not support pipes. -{ -public: - typedef HANDLE Handle; - - PipeImpl(); - ~PipeImpl(); - int writeBytes(const void* buffer, int length); - int readBytes(void* buffer, int length); - Handle readHandle() const; - Handle writeHandle() const; - void closeRead(); - void closeWrite(); - -private: - HANDLE _readHandle; - HANDLE _writeHandle; -}; - - -} // namespace Poco - - -#endif // Foundation_PipeImpl_WIN32_INCLUDED +// +// PipeImpl_WIN32.h +// +// $Id: //poco/1.2/Foundation/include/Poco/PipeImpl_WIN32.h#1 $ +// +// Library: Foundation +// Package: Processes +// Module: PipeImpl +// +// Definition of the PipeImpl class for WIN32. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_PipeImpl_WIN32_INCLUDED +#define Foundation_PipeImpl_WIN32_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/RefCountedObject.h" +#include + + +namespace Poco { + + +class Foundation_API PipeImpl: public RefCountedObject + /// A dummy implementation of PipeImpl for platforms + /// that do not support pipes. +{ +public: + typedef HANDLE Handle; + + PipeImpl(); + ~PipeImpl(); + int writeBytes(const void* buffer, int length); + int readBytes(void* buffer, int length); + Handle readHandle() const; + Handle writeHandle() const; + void closeRead(); + void closeWrite(); + +private: + HANDLE _readHandle; + HANDLE _writeHandle; +}; + + +} // namespace Poco + + +#endif // Foundation_PipeImpl_WIN32_INCLUDED diff --git a/Foundation/include/Poco/PipeStream.h b/Foundation/include/Poco/PipeStream.h index c856ac2b2..03eb8fa47 100644 --- a/Foundation/include/Poco/PipeStream.h +++ b/Foundation/include/Poco/PipeStream.h @@ -1,142 +1,142 @@ -// -// PipeStream.h -// -// $Id: //poco/1.2/Foundation/include/Poco/PipeStream.h#1 $ -// -// Library: Foundation -// Package: Processes -// Module: PipeStream -// -// Definition of the PipeStream class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_PipeStream_INCLUDED -#define Foundation_PipeStream_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/Pipe.h" -#include "Poco/BufferedStreamBuf.h" -#include -#include - - -namespace Poco { - - -class Foundation_API PipeStreamBuf: public BufferedStreamBuf - /// This is the streambuf class used for reading from and writing to a Pipe. -{ -public: - typedef BufferedStreamBuf::openmode openmode; - - PipeStreamBuf(const Pipe& pipe, openmode mode); - /// Creates a PipeStreamBuf with the given Pipe. - - ~PipeStreamBuf(); - /// Destroys the PipeStreamBuf. - - void close(); - /// Closes the pipe. - -protected: - int readFromDevice(char* buffer, std::streamsize length); - int writeToDevice(const char* buffer, std::streamsize length); - -private: - enum - { - STREAM_BUFFER_SIZE = 1024 - }; - - Pipe _pipe; -}; - - -class Foundation_API PipeIOS: public virtual std::ios - /// The base class for PipeInputStream and - /// PipeOutputStream. - /// - /// This class is needed to ensure the correct initialization - /// order of the stream buffer and base classes. -{ -public: - PipeIOS(const Pipe& pipe, openmode mode); - /// Creates the PipeIOS with the given Pipe. - - ~PipeIOS(); - /// Destroys the PipeIOS. - /// - /// Flushes the buffer, but does not close the pipe. - - PipeStreamBuf* rdbuf(); - /// Returns a pointer to the internal PipeStreamBuf. - - void close(); - /// Flushes the stream and closes the pipe. - -protected: - PipeStreamBuf _buf; -}; - - -class Foundation_API PipeOutputStream: public PipeIOS, public std::ostream - /// An output stream for writing to a Pipe. -{ -public: - PipeOutputStream(const Pipe& pipe); - /// Creates the PipeOutputStream with the given Pipe. - - ~PipeOutputStream(); - /// Destroys the PipeOutputStream. - /// - /// Flushes the buffer, but does not close the pipe. -}; - - -class Foundation_API PipeInputStream: public PipeIOS, public std::istream - /// An input stream for reading from a Pipe. - /// - /// Using formatted input from a PipeInputStream - /// is not recommended, due to the read-ahead behavior of - /// istream with formatted reads. -{ -public: - PipeInputStream(const Pipe& pipe); - /// Creates the PipeInputStream with the given Pipe. - - ~PipeInputStream(); - /// Destroys the PipeInputStream. -}; - - -} // namespace Poco - - -#endif // Foundation_PipeStream_INCLUDED +// +// PipeStream.h +// +// $Id: //poco/1.2/Foundation/include/Poco/PipeStream.h#1 $ +// +// Library: Foundation +// Package: Processes +// Module: PipeStream +// +// Definition of the PipeStream class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_PipeStream_INCLUDED +#define Foundation_PipeStream_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Pipe.h" +#include "Poco/BufferedStreamBuf.h" +#include +#include + + +namespace Poco { + + +class Foundation_API PipeStreamBuf: public BufferedStreamBuf + /// This is the streambuf class used for reading from and writing to a Pipe. +{ +public: + typedef BufferedStreamBuf::openmode openmode; + + PipeStreamBuf(const Pipe& pipe, openmode mode); + /// Creates a PipeStreamBuf with the given Pipe. + + ~PipeStreamBuf(); + /// Destroys the PipeStreamBuf. + + void close(); + /// Closes the pipe. + +protected: + int readFromDevice(char* buffer, std::streamsize length); + int writeToDevice(const char* buffer, std::streamsize length); + +private: + enum + { + STREAM_BUFFER_SIZE = 1024 + }; + + Pipe _pipe; +}; + + +class Foundation_API PipeIOS: public virtual std::ios + /// The base class for PipeInputStream and + /// PipeOutputStream. + /// + /// This class is needed to ensure the correct initialization + /// order of the stream buffer and base classes. +{ +public: + PipeIOS(const Pipe& pipe, openmode mode); + /// Creates the PipeIOS with the given Pipe. + + ~PipeIOS(); + /// Destroys the PipeIOS. + /// + /// Flushes the buffer, but does not close the pipe. + + PipeStreamBuf* rdbuf(); + /// Returns a pointer to the internal PipeStreamBuf. + + void close(); + /// Flushes the stream and closes the pipe. + +protected: + PipeStreamBuf _buf; +}; + + +class Foundation_API PipeOutputStream: public PipeIOS, public std::ostream + /// An output stream for writing to a Pipe. +{ +public: + PipeOutputStream(const Pipe& pipe); + /// Creates the PipeOutputStream with the given Pipe. + + ~PipeOutputStream(); + /// Destroys the PipeOutputStream. + /// + /// Flushes the buffer, but does not close the pipe. +}; + + +class Foundation_API PipeInputStream: public PipeIOS, public std::istream + /// An input stream for reading from a Pipe. + /// + /// Using formatted input from a PipeInputStream + /// is not recommended, due to the read-ahead behavior of + /// istream with formatted reads. +{ +public: + PipeInputStream(const Pipe& pipe); + /// Creates the PipeInputStream with the given Pipe. + + ~PipeInputStream(); + /// Destroys the PipeInputStream. +}; + + +} // namespace Poco + + +#endif // Foundation_PipeStream_INCLUDED diff --git a/Foundation/include/Poco/Platform.h b/Foundation/include/Poco/Platform.h index b638bb538..a3d2099e1 100644 --- a/Foundation/include/Poco/Platform.h +++ b/Foundation/include/Poco/Platform.h @@ -1,181 +1,181 @@ -// -// Platform.h -// -// $Id: //poco/1.2/Foundation/include/Poco/Platform.h#1 $ -// -// Library: Foundation -// Package: Core -// Module: Platform -// -// Platform and architecture identification macros. -// -// NOTE: This file may be included from both C++ and C code, so it -// must not contain any C++ specific things. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_Platform_INCLUDED -#define Foundation_Platform_INCLUDED - - -// -// Platform Identification -// -#define POCO_OS_FREE_BSD 0x0001 -#define POCO_OS_AIX 0x0002 -#define POCO_OS_HPUX 0x0003 -#define POCO_OS_TRU64 0x0004 -#define POCO_OS_LINUX 0x0005 -#define POCO_OS_MAC_OS_X 0x0006 -#define POCO_OS_NET_BSD 0x0007 -#define POCO_OS_OPEN_BSD 0x0008 -#define POCO_OS_IRIX 0x0009 -#define POCO_OS_SOLARIS 0x000a -#define POCO_OS_QNX 0x000b -#define POCO_OS_VXWORKS 0x000c -#define POCO_OS_CYGWIN 0x000d -#define POCO_OS_UNKNOWN_UNIX 0x00ff -#define POCO_OS_WINDOWS_NT 0x1001 -#define POCO_OS_WINDOWS_CE 0x1011 -#define POCO_OS_VMS 0x2001 - - -#if defined(__FreeBSD__) - #define POCO_OS_FAMILY_UNIX 1 - #define POCO_OS_FAMILY_BSD 1 - #define POCO_OS POCO_OS_FREE_BSD -#elif defined(_AIX) || defined(__TOS_AIX__) - #define POCO_OS_FAMILY_UNIX 1 - #define POCO_OS POCO_OS_AIX -#elif defined(hpux) || defined(_hpux) - #define POCO_OS_FAMILY_UNIX 1 - #define POCO_OS POCO_OS_HPUX -#elif defined(__digital__) || defined(__osf__) - #define POCO_OS_FAMILY_UNIX 1 - #define POCO_OS POCO_OS_TRU64 -#elif defined(linux) || defined(__linux) || defined(__linux__) || defined(__TOS_LINUX__) - #define POCO_OS_FAMILY_UNIX 1 - #define POCO_OS POCO_OS_LINUX -#elif defined(__APPLE__) || defined(__TOS_MACOS__) - #define POCO_OS_FAMILY_UNIX 1 - #define POCO_OS_FAMILY_BSD 1 - #define POCO_OS POCO_OS_MAC_OS_X -#elif defined(__NetBSD__) - #define POCO_OS_FAMILY_UNIX 1 - #define POCO_OS_FAMILY_BSD 1 - #define POCO_OS POCO_OS_NET_BSD -#elif defined(__OpenBSD__) - #define POCO_OS_FAMILY_UNIX 1 - #define POCO_OS_FAMILY_BSD 1 - #define POCO_OS POCO_OS_OPEN_BSD -#elif defined(sgi) || defined(__sgi) - #define POCO_OS_FAMILY_UNIX 1 - #define POCO_OS POCO_OS_IRIX -#elif defined(sun) || defined(__sun) - #define POCO_OS_FAMILY_UNIX 1 - #define POCO_OS POCO_OS_SOLARIS -#elif defined(__QNX__) - #define POCO_OS_FAMILY_UNIX 1 - #define POCO_OS POCO_OS_QNX -#elif defined(unix) || defined(__unix) || defined(__unix__) - #define POCO_OS_FAMILY_UNIX 1 - #define POCO_OS POCO_OS_UNKNOWN_UNIX -#elif defined(_WIN32_WCE) - #define POCO_OS_FAMILY_WINDOWS 1 - #define POCO_OS POCO_OS_WINDOWS_CE -#elif defined(_WIN32) || defined(_WIN64) - #define POCO_OS_FAMILY_WINDOWS 1 - #define POCO_OS POCO_OS_WINDOWS_NT -#elif defined(__CYGWIN__) - #define POCO_OS_FAMILY_UNIX 1 - #define POCO_OS POCO_OS_CYGWIN -#elif defined(__VMS) - #define POCO_OS_FAMILY_VMS 1 - #define POCO_OS POCO_OS_VMS -#endif - - -// -// Hardware Architecture and Byte Order -// -#define POCO_ARCH_ALPHA 0x01 -#define POCO_ARCH_IA32 0x02 -#define POCO_ARCH_IA64 0x03 -#define POCO_ARCH_MIPS 0x04 -#define POCO_ARCH_HPPA 0x05 -#define POCO_ARCH_PPC 0x06 -#define POCO_ARCH_POWER 0x07 -#define POCO_ARCH_SPARC 0x08 -#define POCO_ARCH_AMD64 0x09 -#define POCO_ARCH_ARM 0x0a - - -#if defined(__ALPHA) || defined(__alpha) || defined(__alpha__) || defined(_M_ALPHA) - #define POCO_ARCH POCO_ARCH_ALPHA - #define POCO_ARCH_LITTLE_ENDIAN 1 -#elif defined(i386) || defined(__i386) || defined(__i386__) || defined(_M_IX86) - #define POCO_ARCH POCO_ARCH_IA32 - #define POCO_ARCH_LITTLE_ENDIAN 1 -#elif defined(_IA64) || defined(__IA64__) || defined(__ia64__) || defined(__ia64) || defined(_M_IA64) - #define POCO_ARCH POCO_ARCH_IA64 - #if defined(hpux) || defined(_hpux) - #define POCO_ARCH_BIG_ENDIAN 1 - #else - #define POCO_ARCH_LITTLE_ENDIAN 1 - #endif -#elif defined(__x86_64__) - #define POCO_ARCH POCO_ARCH_AMD64 - #define POCO_ARCH_LITTLE_ENDIAN 1 -#elif defined(__mips__) || defined(__mips) || defined(__MIPS__) || defined(_M_MRX000) - #define POCO_ARCH POCO_ARCH_MIPS - #define POCO_ARCH_BIG_ENDIAN 1 -#elif defined(__hppa) || defined(__hppa__) - #define POCO_ARCH POCO_ARCH_HPPA - #define POCO_ARCH_BIG_ENDIAN 1 -#elif defined(__PPC) || defined(__POWERPC__) || defined(__powerpc) || defined(__PPC__) || \ - defined(__powerpc__) || defined(__ppc__) || defined(_ARCH_PPC) || defined(_M_PPC) - #define POCO_ARCH POCO_ARCH_PPC - #define POCO_ARCH_BIG_ENDIAN 1 -#elif defined(_POWER) || defined(_ARCH_PWR) || defined(_ARCH_PWR2) || defined(_ARCH_PWR3) || \ - defined(_ARCH_PWR4) || defined(__THW_RS6000) - #define POCO_ARCH POCO_ARCH_POWER - #define POCO_ARCH_BIG_ENDIAN 1 -#elif defined(__sparc__) || defined(__sparc) || defined(sparc) - #define POCO_ARCH POCO_ARCH_SPARC - #define POCO_ARCH_BIG_ENDIAN 1 -#elif defined(__arm__) || defined(__arm) || defined(ARM) || defined(_ARM_) || defined(__ARM__) || defined(_M_ARM) - #define POCO_ARCH POCO_ARCH_ARM - #if defined(__ARMEB__) - #define POCO_ARCH_BIG_ENDIAN 1 - #else - #define POCO_ARCH_LITTLE_ENDIAN 1 - #endif -#endif - - -#endif // Foundation_Platform_INCLUDED +// +// Platform.h +// +// $Id: //poco/1.2/Foundation/include/Poco/Platform.h#1 $ +// +// Library: Foundation +// Package: Core +// Module: Platform +// +// Platform and architecture identification macros. +// +// NOTE: This file may be included from both C++ and C code, so it +// must not contain any C++ specific things. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_Platform_INCLUDED +#define Foundation_Platform_INCLUDED + + +// +// Platform Identification +// +#define POCO_OS_FREE_BSD 0x0001 +#define POCO_OS_AIX 0x0002 +#define POCO_OS_HPUX 0x0003 +#define POCO_OS_TRU64 0x0004 +#define POCO_OS_LINUX 0x0005 +#define POCO_OS_MAC_OS_X 0x0006 +#define POCO_OS_NET_BSD 0x0007 +#define POCO_OS_OPEN_BSD 0x0008 +#define POCO_OS_IRIX 0x0009 +#define POCO_OS_SOLARIS 0x000a +#define POCO_OS_QNX 0x000b +#define POCO_OS_VXWORKS 0x000c +#define POCO_OS_CYGWIN 0x000d +#define POCO_OS_UNKNOWN_UNIX 0x00ff +#define POCO_OS_WINDOWS_NT 0x1001 +#define POCO_OS_WINDOWS_CE 0x1011 +#define POCO_OS_VMS 0x2001 + + +#if defined(__FreeBSD__) + #define POCO_OS_FAMILY_UNIX 1 + #define POCO_OS_FAMILY_BSD 1 + #define POCO_OS POCO_OS_FREE_BSD +#elif defined(_AIX) || defined(__TOS_AIX__) + #define POCO_OS_FAMILY_UNIX 1 + #define POCO_OS POCO_OS_AIX +#elif defined(hpux) || defined(_hpux) + #define POCO_OS_FAMILY_UNIX 1 + #define POCO_OS POCO_OS_HPUX +#elif defined(__digital__) || defined(__osf__) + #define POCO_OS_FAMILY_UNIX 1 + #define POCO_OS POCO_OS_TRU64 +#elif defined(linux) || defined(__linux) || defined(__linux__) || defined(__TOS_LINUX__) + #define POCO_OS_FAMILY_UNIX 1 + #define POCO_OS POCO_OS_LINUX +#elif defined(__APPLE__) || defined(__TOS_MACOS__) + #define POCO_OS_FAMILY_UNIX 1 + #define POCO_OS_FAMILY_BSD 1 + #define POCO_OS POCO_OS_MAC_OS_X +#elif defined(__NetBSD__) + #define POCO_OS_FAMILY_UNIX 1 + #define POCO_OS_FAMILY_BSD 1 + #define POCO_OS POCO_OS_NET_BSD +#elif defined(__OpenBSD__) + #define POCO_OS_FAMILY_UNIX 1 + #define POCO_OS_FAMILY_BSD 1 + #define POCO_OS POCO_OS_OPEN_BSD +#elif defined(sgi) || defined(__sgi) + #define POCO_OS_FAMILY_UNIX 1 + #define POCO_OS POCO_OS_IRIX +#elif defined(sun) || defined(__sun) + #define POCO_OS_FAMILY_UNIX 1 + #define POCO_OS POCO_OS_SOLARIS +#elif defined(__QNX__) + #define POCO_OS_FAMILY_UNIX 1 + #define POCO_OS POCO_OS_QNX +#elif defined(unix) || defined(__unix) || defined(__unix__) + #define POCO_OS_FAMILY_UNIX 1 + #define POCO_OS POCO_OS_UNKNOWN_UNIX +#elif defined(_WIN32_WCE) + #define POCO_OS_FAMILY_WINDOWS 1 + #define POCO_OS POCO_OS_WINDOWS_CE +#elif defined(_WIN32) || defined(_WIN64) + #define POCO_OS_FAMILY_WINDOWS 1 + #define POCO_OS POCO_OS_WINDOWS_NT +#elif defined(__CYGWIN__) + #define POCO_OS_FAMILY_UNIX 1 + #define POCO_OS POCO_OS_CYGWIN +#elif defined(__VMS) + #define POCO_OS_FAMILY_VMS 1 + #define POCO_OS POCO_OS_VMS +#endif + + +// +// Hardware Architecture and Byte Order +// +#define POCO_ARCH_ALPHA 0x01 +#define POCO_ARCH_IA32 0x02 +#define POCO_ARCH_IA64 0x03 +#define POCO_ARCH_MIPS 0x04 +#define POCO_ARCH_HPPA 0x05 +#define POCO_ARCH_PPC 0x06 +#define POCO_ARCH_POWER 0x07 +#define POCO_ARCH_SPARC 0x08 +#define POCO_ARCH_AMD64 0x09 +#define POCO_ARCH_ARM 0x0a + + +#if defined(__ALPHA) || defined(__alpha) || defined(__alpha__) || defined(_M_ALPHA) + #define POCO_ARCH POCO_ARCH_ALPHA + #define POCO_ARCH_LITTLE_ENDIAN 1 +#elif defined(i386) || defined(__i386) || defined(__i386__) || defined(_M_IX86) + #define POCO_ARCH POCO_ARCH_IA32 + #define POCO_ARCH_LITTLE_ENDIAN 1 +#elif defined(_IA64) || defined(__IA64__) || defined(__ia64__) || defined(__ia64) || defined(_M_IA64) + #define POCO_ARCH POCO_ARCH_IA64 + #if defined(hpux) || defined(_hpux) + #define POCO_ARCH_BIG_ENDIAN 1 + #else + #define POCO_ARCH_LITTLE_ENDIAN 1 + #endif +#elif defined(__x86_64__) + #define POCO_ARCH POCO_ARCH_AMD64 + #define POCO_ARCH_LITTLE_ENDIAN 1 +#elif defined(__mips__) || defined(__mips) || defined(__MIPS__) || defined(_M_MRX000) + #define POCO_ARCH POCO_ARCH_MIPS + #define POCO_ARCH_BIG_ENDIAN 1 +#elif defined(__hppa) || defined(__hppa__) + #define POCO_ARCH POCO_ARCH_HPPA + #define POCO_ARCH_BIG_ENDIAN 1 +#elif defined(__PPC) || defined(__POWERPC__) || defined(__powerpc) || defined(__PPC__) || \ + defined(__powerpc__) || defined(__ppc__) || defined(_ARCH_PPC) || defined(_M_PPC) + #define POCO_ARCH POCO_ARCH_PPC + #define POCO_ARCH_BIG_ENDIAN 1 +#elif defined(_POWER) || defined(_ARCH_PWR) || defined(_ARCH_PWR2) || defined(_ARCH_PWR3) || \ + defined(_ARCH_PWR4) || defined(__THW_RS6000) + #define POCO_ARCH POCO_ARCH_POWER + #define POCO_ARCH_BIG_ENDIAN 1 +#elif defined(__sparc__) || defined(__sparc) || defined(sparc) + #define POCO_ARCH POCO_ARCH_SPARC + #define POCO_ARCH_BIG_ENDIAN 1 +#elif defined(__arm__) || defined(__arm) || defined(ARM) || defined(_ARM_) || defined(__ARM__) || defined(_M_ARM) + #define POCO_ARCH POCO_ARCH_ARM + #if defined(__ARMEB__) + #define POCO_ARCH_BIG_ENDIAN 1 + #else + #define POCO_ARCH_LITTLE_ENDIAN 1 + #endif +#endif + + +#endif // Foundation_Platform_INCLUDED diff --git a/Foundation/include/Poco/Platform_POSIX.h b/Foundation/include/Poco/Platform_POSIX.h index c87e24c1f..25a845416 100644 --- a/Foundation/include/Poco/Platform_POSIX.h +++ b/Foundation/include/Poco/Platform_POSIX.h @@ -1,57 +1,57 @@ -// -// Platform_POSIX.h -// -// $Id: //poco/1.2/Foundation/include/Poco/Platform_POSIX.h#1 $ -// -// Library: Foundation -// Package: Core -// Module: Platform -// -// Platform and architecture identification macros -// and platform-specific definitions for various POSIX platforms -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_Platform_POSIX_INCLUDED -#define Foundation_Platform_POSIX_INCLUDED - - -// -// PA-RISC based HP-UX platforms have some issues... -// -#if defined(hpux) || defined(_hpux) - #if defined(__hppa) || defined(__hppa__) - #define POCO_NO_SYS_SELECT_H 1 - #if defined(__HP_aCC) - #define POCO_NO_TEMPLATE_ICOMPARE 1 - #endif - #endif -#endif - - -#endif // Foundation_Platform_POSIX_INCLUDED +// +// Platform_POSIX.h +// +// $Id: //poco/1.2/Foundation/include/Poco/Platform_POSIX.h#1 $ +// +// Library: Foundation +// Package: Core +// Module: Platform +// +// Platform and architecture identification macros +// and platform-specific definitions for various POSIX platforms +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_Platform_POSIX_INCLUDED +#define Foundation_Platform_POSIX_INCLUDED + + +// +// PA-RISC based HP-UX platforms have some issues... +// +#if defined(hpux) || defined(_hpux) + #if defined(__hppa) || defined(__hppa__) + #define POCO_NO_SYS_SELECT_H 1 + #if defined(__HP_aCC) + #define POCO_NO_TEMPLATE_ICOMPARE 1 + #endif + #endif +#endif + + +#endif // Foundation_Platform_POSIX_INCLUDED diff --git a/Foundation/include/Poco/Platform_VMS.h b/Foundation/include/Poco/Platform_VMS.h index 27b23b73d..38a76dee7 100644 --- a/Foundation/include/Poco/Platform_VMS.h +++ b/Foundation/include/Poco/Platform_VMS.h @@ -1,92 +1,92 @@ -// -// Platform_VMS.h -// -// $Id: //poco/1.2/Foundation/include/Poco/Platform_VMS.h#1 $ -// -// Library: Foundation -// Package: Core -// Module: Platform -// -// Platform and architecture identification macros -// and platform-specific definitions for OpenVMS. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_Platform_VMS_INCLUDED -#define Foundation_Platform_VMS_INCLUDED - - -// Define the POCO_DESCRIPTOR_STRING and POCO_DESCRIPTOR_LITERAL -// macros which we use instead of $DESCRIPTOR and $DESCRIPTOR64. -// Our macros work with both 32bit and 64bit pointer sizes. -#if __INITIAL_POINTER_SIZE != 64 - #define POCO_DESCRIPTOR_STRING(name, string) \ - struct dsc$descriptor_s name = \ - { \ - string.size(), \ - DSC$K_DTYPE_T, \ - DSC$K_CLASS_S, \ - (char*) string.data() \ - } - #define POCO_DESCRIPTOR_LITERAL(name, string) \ - struct dsc$descriptor_s name = \ - { \ - sizeof(string) - 1, \ - DSC$K_DTYPE_T, \ - DSC$K_CLASS_S, \ - (char*) string \ - } -#else - #define POCO_DESCRIPTOR_STRING(name, string) \ - struct dsc64$descriptor_s name =\ - { \ - 1, \ - DSC64$K_DTYPE_T, \ - DSC64$K_CLASS_S, \ - -1, \ - string.size(), \ - (char*) string.data() \ - } - #define POCO_DESCRIPTOR_LITERAL(name, string) \ - struct dsc64$descriptor_s name =\ - { \ - 1, \ - DSC64$K_DTYPE_T, \ - DSC64$K_CLASS_S, \ - -1, \ - sizeof(string) - 1, \ - (char*) string \ - } -#endif - - -// No header file -#define POCO_NO_SYS_SELECT_H - - -#endif // Foundation_Platform_VMS_INCLUDED +// +// Platform_VMS.h +// +// $Id: //poco/1.2/Foundation/include/Poco/Platform_VMS.h#1 $ +// +// Library: Foundation +// Package: Core +// Module: Platform +// +// Platform and architecture identification macros +// and platform-specific definitions for OpenVMS. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_Platform_VMS_INCLUDED +#define Foundation_Platform_VMS_INCLUDED + + +// Define the POCO_DESCRIPTOR_STRING and POCO_DESCRIPTOR_LITERAL +// macros which we use instead of $DESCRIPTOR and $DESCRIPTOR64. +// Our macros work with both 32bit and 64bit pointer sizes. +#if __INITIAL_POINTER_SIZE != 64 + #define POCO_DESCRIPTOR_STRING(name, string) \ + struct dsc$descriptor_s name = \ + { \ + string.size(), \ + DSC$K_DTYPE_T, \ + DSC$K_CLASS_S, \ + (char*) string.data() \ + } + #define POCO_DESCRIPTOR_LITERAL(name, string) \ + struct dsc$descriptor_s name = \ + { \ + sizeof(string) - 1, \ + DSC$K_DTYPE_T, \ + DSC$K_CLASS_S, \ + (char*) string \ + } +#else + #define POCO_DESCRIPTOR_STRING(name, string) \ + struct dsc64$descriptor_s name =\ + { \ + 1, \ + DSC64$K_DTYPE_T, \ + DSC64$K_CLASS_S, \ + -1, \ + string.size(), \ + (char*) string.data() \ + } + #define POCO_DESCRIPTOR_LITERAL(name, string) \ + struct dsc64$descriptor_s name =\ + { \ + 1, \ + DSC64$K_DTYPE_T, \ + DSC64$K_CLASS_S, \ + -1, \ + sizeof(string) - 1, \ + (char*) string \ + } +#endif + + +// No header file +#define POCO_NO_SYS_SELECT_H + + +#endif // Foundation_Platform_VMS_INCLUDED diff --git a/Foundation/include/Poco/Platform_WIN32.h b/Foundation/include/Poco/Platform_WIN32.h index d00ae3079..370963516 100644 --- a/Foundation/include/Poco/Platform_WIN32.h +++ b/Foundation/include/Poco/Platform_WIN32.h @@ -1,86 +1,86 @@ -// -// Platform_WIN32.h -// -// $Id: //poco/1.2/Foundation/include/Poco/Platform_WIN32.h#1 $ -// -// Library: Foundation -// Package: Core -// Module: Platform -// -// Platform and architecture identification macros -// and platform-specific definitions for Windows. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_Platform_WIN32_INCLUDED -#define Foundation_Platform_WIN32_INCLUDED - - -// Verify that we're built with the multithreaded -// versions of the runtime libraries -#if defined(_MSC_VER) && !defined(_MT) - #error Must compile with /MD, /MDd, /MT or /MTd -#endif - - -// Check debug/release settings consistency -#if defined(NDEBUG) && defined(_DEBUG) - #error Inconsistent build settings (check for /MD[d]) -#endif - - -// Reduce bloat imported by -#if defined(_WIN32) - #if !defined(_WIN32_WINNT) - #define _WIN32_WINNT 0x0500 - #endif - #if !defined(WIN32_LEAN_AND_MEAN) && !defined(POCO_BLOATED_WIN32) - #define WIN32_LEAN_AND_MEAN - #endif -#endif - - -// Unicode Support -#if defined(UNICODE) && !defined(POCO_WIN32_UTF8) -#define POCO_WIN32_UTF8 -#endif -#if defined(POCO_WIN32_UTF8) && !defined(UNICODE) -#define UNICODE -#endif - - -// Turn off some annoying warnings -#if defined(_MSC_VER) - #pragma warning(disable:4018) // signed/unsigned comparison - #pragma warning(disable:4251) // ... needs to have dll-interface warning - #pragma warning(disable:4355) // 'this' : used in base member initializer list - #pragma warning(disable:4996) // VC++ 8.0 deprecation warnings -#endif - - -#endif // Foundation_Platform_WIN32_INCLUDED +// +// Platform_WIN32.h +// +// $Id: //poco/1.2/Foundation/include/Poco/Platform_WIN32.h#1 $ +// +// Library: Foundation +// Package: Core +// Module: Platform +// +// Platform and architecture identification macros +// and platform-specific definitions for Windows. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_Platform_WIN32_INCLUDED +#define Foundation_Platform_WIN32_INCLUDED + + +// Verify that we're built with the multithreaded +// versions of the runtime libraries +#if defined(_MSC_VER) && !defined(_MT) + #error Must compile with /MD, /MDd, /MT or /MTd +#endif + + +// Check debug/release settings consistency +#if defined(NDEBUG) && defined(_DEBUG) + #error Inconsistent build settings (check for /MD[d]) +#endif + + +// Reduce bloat imported by +#if defined(_WIN32) + #if !defined(_WIN32_WINNT) + #define _WIN32_WINNT 0x0500 + #endif + #if !defined(WIN32_LEAN_AND_MEAN) && !defined(POCO_BLOATED_WIN32) + #define WIN32_LEAN_AND_MEAN + #endif +#endif + + +// Unicode Support +#if defined(UNICODE) && !defined(POCO_WIN32_UTF8) +#define POCO_WIN32_UTF8 +#endif +#if defined(POCO_WIN32_UTF8) && !defined(UNICODE) +#define UNICODE +#endif + + +// Turn off some annoying warnings +#if defined(_MSC_VER) + #pragma warning(disable:4018) // signed/unsigned comparison + #pragma warning(disable:4251) // ... needs to have dll-interface warning + #pragma warning(disable:4355) // 'this' : used in base member initializer list + #pragma warning(disable:4996) // VC++ 8.0 deprecation warnings +#endif + + +#endif // Foundation_Platform_WIN32_INCLUDED diff --git a/Foundation/include/Poco/Poco.h b/Foundation/include/Poco/Poco.h index 4d55fb490..bdeab3bc2 100644 --- a/Foundation/include/Poco/Poco.h +++ b/Foundation/include/Poco/Poco.h @@ -1,46 +1,46 @@ -// -// Poco.h -// -// $Id: //poco/1.2/Foundation/include/Poco/Poco.h#1 $ -// -// Library: Foundation -// Package: Core -// Module: Foundation -// -// Basic definitions for the POCO libraries. -// -// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_Poco_INCLUDED -#define Foundation_Poco_INCLUDED - - -#include "Poco/Foundation.h" - - -#endif // Foundation_Poco_INCLUDED +// +// Poco.h +// +// $Id: //poco/1.2/Foundation/include/Poco/Poco.h#1 $ +// +// Library: Foundation +// Package: Core +// Module: Foundation +// +// Basic definitions for the POCO libraries. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_Poco_INCLUDED +#define Foundation_Poco_INCLUDED + + +#include "Poco/Foundation.h" + + +#endif // Foundation_Poco_INCLUDED diff --git a/Foundation/include/Poco/PriorityDelegate.h b/Foundation/include/Poco/PriorityDelegate.h index 6680e4806..874a8e6b2 100644 --- a/Foundation/include/Poco/PriorityDelegate.h +++ b/Foundation/include/Poco/PriorityDelegate.h @@ -1,110 +1,110 @@ -// -// PriorityDelegate.h -// -// $Id: //poco/1.2/Foundation/include/Poco/PriorityDelegate.h#3 $ -// -// Library: Foundation -// Package: Events -// Module: PriorityDelegate -// -// Implementation of the PriorityDelegate template. -// -// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_PriorityDelegate_INCLUDED -#define Foundation_PriorityDelegate_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/AbstractPriorityDelegate.h" -#include "Poco/PriorityExpire.h" - - -namespace Poco { - - -template -class PriorityDelegate: public AbstractPriorityDelegate -{ -public: - typedef void (TObj::*NotifyMethod)(const void*, TArgs&); - - PriorityDelegate(TObj* obj, NotifyMethod method, int prio): - AbstractPriorityDelegate(obj, prio), - _receiverObject(obj), - _receiverMethod(method) - { - } - - PriorityDelegate(const PriorityDelegate& delegate): - AbstractPriorityDelegate(delegate._pTarget, delegate._priority), - _receiverObject(delegate._receiverObject), - _receiverMethod(delegate._receiverMethod) - { - } - - PriorityDelegate& operator = (const PriorityDelegate& delegate) - { - if (&delegate != this) - { - this->_pTarget = delegate._pTarget; - this->_receiverObject = delegate._receiverObject; - this->_receiverMethod = delegate._receiverMethod; - this->_priority = delegate._priority; - } - return *this; - } - - ~PriorityDelegate() - { - } - - bool notify(const void* sender, TArgs& arguments) - { - (_receiverObject->*_receiverMethod)(sender, arguments); - return true; // per default the delegate never expires - } - - AbstractPriorityDelegate* clone() const - { - return new PriorityDelegate(*this); - } - -protected: - TObj* _receiverObject; - NotifyMethod _receiverMethod; - -private: - PriorityDelegate(); -}; - - -} // namespace Poco - - -#endif +// +// PriorityDelegate.h +// +// $Id: //poco/1.2/Foundation/include/Poco/PriorityDelegate.h#3 $ +// +// Library: Foundation +// Package: Events +// Module: PriorityDelegate +// +// Implementation of the PriorityDelegate template. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_PriorityDelegate_INCLUDED +#define Foundation_PriorityDelegate_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/AbstractPriorityDelegate.h" +#include "Poco/PriorityExpire.h" + + +namespace Poco { + + +template +class PriorityDelegate: public AbstractPriorityDelegate +{ +public: + typedef void (TObj::*NotifyMethod)(const void*, TArgs&); + + PriorityDelegate(TObj* obj, NotifyMethod method, int prio): + AbstractPriorityDelegate(obj, prio), + _receiverObject(obj), + _receiverMethod(method) + { + } + + PriorityDelegate(const PriorityDelegate& delegate): + AbstractPriorityDelegate(delegate._pTarget, delegate._priority), + _receiverObject(delegate._receiverObject), + _receiverMethod(delegate._receiverMethod) + { + } + + PriorityDelegate& operator = (const PriorityDelegate& delegate) + { + if (&delegate != this) + { + this->_pTarget = delegate._pTarget; + this->_receiverObject = delegate._receiverObject; + this->_receiverMethod = delegate._receiverMethod; + this->_priority = delegate._priority; + } + return *this; + } + + ~PriorityDelegate() + { + } + + bool notify(const void* sender, TArgs& arguments) + { + (_receiverObject->*_receiverMethod)(sender, arguments); + return true; // per default the delegate never expires + } + + AbstractPriorityDelegate* clone() const + { + return new PriorityDelegate(*this); + } + +protected: + TObj* _receiverObject; + NotifyMethod _receiverMethod; + +private: + PriorityDelegate(); +}; + + +} // namespace Poco + + +#endif diff --git a/Foundation/include/Poco/PriorityEvent.h b/Foundation/include/Poco/PriorityEvent.h index af20a5fa8..26e131d10 100644 --- a/Foundation/include/Poco/PriorityEvent.h +++ b/Foundation/include/Poco/PriorityEvent.h @@ -1,90 +1,90 @@ -// -// PriorityEvent.h -// -// $Id: //poco/1.2/Foundation/include/Poco/PriorityEvent.h#1 $ -// -// Library: Foundation -// Package: Events -// Module: PriorityEvent -// -// Implementation of the PriorityEvent template. -// -// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_PriorityEvent_INCLUDED -#define Foundation_PriorityEvent_INCLUDED - - -#include "Poco/AbstractEvent.h" -#include "Poco/DefaultStrategy.h" -#include "Poco/AbstractPriorityDelegate.h" -#include "Poco/CompareFunctions.h" - - -namespace Poco { - - -template -class PriorityEvent: public AbstractEvent < - TArgs, - DefaultStrategy, p_less > >, - AbstractPriorityDelegate -> - /// A PriorityEvent uses internally a DefaultStrategy which - /// invokes delegates in a manner determined by the priority field - /// in the PriorityDelegates (lower priorities first). - /// PriorityEvents can only be used together with PriorityDelegates. - /// PriorityDelegates are sorted according to the priority value, when - /// two delegates have the same priority, they are invoked in - /// an arbitrary manner. - /// Note that one object can register several methods as long as they differ - /// in their priority value: - /// PriorityEvent tmp; - /// MyClass myObject; - /// tmp += PriorityDelegate(&myObject, &MyClass::myMethod1, 1); - /// tmp += PriorityDelegate(&myObject, &MyClass::myMethod2, 2); -{ -public: - PriorityEvent() - { - } - - ~PriorityEvent() - { - } - -private: - PriorityEvent(const PriorityEvent& e); - PriorityEvent& operator = (const PriorityEvent& e); -}; - - -} // namespace Poco - - -#endif +// +// PriorityEvent.h +// +// $Id: //poco/1.2/Foundation/include/Poco/PriorityEvent.h#1 $ +// +// Library: Foundation +// Package: Events +// Module: PriorityEvent +// +// Implementation of the PriorityEvent template. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_PriorityEvent_INCLUDED +#define Foundation_PriorityEvent_INCLUDED + + +#include "Poco/AbstractEvent.h" +#include "Poco/DefaultStrategy.h" +#include "Poco/AbstractPriorityDelegate.h" +#include "Poco/CompareFunctions.h" + + +namespace Poco { + + +template +class PriorityEvent: public AbstractEvent < + TArgs, + DefaultStrategy, p_less > >, + AbstractPriorityDelegate +> + /// A PriorityEvent uses internally a DefaultStrategy which + /// invokes delegates in a manner determined by the priority field + /// in the PriorityDelegates (lower priorities first). + /// PriorityEvents can only be used together with PriorityDelegates. + /// PriorityDelegates are sorted according to the priority value, when + /// two delegates have the same priority, they are invoked in + /// an arbitrary manner. + /// Note that one object can register several methods as long as they differ + /// in their priority value: + /// PriorityEvent tmp; + /// MyClass myObject; + /// tmp += PriorityDelegate(&myObject, &MyClass::myMethod1, 1); + /// tmp += PriorityDelegate(&myObject, &MyClass::myMethod2, 2); +{ +public: + PriorityEvent() + { + } + + ~PriorityEvent() + { + } + +private: + PriorityEvent(const PriorityEvent& e); + PriorityEvent& operator = (const PriorityEvent& e); +}; + + +} // namespace Poco + + +#endif diff --git a/Foundation/include/Poco/PriorityExpire.h b/Foundation/include/Poco/PriorityExpire.h index a0d352e23..887a2113b 100644 --- a/Foundation/include/Poco/PriorityExpire.h +++ b/Foundation/include/Poco/PriorityExpire.h @@ -1,132 +1,132 @@ -// -// PriorityExpire.h -// -// $Id: //poco/1.2/Foundation/include/Poco/PriorityExpire.h#2 $ -// -// Library: Foundation -// Package: Events -// Module: PriorityExpire -// -// Implementation of the PriorityExpire template. -// -// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_PriorityExpire_INCLUDED -#define Foundation_PriorityExpire_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/Timestamp.h" -#include "Poco/AbstractPriorityDelegate.h" - - -namespace Poco { - - -template -class PriorityExpire: public AbstractPriorityDelegate - /// Decorator for AbstractPriorityDelegate adding automatic - /// expiring of registrations to AbstractPriorityDelegate. -{ -public: - PriorityExpire(const AbstractPriorityDelegate& p, Timestamp::TimeDiff expireMilliSec): - AbstractPriorityDelegate(p), - _pDelegate(p.clone()), - _expire(expireMilliSec*1000) - { - } - - PriorityExpire(const PriorityExpire& expire): - AbstractPriorityDelegate(expire), - _pDelegate(expire._pDelegate->clone()), - _expire(expire._expire), - _creationTime(expire._creationTime) - { - } - - ~PriorityExpire() - { - destroy(); - } - - PriorityExpire& operator = (const PriorityExpire& expire) - { - if (&expire != this) - { - delete this->_pDelegate; - this->_pTarget = expire._pTarget; - this->_pDelegate = expire._pDelegate->clone(); - this->_expire = expire._expire; - this->_creationTime = expire._creationTime; - } - return *this; - } - - bool notify(const void* sender, TArgs& arguments) - { - if (!expired()) - return this->_pDelegate->notify(sender, arguments); - else - return false; - } - - AbstractPriorityDelegate* clone() const - { - return new PriorityExpire(*this); - } - - void destroy() - { - delete this->_pDelegate; - this->_pDelegate = 0; - } - - const AbstractPriorityDelegate& getDelegate() const - { - return *this->_pDelegate; - } - -protected: - bool expired() const - { - return _creationTime.isElapsed(_expire); - } - - AbstractPriorityDelegate* _pDelegate; - Timestamp::TimeDiff _expire; - Timestamp _creationTime; - -private: - PriorityExpire(); -}; - - -} // namespace Poco - - -#endif +// +// PriorityExpire.h +// +// $Id: //poco/1.2/Foundation/include/Poco/PriorityExpire.h#2 $ +// +// Library: Foundation +// Package: Events +// Module: PriorityExpire +// +// Implementation of the PriorityExpire template. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_PriorityExpire_INCLUDED +#define Foundation_PriorityExpire_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Timestamp.h" +#include "Poco/AbstractPriorityDelegate.h" + + +namespace Poco { + + +template +class PriorityExpire: public AbstractPriorityDelegate + /// Decorator for AbstractPriorityDelegate adding automatic + /// expiring of registrations to AbstractPriorityDelegate. +{ +public: + PriorityExpire(const AbstractPriorityDelegate& p, Timestamp::TimeDiff expireMilliSec): + AbstractPriorityDelegate(p), + _pDelegate(p.clone()), + _expire(expireMilliSec*1000) + { + } + + PriorityExpire(const PriorityExpire& expire): + AbstractPriorityDelegate(expire), + _pDelegate(expire._pDelegate->clone()), + _expire(expire._expire), + _creationTime(expire._creationTime) + { + } + + ~PriorityExpire() + { + destroy(); + } + + PriorityExpire& operator = (const PriorityExpire& expire) + { + if (&expire != this) + { + delete this->_pDelegate; + this->_pTarget = expire._pTarget; + this->_pDelegate = expire._pDelegate->clone(); + this->_expire = expire._expire; + this->_creationTime = expire._creationTime; + } + return *this; + } + + bool notify(const void* sender, TArgs& arguments) + { + if (!expired()) + return this->_pDelegate->notify(sender, arguments); + else + return false; + } + + AbstractPriorityDelegate* clone() const + { + return new PriorityExpire(*this); + } + + void destroy() + { + delete this->_pDelegate; + this->_pDelegate = 0; + } + + const AbstractPriorityDelegate& getDelegate() const + { + return *this->_pDelegate; + } + +protected: + bool expired() const + { + return _creationTime.isElapsed(_expire); + } + + AbstractPriorityDelegate* _pDelegate; + Timestamp::TimeDiff _expire; + Timestamp _creationTime; + +private: + PriorityExpire(); +}; + + +} // namespace Poco + + +#endif diff --git a/Foundation/include/Poco/Process.h b/Foundation/include/Poco/Process.h index b83761119..d14a17eae 100644 --- a/Foundation/include/Poco/Process.h +++ b/Foundation/include/Poco/Process.h @@ -1,186 +1,186 @@ -// -// Process.h -// -// $Id: //poco/1.2/Foundation/include/Poco/Process.h#1 $ -// -// Library: Foundation -// Package: Processes -// Module: Process -// -// Definition of the Process class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_Process_INCLUDED -#define Foundation_Process_INCLUDED - - -#include "Poco/Foundation.h" - - -#if defined(POCO_OS_FAMILY_WINDOWS) && defined(POCO_WIN32_UTF8) -#include "Poco/Process_WIN32U.h" -#elif defined(POCO_OS_FAMILY_WINDOWS) -#include "Poco/Process_WIN32.h" -#elif defined(POCO_OS_FAMILY_UNIX) -#include "Poco/Process_UNIX.h" -#else -#include "Poco/Process_VMS.h" -#endif - - -namespace Poco { - - -class Pipe; - - -class Foundation_API ProcessHandle - /// A handle for a process created with Process::launch(). - /// - /// This handle can be used to determine the process ID of - /// the newly created process and it can be used to wait for - /// the completion of a process. -{ -public: - typedef ProcessImpl::PIDImpl PID; - - ProcessHandle(const ProcessHandle& handle); - /// Creates a ProcessHandle by copying another one. - - ~ProcessHandle(); - /// Destroys the ProcessHandle. - - ProcessHandle& operator = (const ProcessHandle& handle); - /// Assigns another handle. - - PID id() const; - /// Returns the process ID. - - int wait() const; - /// Waits for the process to terminate - /// and returns the exit code of the process. - -protected: - ProcessHandle(ProcessHandleImpl* pImpl); - -private: - ProcessHandle(); - - ProcessHandleImpl* _pImpl; - - friend class Process; -}; - - -class Foundation_API Process: public ProcessImpl - /// This class provides methods for working with processes. -{ -public: - typedef PIDImpl PID; - typedef ArgsImpl Args; - - static PID id(); - /// Returns the process ID of the current process. - - static void times(long& userTime, long& kernelTime); - /// Returns the number of seconds spent by the - /// current process in user and kernel mode. - - static ProcessHandle launch(const std::string& command, const Args& args); - /// Creates a new process for the given command and returns - /// a ProcessHandle of the new process. The given arguments are - /// passed to the command on the command line. - - static ProcessHandle launch(const std::string& command, const Args& args, Pipe* inPipe, Pipe* outPipe, Pipe* errPipe); - /// Creates a new process for the given command and returns - /// a ProcessHandle of the new process. The given arguments are - /// passed to the command on the command line. - /// - /// If inPipe, outPipe or errPipe is non-null, the corresponding - /// standard input, standard output or standard error stream - /// of the launched process is redirected to the Pipe. - /// PipeInputStream or PipeOutputStream can be used to - /// send receive data from, or send data to the process. - /// - /// Note: the same Pipe can be used for both outPipe and errPipe. - /// - /// After a Pipe has been passed as inPipe, only write operations - /// are valid. After a Pipe has been passed as outPipe or errPipe, - /// only read operations are valid. - /// - /// It is forbidden to pass the same pipe as inPipe and outPipe or errPipe. - /// - /// Usage example: - /// Pipe outPipe; - /// Process::Args args; - /// ProcessHandle ph(launch("/bin/ps", args, &outPipe, 0, 0)); - /// PipeInputStream istr(outPipe); - /// ... // read output of ps from istr - /// int rc = ph.wait(); - - static int wait(const ProcessHandle& handle); - /// Waits for the process specified by handle to terminate - /// and returns the exit code of the process. - - static void kill(PID pid); - /// Kills the process with the given pid. - - static void requestTermination(PID pid); - /// Requests termination of the process with the give PID. - /// - /// On Unix platforms, this will send a SIGINT to the - /// process and thus work with arbitrary processes. - /// - /// On other platforms, a global event flag - /// will be set. Setting the flag will cause - /// Util::ServerApplication::waitForTerminationRequest() to - /// return. Therefore this will only work with applications - /// based on Util::ServerApplication. -}; - - -// -// inlines -// -inline Process::PID Process::id() -{ - return ProcessImpl::idImpl(); -} - - -inline void Process::times(long& userTime, long& kernelTime) -{ - ProcessImpl::timesImpl(userTime, kernelTime); -} - - -} // namespace Poco - - -#endif // Foundation_Process_INCLUDED +// +// Process.h +// +// $Id: //poco/1.2/Foundation/include/Poco/Process.h#1 $ +// +// Library: Foundation +// Package: Processes +// Module: Process +// +// Definition of the Process class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_Process_INCLUDED +#define Foundation_Process_INCLUDED + + +#include "Poco/Foundation.h" + + +#if defined(POCO_OS_FAMILY_WINDOWS) && defined(POCO_WIN32_UTF8) +#include "Poco/Process_WIN32U.h" +#elif defined(POCO_OS_FAMILY_WINDOWS) +#include "Poco/Process_WIN32.h" +#elif defined(POCO_OS_FAMILY_UNIX) +#include "Poco/Process_UNIX.h" +#else +#include "Poco/Process_VMS.h" +#endif + + +namespace Poco { + + +class Pipe; + + +class Foundation_API ProcessHandle + /// A handle for a process created with Process::launch(). + /// + /// This handle can be used to determine the process ID of + /// the newly created process and it can be used to wait for + /// the completion of a process. +{ +public: + typedef ProcessImpl::PIDImpl PID; + + ProcessHandle(const ProcessHandle& handle); + /// Creates a ProcessHandle by copying another one. + + ~ProcessHandle(); + /// Destroys the ProcessHandle. + + ProcessHandle& operator = (const ProcessHandle& handle); + /// Assigns another handle. + + PID id() const; + /// Returns the process ID. + + int wait() const; + /// Waits for the process to terminate + /// and returns the exit code of the process. + +protected: + ProcessHandle(ProcessHandleImpl* pImpl); + +private: + ProcessHandle(); + + ProcessHandleImpl* _pImpl; + + friend class Process; +}; + + +class Foundation_API Process: public ProcessImpl + /// This class provides methods for working with processes. +{ +public: + typedef PIDImpl PID; + typedef ArgsImpl Args; + + static PID id(); + /// Returns the process ID of the current process. + + static void times(long& userTime, long& kernelTime); + /// Returns the number of seconds spent by the + /// current process in user and kernel mode. + + static ProcessHandle launch(const std::string& command, const Args& args); + /// Creates a new process for the given command and returns + /// a ProcessHandle of the new process. The given arguments are + /// passed to the command on the command line. + + static ProcessHandle launch(const std::string& command, const Args& args, Pipe* inPipe, Pipe* outPipe, Pipe* errPipe); + /// Creates a new process for the given command and returns + /// a ProcessHandle of the new process. The given arguments are + /// passed to the command on the command line. + /// + /// If inPipe, outPipe or errPipe is non-null, the corresponding + /// standard input, standard output or standard error stream + /// of the launched process is redirected to the Pipe. + /// PipeInputStream or PipeOutputStream can be used to + /// send receive data from, or send data to the process. + /// + /// Note: the same Pipe can be used for both outPipe and errPipe. + /// + /// After a Pipe has been passed as inPipe, only write operations + /// are valid. After a Pipe has been passed as outPipe or errPipe, + /// only read operations are valid. + /// + /// It is forbidden to pass the same pipe as inPipe and outPipe or errPipe. + /// + /// Usage example: + /// Pipe outPipe; + /// Process::Args args; + /// ProcessHandle ph(launch("/bin/ps", args, &outPipe, 0, 0)); + /// PipeInputStream istr(outPipe); + /// ... // read output of ps from istr + /// int rc = ph.wait(); + + static int wait(const ProcessHandle& handle); + /// Waits for the process specified by handle to terminate + /// and returns the exit code of the process. + + static void kill(PID pid); + /// Kills the process with the given pid. + + static void requestTermination(PID pid); + /// Requests termination of the process with the give PID. + /// + /// On Unix platforms, this will send a SIGINT to the + /// process and thus work with arbitrary processes. + /// + /// On other platforms, a global event flag + /// will be set. Setting the flag will cause + /// Util::ServerApplication::waitForTerminationRequest() to + /// return. Therefore this will only work with applications + /// based on Util::ServerApplication. +}; + + +// +// inlines +// +inline Process::PID Process::id() +{ + return ProcessImpl::idImpl(); +} + + +inline void Process::times(long& userTime, long& kernelTime) +{ + ProcessImpl::timesImpl(userTime, kernelTime); +} + + +} // namespace Poco + + +#endif // Foundation_Process_INCLUDED diff --git a/Foundation/include/Poco/Process_UNIX.h b/Foundation/include/Poco/Process_UNIX.h index 86e514653..3f69fea91 100644 --- a/Foundation/include/Poco/Process_UNIX.h +++ b/Foundation/include/Poco/Process_UNIX.h @@ -1,86 +1,86 @@ -// -// Process_UNIX.h -// -// $Id: //poco/1.2/Foundation/include/Poco/Process_UNIX.h#1 $ -// -// Library: Foundation -// Package: Processes -// Module: Process -// -// Definition of the ProcessImpl class for Unix. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_Process_UNIX_INCLUDED -#define Foundation_Process_UNIX_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/RefCountedObject.h" -#include -#include - - -namespace Poco { - - -class Pipe; - - -class Foundation_API ProcessHandleImpl: public RefCountedObject -{ -public: - ProcessHandleImpl(pid_t pid); - ~ProcessHandleImpl(); - - pid_t id() const; - int wait() const; - -private: - pid_t _pid; -}; - - -class Foundation_API ProcessImpl -{ -public: - typedef pid_t PIDImpl; - typedef std::vector ArgsImpl; - - static PIDImpl idImpl(); - static void timesImpl(long& userTime, long& kernelTime); - static ProcessHandleImpl* launchImpl(const std::string& command, const ArgsImpl& args, Pipe* inPipe, Pipe* outPipe, Pipe* errPipe); - static void killImpl(PIDImpl pid); - static void requestTerminationImpl(PIDImpl pid); -}; - - -} // namespace Poco - - -#endif // Foundation_Process_UNIX_INCLUDED +// +// Process_UNIX.h +// +// $Id: //poco/1.2/Foundation/include/Poco/Process_UNIX.h#1 $ +// +// Library: Foundation +// Package: Processes +// Module: Process +// +// Definition of the ProcessImpl class for Unix. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_Process_UNIX_INCLUDED +#define Foundation_Process_UNIX_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/RefCountedObject.h" +#include +#include + + +namespace Poco { + + +class Pipe; + + +class Foundation_API ProcessHandleImpl: public RefCountedObject +{ +public: + ProcessHandleImpl(pid_t pid); + ~ProcessHandleImpl(); + + pid_t id() const; + int wait() const; + +private: + pid_t _pid; +}; + + +class Foundation_API ProcessImpl +{ +public: + typedef pid_t PIDImpl; + typedef std::vector ArgsImpl; + + static PIDImpl idImpl(); + static void timesImpl(long& userTime, long& kernelTime); + static ProcessHandleImpl* launchImpl(const std::string& command, const ArgsImpl& args, Pipe* inPipe, Pipe* outPipe, Pipe* errPipe); + static void killImpl(PIDImpl pid); + static void requestTerminationImpl(PIDImpl pid); +}; + + +} // namespace Poco + + +#endif // Foundation_Process_UNIX_INCLUDED diff --git a/Foundation/include/Poco/Process_VMS.h b/Foundation/include/Poco/Process_VMS.h index 91c4c09dd..33f97e488 100644 --- a/Foundation/include/Poco/Process_VMS.h +++ b/Foundation/include/Poco/Process_VMS.h @@ -1,87 +1,87 @@ -// -// Process_VMS.h -// -// $Id: //poco/1.2/Foundation/include/Poco/Process_VMS.h#1 $ -// -// Library: Foundation -// Package: Processes -// Module: Process -// -// Definition of the ProcessImpl class for OpenVMS. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_Process_VMS_INCLUDED -#define Foundation_Process_VMS_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/RefCountedObject.h" -#include -#include - - -namespace Poco { - - -class Pipe; - - -class ProcessHandleImpl: public RefCountedObject -{ -public: - ProcessHandleImpl(pid_t pid); - ~ProcessHandleImpl(); - - pid_t id() const; - int wait() const; - -private: - pid_t _pid; -}; - - -class ProcessImpl -{ -public: - typedef pid_t PIDImpl; - typedef std::vector ArgsImpl; - - static PIDImpl idImpl(); - static void timesImpl(long& userTime, long& kernelTime); - static ProcessHandleImpl* launchImpl(const std::string& command, const ArgsImpl& args, Pipe* inPipe, Pipe* outPipe, Pipe* errPipe); - static int waitImpl(PIDImpl pid); - static void killImpl(PIDImpl pid); - static void requestTerminationImpl(PIDImpl pid); -}; - - -} // namespace Poco - - -#endif // Foundation_Process_VMS_INCLUDED +// +// Process_VMS.h +// +// $Id: //poco/1.2/Foundation/include/Poco/Process_VMS.h#1 $ +// +// Library: Foundation +// Package: Processes +// Module: Process +// +// Definition of the ProcessImpl class for OpenVMS. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_Process_VMS_INCLUDED +#define Foundation_Process_VMS_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/RefCountedObject.h" +#include +#include + + +namespace Poco { + + +class Pipe; + + +class ProcessHandleImpl: public RefCountedObject +{ +public: + ProcessHandleImpl(pid_t pid); + ~ProcessHandleImpl(); + + pid_t id() const; + int wait() const; + +private: + pid_t _pid; +}; + + +class ProcessImpl +{ +public: + typedef pid_t PIDImpl; + typedef std::vector ArgsImpl; + + static PIDImpl idImpl(); + static void timesImpl(long& userTime, long& kernelTime); + static ProcessHandleImpl* launchImpl(const std::string& command, const ArgsImpl& args, Pipe* inPipe, Pipe* outPipe, Pipe* errPipe); + static int waitImpl(PIDImpl pid); + static void killImpl(PIDImpl pid); + static void requestTerminationImpl(PIDImpl pid); +}; + + +} // namespace Poco + + +#endif // Foundation_Process_VMS_INCLUDED diff --git a/Foundation/include/Poco/Process_WIN32.h b/Foundation/include/Poco/Process_WIN32.h index 41d455e83..ac0b0561d 100644 --- a/Foundation/include/Poco/Process_WIN32.h +++ b/Foundation/include/Poco/Process_WIN32.h @@ -1,87 +1,87 @@ -// -// Process_WIN32.h -// -// $Id: //poco/1.2/Foundation/include/Poco/Process_WIN32.h#1 $ -// -// Library: Foundation -// Package: Processes -// Module: Process -// -// Definition of the ProcessImpl class for WIN32. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_Process_WIN32_INCLUDED -#define Foundation_Process_WIN32_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/RefCountedObject.h" -#include -#include - - -namespace Poco { - - -class Pipe; - - -class Foundation_API ProcessHandleImpl: public RefCountedObject -{ -public: - ProcessHandleImpl(HANDLE _hProcess, UInt32 pid); - ~ProcessHandleImpl(); - - UInt32 id() const; - int wait() const; - -private: - HANDLE _hProcess; - UInt32 _pid; -}; - - -class Foundation_API ProcessImpl -{ -public: - typedef UInt32 PIDImpl; - typedef std::vector ArgsImpl; - - static PIDImpl idImpl(); - static void timesImpl(long& userTime, long& kernelTime); - static ProcessHandleImpl* launchImpl(const std::string& command, const ArgsImpl& args, Pipe* inPipe, Pipe* outPipe, Pipe* errPipe); - static void killImpl(PIDImpl pid); - static void requestTerminationImpl(PIDImpl pid); -}; - - -} // namespace Poco - - -#endif // Foundation_Process_WIN32_INCLUDED +// +// Process_WIN32.h +// +// $Id: //poco/1.2/Foundation/include/Poco/Process_WIN32.h#1 $ +// +// Library: Foundation +// Package: Processes +// Module: Process +// +// Definition of the ProcessImpl class for WIN32. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_Process_WIN32_INCLUDED +#define Foundation_Process_WIN32_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/RefCountedObject.h" +#include +#include + + +namespace Poco { + + +class Pipe; + + +class Foundation_API ProcessHandleImpl: public RefCountedObject +{ +public: + ProcessHandleImpl(HANDLE _hProcess, UInt32 pid); + ~ProcessHandleImpl(); + + UInt32 id() const; + int wait() const; + +private: + HANDLE _hProcess; + UInt32 _pid; +}; + + +class Foundation_API ProcessImpl +{ +public: + typedef UInt32 PIDImpl; + typedef std::vector ArgsImpl; + + static PIDImpl idImpl(); + static void timesImpl(long& userTime, long& kernelTime); + static ProcessHandleImpl* launchImpl(const std::string& command, const ArgsImpl& args, Pipe* inPipe, Pipe* outPipe, Pipe* errPipe); + static void killImpl(PIDImpl pid); + static void requestTerminationImpl(PIDImpl pid); +}; + + +} // namespace Poco + + +#endif // Foundation_Process_WIN32_INCLUDED diff --git a/Foundation/include/Poco/Process_WIN32U.h b/Foundation/include/Poco/Process_WIN32U.h index 757c89c3d..a2e58d644 100644 --- a/Foundation/include/Poco/Process_WIN32U.h +++ b/Foundation/include/Poco/Process_WIN32U.h @@ -1,87 +1,87 @@ -// -// Process_WIN32U.h -// -// $Id: //poco/1.2/Foundation/include/Poco/Process_WIN32U.h#1 $ -// -// Library: Foundation -// Package: Processes -// Module: Process -// -// Definition of the ProcessImpl class for WIN32. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_Process_WIN32U_INCLUDED -#define Foundation_Process_WIN32U_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/RefCountedObject.h" -#include -#include - - -namespace Poco { - - -class Pipe; - - -class Foundation_API ProcessHandleImpl: public RefCountedObject -{ -public: - ProcessHandleImpl(HANDLE _hProcess, UInt32 pid); - ~ProcessHandleImpl(); - - UInt32 id() const; - int wait() const; - -private: - HANDLE _hProcess; - UInt32 _pid; -}; - - -class Foundation_API ProcessImpl -{ -public: - typedef UInt32 PIDImpl; - typedef std::vector ArgsImpl; - - static PIDImpl idImpl(); - static void timesImpl(long& userTime, long& kernelTime); - static ProcessHandleImpl* launchImpl(const std::string& command, const ArgsImpl& args, Pipe* inPipe, Pipe* outPipe, Pipe* errPipe); - static void killImpl(PIDImpl pid); - static void requestTerminationImpl(PIDImpl pid); -}; - - -} // namespace Poco - - -#endif // Foundation_Process_WIN32U_INCLUDED +// +// Process_WIN32U.h +// +// $Id: //poco/1.2/Foundation/include/Poco/Process_WIN32U.h#1 $ +// +// Library: Foundation +// Package: Processes +// Module: Process +// +// Definition of the ProcessImpl class for WIN32. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_Process_WIN32U_INCLUDED +#define Foundation_Process_WIN32U_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/RefCountedObject.h" +#include +#include + + +namespace Poco { + + +class Pipe; + + +class Foundation_API ProcessHandleImpl: public RefCountedObject +{ +public: + ProcessHandleImpl(HANDLE _hProcess, UInt32 pid); + ~ProcessHandleImpl(); + + UInt32 id() const; + int wait() const; + +private: + HANDLE _hProcess; + UInt32 _pid; +}; + + +class Foundation_API ProcessImpl +{ +public: + typedef UInt32 PIDImpl; + typedef std::vector ArgsImpl; + + static PIDImpl idImpl(); + static void timesImpl(long& userTime, long& kernelTime); + static ProcessHandleImpl* launchImpl(const std::string& command, const ArgsImpl& args, Pipe* inPipe, Pipe* outPipe, Pipe* errPipe); + static void killImpl(PIDImpl pid); + static void requestTerminationImpl(PIDImpl pid); +}; + + +} // namespace Poco + + +#endif // Foundation_Process_WIN32U_INCLUDED diff --git a/Foundation/include/Poco/PurgeStrategy.h b/Foundation/include/Poco/PurgeStrategy.h index 6b0e1dbf6..b2d766cc7 100644 --- a/Foundation/include/Poco/PurgeStrategy.h +++ b/Foundation/include/Poco/PurgeStrategy.h @@ -1,119 +1,119 @@ -// -// PurgeStrategy.h -// -// $Id: //poco/1.2/Foundation/include/Poco/PurgeStrategy.h#1 $ -// -// Library: Foundation -// Package: Logging -// Module: FileChannel -// -// Definition of the PurgeStrategy class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_PurgeStrategy_INCLUDED -#define Foundation_PurgeStrategy_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/File.h" -#include "Poco/Timespan.h" -#include - - -namespace Poco { - - -class Foundation_API PurgeStrategy - /// The PurgeStrategy is used by FileChannel - /// to purge archived log files. -{ -public: - PurgeStrategy(); - virtual ~PurgeStrategy(); - - virtual void purge(const std::string& path) = 0; - /// Purges archived log files. The path to the - /// current "hot" log file is given. - /// To find archived log files, look for files - /// with a name consisting of the given path - /// plus any suffix (e.g., .1, .20050929081500, .1.gz). - /// A list of archived files can be obtained by calling - /// the list() method. - -protected: - void list(const std::string& path, std::vector& files); - /// Fills the given vector with a list of archived log - /// files. The path of the current "hot" log file is - /// given in path. - /// - /// All files with the same name as the one given in path, - /// plus some suffix (e.g., .1, .20050929081500, .1.gz) are - /// considered archived files. - -private: - PurgeStrategy(const PurgeStrategy&); - PurgeStrategy& operator = (const PurgeStrategy&); -}; - - -class Foundation_API PurgeByAgeStrategy: public PurgeStrategy - /// This purge strategy purges all files that have - /// exceeded a given age (given in seconds). -{ -public: - PurgeByAgeStrategy(const Timespan& age); - ~PurgeByAgeStrategy(); - - void purge(const std::string& path); - -private: - Timespan _age; -}; - - -class Foundation_API PurgeByCountStrategy: public PurgeStrategy - /// This purge strategy ensures that a maximum number - /// of archived files is not exceeded. Files are deleted - /// based on their age, with oldest files deleted first. -{ -public: - PurgeByCountStrategy(int count); - ~PurgeByCountStrategy(); - - void purge(const std::string& path); - -private: - int _count; -}; - - -} // namespace Poco - - -#endif // Foundation_PurgeStrategy_INCLUDED +// +// PurgeStrategy.h +// +// $Id: //poco/1.2/Foundation/include/Poco/PurgeStrategy.h#1 $ +// +// Library: Foundation +// Package: Logging +// Module: FileChannel +// +// Definition of the PurgeStrategy class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_PurgeStrategy_INCLUDED +#define Foundation_PurgeStrategy_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/File.h" +#include "Poco/Timespan.h" +#include + + +namespace Poco { + + +class Foundation_API PurgeStrategy + /// The PurgeStrategy is used by FileChannel + /// to purge archived log files. +{ +public: + PurgeStrategy(); + virtual ~PurgeStrategy(); + + virtual void purge(const std::string& path) = 0; + /// Purges archived log files. The path to the + /// current "hot" log file is given. + /// To find archived log files, look for files + /// with a name consisting of the given path + /// plus any suffix (e.g., .1, .20050929081500, .1.gz). + /// A list of archived files can be obtained by calling + /// the list() method. + +protected: + void list(const std::string& path, std::vector& files); + /// Fills the given vector with a list of archived log + /// files. The path of the current "hot" log file is + /// given in path. + /// + /// All files with the same name as the one given in path, + /// plus some suffix (e.g., .1, .20050929081500, .1.gz) are + /// considered archived files. + +private: + PurgeStrategy(const PurgeStrategy&); + PurgeStrategy& operator = (const PurgeStrategy&); +}; + + +class Foundation_API PurgeByAgeStrategy: public PurgeStrategy + /// This purge strategy purges all files that have + /// exceeded a given age (given in seconds). +{ +public: + PurgeByAgeStrategy(const Timespan& age); + ~PurgeByAgeStrategy(); + + void purge(const std::string& path); + +private: + Timespan _age; +}; + + +class Foundation_API PurgeByCountStrategy: public PurgeStrategy + /// This purge strategy ensures that a maximum number + /// of archived files is not exceeded. Files are deleted + /// based on their age, with oldest files deleted first. +{ +public: + PurgeByCountStrategy(int count); + ~PurgeByCountStrategy(); + + void purge(const std::string& path); + +private: + int _count; +}; + + +} // namespace Poco + + +#endif // Foundation_PurgeStrategy_INCLUDED diff --git a/Foundation/include/Poco/RWLock.h b/Foundation/include/Poco/RWLock.h index 4ff91f595..2a128a181 100644 --- a/Foundation/include/Poco/RWLock.h +++ b/Foundation/include/Poco/RWLock.h @@ -1,168 +1,168 @@ -// -// RWLock.h -// -// $Id: //poco/1.2/Foundation/include/Poco/RWLock.h#1 $ -// -// Library: Foundation -// Package: Threading -// Module: RWLock -// -// Definition of the RWLock class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_RWLock_INCLUDED -#define Foundation_RWLock_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/Exception.h" - - -#if defined(POCO_OS_FAMILY_WINDOWS) -#include "Poco/RWLock_WIN32.h" -#else -#include "Poco/RWLock_POSIX.h" -#endif - - -namespace Poco { - - -class ScopedRWLock; - - -class Foundation_API RWLock: private RWLockImpl - /// A reader writer lock allows multiple concurrent - /// readers or one exclusive writer. -{ -public: - typedef ScopedRWLock ScopedLock; - - RWLock(); - /// Creates the Reader/Writer lock. - - ~RWLock(); - /// Destroys the Reader/Writer lock. - - void readLock(); - /// Acquires a read lock. If another thread currently holds a write lock, - /// waits until the write lock is released. - - bool tryReadLock(); - /// Tries to acquire a read lock. Immediately returns true if successful, or - /// false if another thread currently holds a write lock. - - void writeLock(); - /// Acquires a write lock. If one or more other threads currently hold - /// locks, waits until all locks are released. The results are undefined - /// if the same thread already holds a read or write lock - - bool tryWriteLock(); - /// Tries to acquire a write lock. Immediately returns true if successful, - /// or false if one or more other threads currently hold - /// locks. The result is undefined if the same thread already - /// holds a read or write lock. - - void unlock(); - /// Releases the read or write lock. - -private: - RWLock(const RWLock&); - RWLock& operator = (const RWLock&); -}; - - -class Foundation_API ScopedRWLock - /// A variant of ScopedLock for reader/writer locks. -{ -public: - ScopedRWLock(RWLock& rwl, bool write = false); - ~ScopedRWLock(); - -private: - RWLock& _rwl; - - ScopedRWLock(); - ScopedRWLock(const ScopedRWLock&); - ScopedRWLock& operator = (const ScopedRWLock&); -}; - - -// -// inlines -// -inline void RWLock::readLock() -{ - readLockImpl(); -} - - -inline bool RWLock::tryReadLock() -{ - return tryReadLockImpl(); -} - - -inline void RWLock::writeLock() -{ - writeLockImpl(); -} - - -inline bool RWLock::tryWriteLock() -{ - return tryWriteLockImpl(); -} - - -inline void RWLock::unlock() -{ - unlockImpl(); -} - - -inline ScopedRWLock::ScopedRWLock(RWLock& rwl, bool write): _rwl(rwl) -{ - if (write) - _rwl.writeLock(); - else - _rwl.readLock(); -} - - -inline ScopedRWLock::~ScopedRWLock() -{ - _rwl.unlock(); -} - - -} // namespace Poco - - -#endif // Foundation_RWLock_INCLUDED +// +// RWLock.h +// +// $Id: //poco/1.2/Foundation/include/Poco/RWLock.h#1 $ +// +// Library: Foundation +// Package: Threading +// Module: RWLock +// +// Definition of the RWLock class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_RWLock_INCLUDED +#define Foundation_RWLock_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Exception.h" + + +#if defined(POCO_OS_FAMILY_WINDOWS) +#include "Poco/RWLock_WIN32.h" +#else +#include "Poco/RWLock_POSIX.h" +#endif + + +namespace Poco { + + +class ScopedRWLock; + + +class Foundation_API RWLock: private RWLockImpl + /// A reader writer lock allows multiple concurrent + /// readers or one exclusive writer. +{ +public: + typedef ScopedRWLock ScopedLock; + + RWLock(); + /// Creates the Reader/Writer lock. + + ~RWLock(); + /// Destroys the Reader/Writer lock. + + void readLock(); + /// Acquires a read lock. If another thread currently holds a write lock, + /// waits until the write lock is released. + + bool tryReadLock(); + /// Tries to acquire a read lock. Immediately returns true if successful, or + /// false if another thread currently holds a write lock. + + void writeLock(); + /// Acquires a write lock. If one or more other threads currently hold + /// locks, waits until all locks are released. The results are undefined + /// if the same thread already holds a read or write lock + + bool tryWriteLock(); + /// Tries to acquire a write lock. Immediately returns true if successful, + /// or false if one or more other threads currently hold + /// locks. The result is undefined if the same thread already + /// holds a read or write lock. + + void unlock(); + /// Releases the read or write lock. + +private: + RWLock(const RWLock&); + RWLock& operator = (const RWLock&); +}; + + +class Foundation_API ScopedRWLock + /// A variant of ScopedLock for reader/writer locks. +{ +public: + ScopedRWLock(RWLock& rwl, bool write = false); + ~ScopedRWLock(); + +private: + RWLock& _rwl; + + ScopedRWLock(); + ScopedRWLock(const ScopedRWLock&); + ScopedRWLock& operator = (const ScopedRWLock&); +}; + + +// +// inlines +// +inline void RWLock::readLock() +{ + readLockImpl(); +} + + +inline bool RWLock::tryReadLock() +{ + return tryReadLockImpl(); +} + + +inline void RWLock::writeLock() +{ + writeLockImpl(); +} + + +inline bool RWLock::tryWriteLock() +{ + return tryWriteLockImpl(); +} + + +inline void RWLock::unlock() +{ + unlockImpl(); +} + + +inline ScopedRWLock::ScopedRWLock(RWLock& rwl, bool write): _rwl(rwl) +{ + if (write) + _rwl.writeLock(); + else + _rwl.readLock(); +} + + +inline ScopedRWLock::~ScopedRWLock() +{ + _rwl.unlock(); +} + + +} // namespace Poco + + +#endif // Foundation_RWLock_INCLUDED diff --git a/Foundation/include/Poco/RWLock_POSIX.h b/Foundation/include/Poco/RWLock_POSIX.h index 63593d7c2..b46ab2026 100644 --- a/Foundation/include/Poco/RWLock_POSIX.h +++ b/Foundation/include/Poco/RWLock_POSIX.h @@ -1,121 +1,121 @@ -// -// RWLock_POSIX.h -// -// $Id: //poco/1.2/Foundation/include/Poco/RWLock_POSIX.h#1 $ -// -// Library: Foundation -// Package: Threading -// Module: RWLock -// -// Definition of the RWLockImpl class for POSIX Threads. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_RWLock_POSIX_INCLUDED -#define Foundation_RWLock_POSIX_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/Exception.h" -#include -#include - - -namespace Poco { - - -class Foundation_API RWLockImpl -{ -protected: - RWLockImpl(); - ~RWLockImpl(); - void readLockImpl(); - bool tryReadLockImpl(); - void writeLockImpl(); - bool tryWriteLockImpl(); - void unlockImpl(); - -private: - pthread_rwlock_t _rwl; -}; - - -// -// inlines -// -inline void RWLockImpl::readLockImpl() -{ - if (pthread_rwlock_rdlock(&_rwl)) - throw SystemException("cannot lock reader/writer lock"); -} - - -inline bool RWLockImpl::tryReadLockImpl() -{ - int rc = pthread_rwlock_tryrdlock(&_rwl); - if (rc == 0) - return true; - else if (rc == EBUSY) - return false; - else - throw SystemException("cannot lock reader/writer lock"); - -} - - -inline void RWLockImpl::writeLockImpl() -{ - if (pthread_rwlock_wrlock(&_rwl)) - throw SystemException("cannot lock reader/writer lock"); -} - - -inline bool RWLockImpl::tryWriteLockImpl() -{ - int rc = pthread_rwlock_trywrlock(&_rwl); - if (rc == 0) - return true; - else if (rc == EBUSY) - return false; - else - throw SystemException("cannot lock reader/writer lock"); - -} - - -inline void RWLockImpl::unlockImpl() -{ - if (pthread_rwlock_unlock(&_rwl)) - throw SystemException("cannot unlock mutex"); -} - - -} // namespace Poco - - -#endif // Foundation_RWLock_POSIX_INCLUDED +// +// RWLock_POSIX.h +// +// $Id: //poco/1.2/Foundation/include/Poco/RWLock_POSIX.h#1 $ +// +// Library: Foundation +// Package: Threading +// Module: RWLock +// +// Definition of the RWLockImpl class for POSIX Threads. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_RWLock_POSIX_INCLUDED +#define Foundation_RWLock_POSIX_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Exception.h" +#include +#include + + +namespace Poco { + + +class Foundation_API RWLockImpl +{ +protected: + RWLockImpl(); + ~RWLockImpl(); + void readLockImpl(); + bool tryReadLockImpl(); + void writeLockImpl(); + bool tryWriteLockImpl(); + void unlockImpl(); + +private: + pthread_rwlock_t _rwl; +}; + + +// +// inlines +// +inline void RWLockImpl::readLockImpl() +{ + if (pthread_rwlock_rdlock(&_rwl)) + throw SystemException("cannot lock reader/writer lock"); +} + + +inline bool RWLockImpl::tryReadLockImpl() +{ + int rc = pthread_rwlock_tryrdlock(&_rwl); + if (rc == 0) + return true; + else if (rc == EBUSY) + return false; + else + throw SystemException("cannot lock reader/writer lock"); + +} + + +inline void RWLockImpl::writeLockImpl() +{ + if (pthread_rwlock_wrlock(&_rwl)) + throw SystemException("cannot lock reader/writer lock"); +} + + +inline bool RWLockImpl::tryWriteLockImpl() +{ + int rc = pthread_rwlock_trywrlock(&_rwl); + if (rc == 0) + return true; + else if (rc == EBUSY) + return false; + else + throw SystemException("cannot lock reader/writer lock"); + +} + + +inline void RWLockImpl::unlockImpl() +{ + if (pthread_rwlock_unlock(&_rwl)) + throw SystemException("cannot unlock mutex"); +} + + +} // namespace Poco + + +#endif // Foundation_RWLock_POSIX_INCLUDED diff --git a/Foundation/include/Poco/RWLock_WIN32.h b/Foundation/include/Poco/RWLock_WIN32.h index dc53aab0b..83bfef6f0 100644 --- a/Foundation/include/Poco/RWLock_WIN32.h +++ b/Foundation/include/Poco/RWLock_WIN32.h @@ -1,77 +1,77 @@ -// -// RWLock_WIN32.h -// -// $Id: //poco/1.2/Foundation/include/Poco/RWLock_WIN32.h#1 $ -// -// Library: Foundation -// Package: Threading -// Module: RWLock -// -// Definition of the RWLockImpl class for WIN32. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_RWLock_WIN32_INCLUDED -#define Foundation_RWLock_WIN32_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/Exception.h" -#include - - -namespace Poco { - - -class Foundation_API RWLockImpl -{ -protected: - RWLockImpl(); - ~RWLockImpl(); - void readLockImpl(); - bool tryReadLockImpl(); - void writeLockImpl(); - bool tryWriteLockImpl(); - void unlockImpl(); - -private: - void addWriter(); - void removeWriter(); - - HANDLE _mutex; - HANDLE _readEvent; - HANDLE _writeEvent; - unsigned _readers; - unsigned _writers; -}; - - -} // namespace Poco - - -#endif // Foundation_RWLock_WIN32_INCLUDED +// +// RWLock_WIN32.h +// +// $Id: //poco/1.2/Foundation/include/Poco/RWLock_WIN32.h#1 $ +// +// Library: Foundation +// Package: Threading +// Module: RWLock +// +// Definition of the RWLockImpl class for WIN32. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_RWLock_WIN32_INCLUDED +#define Foundation_RWLock_WIN32_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Exception.h" +#include + + +namespace Poco { + + +class Foundation_API RWLockImpl +{ +protected: + RWLockImpl(); + ~RWLockImpl(); + void readLockImpl(); + bool tryReadLockImpl(); + void writeLockImpl(); + bool tryWriteLockImpl(); + void unlockImpl(); + +private: + void addWriter(); + void removeWriter(); + + HANDLE _mutex; + HANDLE _readEvent; + HANDLE _writeEvent; + unsigned _readers; + unsigned _writers; +}; + + +} // namespace Poco + + +#endif // Foundation_RWLock_WIN32_INCLUDED diff --git a/Foundation/include/Poco/Random.h b/Foundation/include/Poco/Random.h index ded3e79e9..d16cbf440 100644 --- a/Foundation/include/Poco/Random.h +++ b/Foundation/include/Poco/Random.h @@ -1,191 +1,191 @@ -// -// Random.h -// -// $Id: //poco/1.2/Foundation/include/Poco/Random.h#1 $ -// -// Library: Foundation -// Package: Crypt -// Module: Random -// -// Definition of class Random. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// -// -// Based on the FreeBSD random number generator. -// src/lib/libc/stdlib/random.c,v 1.13 2000/01/27 23:06:49 jasone Exp -// -// Copyright (c) 1983, 1993 -// The Regents of the University of California. 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. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by the University of -// California, Berkeley and its contributors. -// 4. Neither the name of the University nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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 Foundation_Random_INCLUDED -#define Foundation_Random_INCLUDED - - -#include "Poco/Foundation.h" - - -namespace Poco { - - -class Foundation_API Random - /// A better random number generator. - /// Random implements a pseudo random number generator - /// (PRNG). The PRNG is a nonlinear additive - /// feedback random number generator using 256 bytes - /// of state information and a period of up to 2^69. -{ -public: - enum Type - { - RND_STATE_0 = 8, /// linear congruential - RND_STATE_32 = 32, /// x**7 + x**3 + 1 - RND_STATE_64 = 64, /// x**15 + x + 1 - RND_STATE_128 = 128, /// x**31 + x**3 + 1 - RND_STATE_256 = 256 /// x**63 + x + 1 - }; - - Random(int stateSize = 256); - /// Creates and initializes the PRNG. - /// Specify either a state buffer size - /// (8 to 256 bytes) or one of the Type values. - - ~Random(); - /// Destroys the PRNG. - - void seed(UInt32 seed); - /// Seeds the pseudo random generator with the given seed. - - void seed(); - /// Seeds the pseudo random generator with a random seed - /// obtained from a RandomInputStream. - - UInt32 next(); - /// Returns the next 31-bit pseudo random number. - - UInt32 next(UInt32 n); - /// Returns the next 31-bit pseudo random number modulo n. - - char nextChar(); - /// Returns the next pseudo random character. - - bool nextBool(); - /// Returns the next boolean pseudo random value. - - float nextFloat(); - /// Returns the next float pseudo random number between 0.0 and 1.0. - - double nextDouble(); - /// Returns the next double pseudo random number between 0.0 and 1.0. - -protected: - void initState(UInt32 seed, char* arg_state, Int32 n); - static UInt32 goodRand(Int32 x); - -private: - enum - { - MAX_TYPES = 5, - NSHUFF = 50 - }; - - UInt32* _fptr; - UInt32* _rptr; - UInt32* _state; - int _randType; - int _randDeg; - int _randSep; - UInt32* _endPtr; - char* _pBuffer; -}; - - -// -// inlines -// -inline UInt32 Random::next(UInt32 n) -{ - return next() % n; -} - - -inline char Random::nextChar() -{ - return char((next() >> 3) & 0xFF); -} - - -inline bool Random::nextBool() -{ - return (next() & 0x1000) != 0; -} - - -inline float Random::nextFloat() -{ - return float(next()) / 0x7FFFFFFF; -} - - -inline double Random::nextDouble() -{ - return double(next()) / 0x7FFFFFFF; -} - - -} // namespace Poco - - -#endif // Foundation_Random_INCLUDED +// +// Random.h +// +// $Id: //poco/1.2/Foundation/include/Poco/Random.h#1 $ +// +// Library: Foundation +// Package: Crypt +// Module: Random +// +// Definition of class Random. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// +// +// Based on the FreeBSD random number generator. +// src/lib/libc/stdlib/random.c,v 1.13 2000/01/27 23:06:49 jasone Exp +// +// Copyright (c) 1983, 1993 +// The Regents of the University of California. 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. +// 3. All advertising materials mentioning features or use of this software +// must display the following acknowledgement: +// This product includes software developed by the University of +// California, Berkeley and its contributors. +// 4. Neither the name of the University nor the names of its contributors +// may be used to endorse or promote products derived from this software +// without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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 Foundation_Random_INCLUDED +#define Foundation_Random_INCLUDED + + +#include "Poco/Foundation.h" + + +namespace Poco { + + +class Foundation_API Random + /// A better random number generator. + /// Random implements a pseudo random number generator + /// (PRNG). The PRNG is a nonlinear additive + /// feedback random number generator using 256 bytes + /// of state information and a period of up to 2^69. +{ +public: + enum Type + { + RND_STATE_0 = 8, /// linear congruential + RND_STATE_32 = 32, /// x**7 + x**3 + 1 + RND_STATE_64 = 64, /// x**15 + x + 1 + RND_STATE_128 = 128, /// x**31 + x**3 + 1 + RND_STATE_256 = 256 /// x**63 + x + 1 + }; + + Random(int stateSize = 256); + /// Creates and initializes the PRNG. + /// Specify either a state buffer size + /// (8 to 256 bytes) or one of the Type values. + + ~Random(); + /// Destroys the PRNG. + + void seed(UInt32 seed); + /// Seeds the pseudo random generator with the given seed. + + void seed(); + /// Seeds the pseudo random generator with a random seed + /// obtained from a RandomInputStream. + + UInt32 next(); + /// Returns the next 31-bit pseudo random number. + + UInt32 next(UInt32 n); + /// Returns the next 31-bit pseudo random number modulo n. + + char nextChar(); + /// Returns the next pseudo random character. + + bool nextBool(); + /// Returns the next boolean pseudo random value. + + float nextFloat(); + /// Returns the next float pseudo random number between 0.0 and 1.0. + + double nextDouble(); + /// Returns the next double pseudo random number between 0.0 and 1.0. + +protected: + void initState(UInt32 seed, char* arg_state, Int32 n); + static UInt32 goodRand(Int32 x); + +private: + enum + { + MAX_TYPES = 5, + NSHUFF = 50 + }; + + UInt32* _fptr; + UInt32* _rptr; + UInt32* _state; + int _randType; + int _randDeg; + int _randSep; + UInt32* _endPtr; + char* _pBuffer; +}; + + +// +// inlines +// +inline UInt32 Random::next(UInt32 n) +{ + return next() % n; +} + + +inline char Random::nextChar() +{ + return char((next() >> 3) & 0xFF); +} + + +inline bool Random::nextBool() +{ + return (next() & 0x1000) != 0; +} + + +inline float Random::nextFloat() +{ + return float(next()) / 0x7FFFFFFF; +} + + +inline double Random::nextDouble() +{ + return double(next()) / 0x7FFFFFFF; +} + + +} // namespace Poco + + +#endif // Foundation_Random_INCLUDED diff --git a/Foundation/include/Poco/RandomStream.h b/Foundation/include/Poco/RandomStream.h index e9651e094..6dc0d0ad1 100644 --- a/Foundation/include/Poco/RandomStream.h +++ b/Foundation/include/Poco/RandomStream.h @@ -1,95 +1,95 @@ -// -// RandomStream.h -// -// $Id: //poco/1.2/Foundation/include/Poco/RandomStream.h#1 $ -// -// Library: Foundation -// Package: Crypt -// Module: RandomStream -// -// Definition of class RandomInputStream. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_RandomStream_INCLUDED -#define Foundation_RandomStream_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/BufferedStreamBuf.h" -#include - - -namespace Poco { - - -class Foundation_API RandomBuf: public BufferedStreamBuf - /// This streambuf generates random data. - /// On Windows NT, the cryptographic API is used. - /// On Unix, /dev/random is used, if available. - /// Otherwise, a random number generator, some - /// more-or-less random data and a SHA-1 digest - /// is used to generate random data. -{ -public: - RandomBuf(); - ~RandomBuf(); - int readFromDevice(char* buffer, std::streamsize length); -}; - - -class Foundation_API RandomIOS: public virtual std::ios - /// The base class for RandomInputStream. - /// - /// This class is needed to ensure the correct initialization - /// order of the stream buffer and base classes. -{ -public: - RandomIOS(); - ~RandomIOS(); - RandomBuf* rdbuf(); - -protected: - RandomBuf _buf; -}; - - -class Foundation_API RandomInputStream: public RandomIOS, public std::istream - /// This istream generates random data - /// using the RandomBuf. -{ -public: - RandomInputStream(); - ~RandomInputStream(); -}; - - -} // namespace Poco - - -#endif // Foundation_RandomStream_INCLUDED +// +// RandomStream.h +// +// $Id: //poco/1.2/Foundation/include/Poco/RandomStream.h#1 $ +// +// Library: Foundation +// Package: Crypt +// Module: RandomStream +// +// Definition of class RandomInputStream. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_RandomStream_INCLUDED +#define Foundation_RandomStream_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/BufferedStreamBuf.h" +#include + + +namespace Poco { + + +class Foundation_API RandomBuf: public BufferedStreamBuf + /// This streambuf generates random data. + /// On Windows NT, the cryptographic API is used. + /// On Unix, /dev/random is used, if available. + /// Otherwise, a random number generator, some + /// more-or-less random data and a SHA-1 digest + /// is used to generate random data. +{ +public: + RandomBuf(); + ~RandomBuf(); + int readFromDevice(char* buffer, std::streamsize length); +}; + + +class Foundation_API RandomIOS: public virtual std::ios + /// The base class for RandomInputStream. + /// + /// This class is needed to ensure the correct initialization + /// order of the stream buffer and base classes. +{ +public: + RandomIOS(); + ~RandomIOS(); + RandomBuf* rdbuf(); + +protected: + RandomBuf _buf; +}; + + +class Foundation_API RandomInputStream: public RandomIOS, public std::istream + /// This istream generates random data + /// using the RandomBuf. +{ +public: + RandomInputStream(); + ~RandomInputStream(); +}; + + +} // namespace Poco + + +#endif // Foundation_RandomStream_INCLUDED diff --git a/Foundation/include/Poco/RefCountedObject.h b/Foundation/include/Poco/RefCountedObject.h index 5d610213d..19efd5656 100644 --- a/Foundation/include/Poco/RefCountedObject.h +++ b/Foundation/include/Poco/RefCountedObject.h @@ -1,98 +1,98 @@ -// -// RefCountedObject.h -// -// $Id: //poco/1.2/Foundation/include/Poco/RefCountedObject.h#1 $ -// -// Library: Foundation -// Package: Core -// Module: RefCountedObject -// -// Definition of the RefCountedObject class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_RefCountedObject_INCLUDED -#define Foundation_RefCountedObject_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/Mutex.h" - - -namespace Poco { - - -class Foundation_API RefCountedObject - /// A base class for objects that employ - /// reference counting based garbage collection. - /// - /// Reference-counted objects inhibit construction - /// by copying and assignment. -{ -public: - RefCountedObject(); - /// Creates the RefCountedObject. - /// The initial reference count is one. - - void duplicate() const; - /// Increments the object's reference count. - - void release() const; - /// Decrements the object's reference count - /// and deletes the object if the count - /// reaches zero. - - int referenceCount() const; - /// Returns the reference count. - -protected: - virtual ~RefCountedObject(); - /// Destroys the RefCountedObject. - -private: - RefCountedObject(const RefCountedObject&); - RefCountedObject& operator = (const RefCountedObject&); - - mutable int _rc; - mutable FastMutex _rcMutex; -}; - - -// -// inlines -// -inline int RefCountedObject::referenceCount() const -{ - return _rc; -} - - -} // namespace Poco - - -#endif // Foundation_RefCountedObject_INCLUDED +// +// RefCountedObject.h +// +// $Id: //poco/1.2/Foundation/include/Poco/RefCountedObject.h#1 $ +// +// Library: Foundation +// Package: Core +// Module: RefCountedObject +// +// Definition of the RefCountedObject class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_RefCountedObject_INCLUDED +#define Foundation_RefCountedObject_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Mutex.h" + + +namespace Poco { + + +class Foundation_API RefCountedObject + /// A base class for objects that employ + /// reference counting based garbage collection. + /// + /// Reference-counted objects inhibit construction + /// by copying and assignment. +{ +public: + RefCountedObject(); + /// Creates the RefCountedObject. + /// The initial reference count is one. + + void duplicate() const; + /// Increments the object's reference count. + + void release() const; + /// Decrements the object's reference count + /// and deletes the object if the count + /// reaches zero. + + int referenceCount() const; + /// Returns the reference count. + +protected: + virtual ~RefCountedObject(); + /// Destroys the RefCountedObject. + +private: + RefCountedObject(const RefCountedObject&); + RefCountedObject& operator = (const RefCountedObject&); + + mutable int _rc; + mutable FastMutex _rcMutex; +}; + + +// +// inlines +// +inline int RefCountedObject::referenceCount() const +{ + return _rc; +} + + +} // namespace Poco + + +#endif // Foundation_RefCountedObject_INCLUDED diff --git a/Foundation/include/Poco/RegularExpression.h b/Foundation/include/Poco/RegularExpression.h index a13ce7aa5..246056789 100644 --- a/Foundation/include/Poco/RegularExpression.h +++ b/Foundation/include/Poco/RegularExpression.h @@ -1,232 +1,232 @@ -// -// RegularExpression.h -// -// $Id: //poco/1.2/Foundation/include/Poco/RegularExpression.h#1 $ -// -// Library: Foundation -// Package: RegExp -// Module: RegularExpression -// -// Definitions of class RegularExpression. -// -// A wrapper class for Philip Hazel's PCRE - Perl Compatible Regular Expressions -// library (http://www.pcre.org). -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_RegularExpression_INCLUDED -#define Foundation_RegularExpression_INCLUDED - - -#include "Poco/Foundation.h" -#include - - -// -// Copy these definitions from pcre.h -// to avoid pulling in the entire header file -// -extern "C" -{ - struct real_pcre; - typedef struct real_pcre pcre; - struct pcre_extra; -} - - -namespace Poco { - - -class Foundation_API RegularExpression - /// A class for working with regular expressions. - /// Implemented using PCRE, the Perl Compatible - /// Regular Expressions library by Philip Hazel - /// (see http://www.pcre.org). - /// - /// An overload of operator ^ is provided for - /// simple matching. -{ -public: - enum Options // These must match the corresponsing options in pcre.h! - /// See the PCRE documentation for more information. - { - RE_CASELESS = 0x00001, /// case insensitive matching (/i) - RE_MULTILINE = 0x00002, /// enable multi-line mode; affects ^ and $ (/m) - RE_DOTALL = 0x00004, /// dot matches all characters, including newline (/s) - RE_EXTENDED = 0x00004, /// totally ignore whitespace (/x) - RE_ANCHORED = 0x00010, /// treat pattern as if it starts with a ^ - RE_DOLLAR_ENDONLY = 0x00020, /// dollar matches end-of-string only, not last newline in string - RE_EXTRA = 0x00040, /// enable optional PCRE functionality - RE_NOTBOL = 0x00080, /// circumflex does not match beginning of string - RE_NOTEOL = 0x00100, /// $ does not match end of string - RE_UNGREEDY = 0x00200, /// make quantifiers ungreedy - RE_NOTEMPTY = 0x00400, /// empty string never matches - RE_UTF8 = 0x00800, /// assume pattern and subject is UTF-8 encoded - RE_NO_AUTO_CAPTURE = 0x01000, /// disable numbered capturing parentheses - RE_NO_UTF8_CHECK = 0x02000, /// do not check validity of UTF-8 code sequences - RE_GLOBAL = 0x10000, /// replace all occurences (/g) - RE_NO_VARS = 0x20000 /// treat dollar in replacement string as ordinary character - }; - - struct Match - { - std::string::size_type offset; /// zero based offset (std::string::npos if subexpr does not match) - std::string::size_type length; /// length of substring - }; - typedef std::vector MatchVec; - - RegularExpression(const std::string& pattern, int options = 0, bool study = true); - /// Creates a regular expression and parses the given pattern. - /// If study is true, the pattern is analyzed and optimized. This - /// is mainly useful if the pattern is used more than once. - /// For a description of the options, please see the PCRE documentation. - /// Throws a RegularExpressionException if the patter cannot be compiled. - - ~RegularExpression(); - /// Destroys the regular expression. - - int match(const std::string& subject, Match& mtch, int options = 0) const; - /// Matches the given subject string against the pattern. Returns the position - /// of the first captured substring in mtch. - /// If no part of the subject matches the pattern, mtch.offset is std::string::npos and - /// mtch.length is 0. - /// Throws a RegularExpressionException in case of an error. - /// Returns the number of matches. - - int match(const std::string& subject, std::string::size_type offset, Match& mtch, int options = 0) const; - /// Matches the given subject string, starting at offset, against the pattern. - /// Returns the position of the captured substring in mtch. - /// If no part of the subject matches the pattern, mtch.offset is std::string::npos and - /// mtch.length is 0. - /// Throws a RegularExpressionException in case of an error. - /// Returns the number of matches. - - int match(const std::string& subject, std::string::size_type offset, MatchVec& matches, int options = 0) const; - /// Matches the given subject string against the pattern. - /// The first entry in matches contains the position of the captured substring. - /// The following entries identify matching subpatterns. See the PCRE documentation - /// for a more detailed explanation. - /// If no part of the subject matches the pattern, matches is empty. - /// Throws a RegularExpressionException in case of an error. - /// Returns the number of matches. - - bool match(const std::string& subject, std::string::size_type offset = 0) const; - /// Returns true if and only if the subject matches the regular expression. - - int extract(const std::string& subject, std::string& str, int options = 0) const; - /// Matches the given subject string against the pattern. - /// Returns the captured string. - /// Throws a RegularExpressionException in case of an error. - /// Returns the number of matches. - - int extract(const std::string& subject, std::string::size_type offset, std::string& str, int options = 0) const; - /// Matches the given subject string, starting at offset, against the pattern. - /// Returns the captured string. - /// Throws a RegularExpressionException in case of an error. - /// Returns the number of matches. - - int split(const std::string& subject, std::vector& strings, int options = 0) const; - /// Matches the given subject string against the pattern. - /// The first entry in captured is the captured substring. - /// The following entries contain substrings matching subpatterns. See the PCRE documentation - /// for a more detailed explanation. - /// If no part of the subject matches the pattern, captured is empty. - /// Throws a RegularExpressionException in case of an error. - /// Returns the number of matches. - - int split(const std::string& subject, std::string::size_type offset, std::vector& strings, int options = 0) const; - /// Matches the given subject string against the pattern. - /// The first entry in captured is the captured substring. - /// The following entries contain substrings matching subpatterns. See the PCRE documentation - /// for a more detailed explanation. - /// If no part of the subject matches the pattern, captured is empty. - /// Throws a RegularExpressionException in case of an error. - /// Returns the number of matches. - - int subst(std::string& subject, const std::string& replacement, int options = 0) const; - /// Substitute in subject all matches of the pattern with replacement. - /// If RE_GLOBAL is specified as option, all matches are replaced. Otherwise, - /// only the first match is replaced. - /// Occurences of $ (for example, $1, $2, ...) in replacement are replaced - /// with the corresponding captured string. $0 is the original subject string. - /// Returns the number of replaced occurences. - - int subst(std::string& subject, std::string::size_type offset, const std::string& replacement, int options = 0) const; - /// Substitute in subject all matches of the pattern with replacement, - /// starting at offset. - /// If RE_GLOBAL is specified as option, all matches are replaced. Otherwise, - /// only the first match is replaced. - /// Unless RE_NO_VARS is specified, occurences of $ (for example, $0, $1, $2, ... $9) - /// in replacement are replaced with the corresponding captured string. - /// $0 is the captured substring. $1 ... $n are the substrings maching the subpatterns. - /// Returns the number of replaced occurences. - - static bool match(const std::string& subject, const std::string& pattern, int options = 0); - /// Matches the given subject string against the regular expression given in pattern, - /// using the given options. - -protected: - std::string::size_type substOne(std::string& subject, std::string::size_type offset, const std::string& replacement, int options) const; - -private: - pcre* _pcre; - pcre_extra* _extra; - - static const int OVEC_SIZE; - - RegularExpression(); - RegularExpression(const RegularExpression&); - RegularExpression& operator = (const RegularExpression&); -}; - - -// -// inlines -// -inline int RegularExpression::match(const std::string& subject, Match& mtch, int options) const -{ - return match(subject, 0, mtch, options); -} - - -inline int RegularExpression::split(const std::string& subject, std::vector& strings, int options) const -{ - return split(subject, 0, strings, options); -} - - -inline int RegularExpression::subst(std::string& subject, const std::string& replacement, int options) const -{ - return subst(subject, 0, replacement, options); -} - - -} // namespace Poco - - -#endif // Foundation_RegularExpression_INCLUDED +// +// RegularExpression.h +// +// $Id: //poco/1.2/Foundation/include/Poco/RegularExpression.h#1 $ +// +// Library: Foundation +// Package: RegExp +// Module: RegularExpression +// +// Definitions of class RegularExpression. +// +// A wrapper class for Philip Hazel's PCRE - Perl Compatible Regular Expressions +// library (http://www.pcre.org). +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_RegularExpression_INCLUDED +#define Foundation_RegularExpression_INCLUDED + + +#include "Poco/Foundation.h" +#include + + +// +// Copy these definitions from pcre.h +// to avoid pulling in the entire header file +// +extern "C" +{ + struct real_pcre; + typedef struct real_pcre pcre; + struct pcre_extra; +} + + +namespace Poco { + + +class Foundation_API RegularExpression + /// A class for working with regular expressions. + /// Implemented using PCRE, the Perl Compatible + /// Regular Expressions library by Philip Hazel + /// (see http://www.pcre.org). + /// + /// An overload of operator ^ is provided for + /// simple matching. +{ +public: + enum Options // These must match the corresponsing options in pcre.h! + /// See the PCRE documentation for more information. + { + RE_CASELESS = 0x00001, /// case insensitive matching (/i) + RE_MULTILINE = 0x00002, /// enable multi-line mode; affects ^ and $ (/m) + RE_DOTALL = 0x00004, /// dot matches all characters, including newline (/s) + RE_EXTENDED = 0x00004, /// totally ignore whitespace (/x) + RE_ANCHORED = 0x00010, /// treat pattern as if it starts with a ^ + RE_DOLLAR_ENDONLY = 0x00020, /// dollar matches end-of-string only, not last newline in string + RE_EXTRA = 0x00040, /// enable optional PCRE functionality + RE_NOTBOL = 0x00080, /// circumflex does not match beginning of string + RE_NOTEOL = 0x00100, /// $ does not match end of string + RE_UNGREEDY = 0x00200, /// make quantifiers ungreedy + RE_NOTEMPTY = 0x00400, /// empty string never matches + RE_UTF8 = 0x00800, /// assume pattern and subject is UTF-8 encoded + RE_NO_AUTO_CAPTURE = 0x01000, /// disable numbered capturing parentheses + RE_NO_UTF8_CHECK = 0x02000, /// do not check validity of UTF-8 code sequences + RE_GLOBAL = 0x10000, /// replace all occurences (/g) + RE_NO_VARS = 0x20000 /// treat dollar in replacement string as ordinary character + }; + + struct Match + { + std::string::size_type offset; /// zero based offset (std::string::npos if subexpr does not match) + std::string::size_type length; /// length of substring + }; + typedef std::vector MatchVec; + + RegularExpression(const std::string& pattern, int options = 0, bool study = true); + /// Creates a regular expression and parses the given pattern. + /// If study is true, the pattern is analyzed and optimized. This + /// is mainly useful if the pattern is used more than once. + /// For a description of the options, please see the PCRE documentation. + /// Throws a RegularExpressionException if the patter cannot be compiled. + + ~RegularExpression(); + /// Destroys the regular expression. + + int match(const std::string& subject, Match& mtch, int options = 0) const; + /// Matches the given subject string against the pattern. Returns the position + /// of the first captured substring in mtch. + /// If no part of the subject matches the pattern, mtch.offset is std::string::npos and + /// mtch.length is 0. + /// Throws a RegularExpressionException in case of an error. + /// Returns the number of matches. + + int match(const std::string& subject, std::string::size_type offset, Match& mtch, int options = 0) const; + /// Matches the given subject string, starting at offset, against the pattern. + /// Returns the position of the captured substring in mtch. + /// If no part of the subject matches the pattern, mtch.offset is std::string::npos and + /// mtch.length is 0. + /// Throws a RegularExpressionException in case of an error. + /// Returns the number of matches. + + int match(const std::string& subject, std::string::size_type offset, MatchVec& matches, int options = 0) const; + /// Matches the given subject string against the pattern. + /// The first entry in matches contains the position of the captured substring. + /// The following entries identify matching subpatterns. See the PCRE documentation + /// for a more detailed explanation. + /// If no part of the subject matches the pattern, matches is empty. + /// Throws a RegularExpressionException in case of an error. + /// Returns the number of matches. + + bool match(const std::string& subject, std::string::size_type offset = 0) const; + /// Returns true if and only if the subject matches the regular expression. + + int extract(const std::string& subject, std::string& str, int options = 0) const; + /// Matches the given subject string against the pattern. + /// Returns the captured string. + /// Throws a RegularExpressionException in case of an error. + /// Returns the number of matches. + + int extract(const std::string& subject, std::string::size_type offset, std::string& str, int options = 0) const; + /// Matches the given subject string, starting at offset, against the pattern. + /// Returns the captured string. + /// Throws a RegularExpressionException in case of an error. + /// Returns the number of matches. + + int split(const std::string& subject, std::vector& strings, int options = 0) const; + /// Matches the given subject string against the pattern. + /// The first entry in captured is the captured substring. + /// The following entries contain substrings matching subpatterns. See the PCRE documentation + /// for a more detailed explanation. + /// If no part of the subject matches the pattern, captured is empty. + /// Throws a RegularExpressionException in case of an error. + /// Returns the number of matches. + + int split(const std::string& subject, std::string::size_type offset, std::vector& strings, int options = 0) const; + /// Matches the given subject string against the pattern. + /// The first entry in captured is the captured substring. + /// The following entries contain substrings matching subpatterns. See the PCRE documentation + /// for a more detailed explanation. + /// If no part of the subject matches the pattern, captured is empty. + /// Throws a RegularExpressionException in case of an error. + /// Returns the number of matches. + + int subst(std::string& subject, const std::string& replacement, int options = 0) const; + /// Substitute in subject all matches of the pattern with replacement. + /// If RE_GLOBAL is specified as option, all matches are replaced. Otherwise, + /// only the first match is replaced. + /// Occurences of $ (for example, $1, $2, ...) in replacement are replaced + /// with the corresponding captured string. $0 is the original subject string. + /// Returns the number of replaced occurences. + + int subst(std::string& subject, std::string::size_type offset, const std::string& replacement, int options = 0) const; + /// Substitute in subject all matches of the pattern with replacement, + /// starting at offset. + /// If RE_GLOBAL is specified as option, all matches are replaced. Otherwise, + /// only the first match is replaced. + /// Unless RE_NO_VARS is specified, occurences of $ (for example, $0, $1, $2, ... $9) + /// in replacement are replaced with the corresponding captured string. + /// $0 is the captured substring. $1 ... $n are the substrings maching the subpatterns. + /// Returns the number of replaced occurences. + + static bool match(const std::string& subject, const std::string& pattern, int options = 0); + /// Matches the given subject string against the regular expression given in pattern, + /// using the given options. + +protected: + std::string::size_type substOne(std::string& subject, std::string::size_type offset, const std::string& replacement, int options) const; + +private: + pcre* _pcre; + pcre_extra* _extra; + + static const int OVEC_SIZE; + + RegularExpression(); + RegularExpression(const RegularExpression&); + RegularExpression& operator = (const RegularExpression&); +}; + + +// +// inlines +// +inline int RegularExpression::match(const std::string& subject, Match& mtch, int options) const +{ + return match(subject, 0, mtch, options); +} + + +inline int RegularExpression::split(const std::string& subject, std::vector& strings, int options) const +{ + return split(subject, 0, strings, options); +} + + +inline int RegularExpression::subst(std::string& subject, const std::string& replacement, int options) const +{ + return subst(subject, 0, replacement, options); +} + + +} // namespace Poco + + +#endif // Foundation_RegularExpression_INCLUDED diff --git a/Foundation/include/Poco/RotateStrategy.h b/Foundation/include/Poco/RotateStrategy.h index 291efe00f..dc34a6b60 100644 --- a/Foundation/include/Poco/RotateStrategy.h +++ b/Foundation/include/Poco/RotateStrategy.h @@ -1,180 +1,180 @@ -// -// RotateStrategy.h -// -// $Id: //poco/1.2/Foundation/include/Poco/RotateStrategy.h#1 $ -// -// Library: Foundation -// Package: Logging -// Module: FileChannel -// -// Definition of the RotateStrategy class and subclasses. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_RotateStrategy_INCLUDED -#define Foundation_RotateStrategy_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/Timespan.h" -#include "Poco/Timestamp.h" -#include "Poco/Exception.h" -#include "Poco/LogFile.h" -#include "Poco/StringTokenizer.h" -#include "Poco/DateTimeParser.h" -#include "Poco/NumberParser.h" - - -namespace Poco { - - -class Foundation_API RotateStrategy - /// The RotateStrategy is used by LogFile to determine when - /// a file must be rotated. -{ -public: - RotateStrategy(); - virtual ~RotateStrategy(); - - virtual bool mustRotate(LogFile* pFile) = 0; - /// Returns true if the given log file must - /// be rotated, false otherwise. - -private: - RotateStrategy(const RotateStrategy&); - RotateStrategy& operator = (const RotateStrategy&); -}; - - -template -class RotateAtTimeStrategy: public RotateStrategy - /// The file is rotated at specified [day,][hour]:minute -{ -public: - RotateAtTimeStrategy(const std::string& rtime): - _day(-1), - _hour(-1), - _minute(0) - { - if (rtime.empty()) - throw InvalidArgumentException("Rotation time must be specified."); - - if ((rtime.find(',') != rtime.npos) && (rtime.find(':') == rtime.npos)) - throw InvalidArgumentException("Invalid rotation time specified."); - - StringTokenizer timestr(rtime, ",:", StringTokenizer::TOK_TRIM | StringTokenizer::TOK_IGNORE_EMPTY); - int index = 0; - - switch (timestr.count()) - { - case 3: // day,hh:mm - { - std::string::const_iterator it = timestr[index].begin(); - _day = DateTimeParser::parseDayOfWeek(it, timestr[index].end()); - ++index; - } - case 2: // hh:mm - _hour = NumberParser::parse(timestr[index]); - ++index; - case 1: // mm - _minute = NumberParser::parse(timestr[index]); - break; - default: - throw InvalidArgumentException("Invalid rotation time specified."); - } - getNextRollover(); - } - - ~RotateAtTimeStrategy() - { - } - - bool mustRotate(LogFile* pFile) - { - if (DT() >= _threshold) - { - getNextRollover(); - return true; - } - return false; - } - -private: - void getNextRollover() - { - Timespan tsp(0, 0, 1, 0, 1000); // 0,00:01:00.001 - do - { - _threshold += tsp; - } - while (!(_threshold.minute() == _minute && - (-1 == _hour || _threshold.hour() == _hour) && - (-1 == _day || _threshold.dayOfWeek() == _day))); - // round to :00.0 seconds - _threshold.assign(_threshold.year(), _threshold.month(), _threshold.day(), _threshold.hour(), _threshold.minute()); - } - - DT _threshold; - int _day; - int _hour; - int _minute; -}; - - -class Foundation_API RotateByIntervalStrategy: public RotateStrategy - /// The file is rotated when the log file - /// exceeds a given age. -{ -public: - RotateByIntervalStrategy(const Timespan& span); - ~RotateByIntervalStrategy(); - bool mustRotate(LogFile* pFile); - -private: - Timespan _span; -}; - - -class Foundation_API RotateBySizeStrategy: public RotateStrategy - /// The file is rotated when the log file - /// exceeds a given size. -{ -public: - RotateBySizeStrategy(UInt64 size); - ~RotateBySizeStrategy(); - bool mustRotate(LogFile* pFile); - -private: - UInt64 _size; -}; - - -} // namespace Poco - - -#endif // Foundation_RotateStrategy_INCLUDED +// +// RotateStrategy.h +// +// $Id: //poco/1.2/Foundation/include/Poco/RotateStrategy.h#1 $ +// +// Library: Foundation +// Package: Logging +// Module: FileChannel +// +// Definition of the RotateStrategy class and subclasses. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_RotateStrategy_INCLUDED +#define Foundation_RotateStrategy_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Timespan.h" +#include "Poco/Timestamp.h" +#include "Poco/Exception.h" +#include "Poco/LogFile.h" +#include "Poco/StringTokenizer.h" +#include "Poco/DateTimeParser.h" +#include "Poco/NumberParser.h" + + +namespace Poco { + + +class Foundation_API RotateStrategy + /// The RotateStrategy is used by LogFile to determine when + /// a file must be rotated. +{ +public: + RotateStrategy(); + virtual ~RotateStrategy(); + + virtual bool mustRotate(LogFile* pFile) = 0; + /// Returns true if the given log file must + /// be rotated, false otherwise. + +private: + RotateStrategy(const RotateStrategy&); + RotateStrategy& operator = (const RotateStrategy&); +}; + + +template +class RotateAtTimeStrategy: public RotateStrategy + /// The file is rotated at specified [day,][hour]:minute +{ +public: + RotateAtTimeStrategy(const std::string& rtime): + _day(-1), + _hour(-1), + _minute(0) + { + if (rtime.empty()) + throw InvalidArgumentException("Rotation time must be specified."); + + if ((rtime.find(',') != rtime.npos) && (rtime.find(':') == rtime.npos)) + throw InvalidArgumentException("Invalid rotation time specified."); + + StringTokenizer timestr(rtime, ",:", StringTokenizer::TOK_TRIM | StringTokenizer::TOK_IGNORE_EMPTY); + int index = 0; + + switch (timestr.count()) + { + case 3: // day,hh:mm + { + std::string::const_iterator it = timestr[index].begin(); + _day = DateTimeParser::parseDayOfWeek(it, timestr[index].end()); + ++index; + } + case 2: // hh:mm + _hour = NumberParser::parse(timestr[index]); + ++index; + case 1: // mm + _minute = NumberParser::parse(timestr[index]); + break; + default: + throw InvalidArgumentException("Invalid rotation time specified."); + } + getNextRollover(); + } + + ~RotateAtTimeStrategy() + { + } + + bool mustRotate(LogFile* pFile) + { + if (DT() >= _threshold) + { + getNextRollover(); + return true; + } + return false; + } + +private: + void getNextRollover() + { + Timespan tsp(0, 0, 1, 0, 1000); // 0,00:01:00.001 + do + { + _threshold += tsp; + } + while (!(_threshold.minute() == _minute && + (-1 == _hour || _threshold.hour() == _hour) && + (-1 == _day || _threshold.dayOfWeek() == _day))); + // round to :00.0 seconds + _threshold.assign(_threshold.year(), _threshold.month(), _threshold.day(), _threshold.hour(), _threshold.minute()); + } + + DT _threshold; + int _day; + int _hour; + int _minute; +}; + + +class Foundation_API RotateByIntervalStrategy: public RotateStrategy + /// The file is rotated when the log file + /// exceeds a given age. +{ +public: + RotateByIntervalStrategy(const Timespan& span); + ~RotateByIntervalStrategy(); + bool mustRotate(LogFile* pFile); + +private: + Timespan _span; +}; + + +class Foundation_API RotateBySizeStrategy: public RotateStrategy + /// The file is rotated when the log file + /// exceeds a given size. +{ +public: + RotateBySizeStrategy(UInt64 size); + ~RotateBySizeStrategy(); + bool mustRotate(LogFile* pFile); + +private: + UInt64 _size; +}; + + +} // namespace Poco + + +#endif // Foundation_RotateStrategy_INCLUDED diff --git a/Foundation/include/Poco/Runnable.h b/Foundation/include/Poco/Runnable.h index 451e09b2c..a435cf81e 100644 --- a/Foundation/include/Poco/Runnable.h +++ b/Foundation/include/Poco/Runnable.h @@ -1,67 +1,67 @@ -// -// Runnable.h -// -// $Id: //poco/1.2/Foundation/include/Poco/Runnable.h#1 $ -// -// Library: Foundation -// Package: Threading -// Module: Thread -// -// Definition of the Runnable class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_Runnable_INCLUDED -#define Foundation_Runnable_INCLUDED - - -#include "Poco/Foundation.h" - - -namespace Poco { - - -class Foundation_API Runnable - /// The Runnable interface with the run() method - /// must be implemented by classes that provide - /// an entry point for a thread. -{ -public: - Runnable(); - virtual ~Runnable(); - - virtual void run() = 0; - /// Do whatever the thread needs to do. Must - /// be overridden by subclasses. -}; - - -} // namespace Poco - - -#endif // Foundation_Runnable_INCLUDED +// +// Runnable.h +// +// $Id: //poco/1.2/Foundation/include/Poco/Runnable.h#1 $ +// +// Library: Foundation +// Package: Threading +// Module: Thread +// +// Definition of the Runnable class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_Runnable_INCLUDED +#define Foundation_Runnable_INCLUDED + + +#include "Poco/Foundation.h" + + +namespace Poco { + + +class Foundation_API Runnable + /// The Runnable interface with the run() method + /// must be implemented by classes that provide + /// an entry point for a thread. +{ +public: + Runnable(); + virtual ~Runnable(); + + virtual void run() = 0; + /// Do whatever the thread needs to do. Must + /// be overridden by subclasses. +}; + + +} // namespace Poco + + +#endif // Foundation_Runnable_INCLUDED diff --git a/Foundation/include/Poco/RunnableAdapter.h b/Foundation/include/Poco/RunnableAdapter.h index 23ef1bf43..b4341a97b 100644 --- a/Foundation/include/Poco/RunnableAdapter.h +++ b/Foundation/include/Poco/RunnableAdapter.h @@ -1,96 +1,96 @@ -// -// RunnableAdapter.h -// -// $Id: //poco/1.2/Foundation/include/Poco/RunnableAdapter.h#1 $ -// -// Library: Foundation -// Package: Threading -// Module: Thread -// -// Definition of the RunnableAdapter template class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_RunnableAdapter_INCLUDED -#define Foundation_RunnableAdapter_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/Runnable.h" - - -namespace Poco { - - -template -class RunnableAdapter: public Runnable - /// This adapter simplifies using ordinary methods as - /// targets for threads. - /// Usage: - /// RunnableAdapter ra(myObject, &MyObject::doSomething)); - /// Thread thr; - /// thr.Start(ra); -{ -public: - typedef void (C::*Callback)(); - - RunnableAdapter(C& object, Callback method): _pObject(&object), _method(method) - { - } - - RunnableAdapter(const RunnableAdapter& ra): _pObject(ra._pObject), _method(ra._method) - { - } - - ~RunnableAdapter() - { - } - - RunnableAdapter& operator = (const RunnableAdapter& ra) - { - _pObject = ra._pObject; - _method = ra._method; - } - - void run() - { - (_pObject->*_method)(); - } - -private: - RunnableAdapter(); - - C* _pObject; - Callback _method; -}; - - -} // namespace Poco - - -#endif // Foundation_RunnableAdapter_INCLUDED +// +// RunnableAdapter.h +// +// $Id: //poco/1.2/Foundation/include/Poco/RunnableAdapter.h#1 $ +// +// Library: Foundation +// Package: Threading +// Module: Thread +// +// Definition of the RunnableAdapter template class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_RunnableAdapter_INCLUDED +#define Foundation_RunnableAdapter_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Runnable.h" + + +namespace Poco { + + +template +class RunnableAdapter: public Runnable + /// This adapter simplifies using ordinary methods as + /// targets for threads. + /// Usage: + /// RunnableAdapter ra(myObject, &MyObject::doSomething)); + /// Thread thr; + /// thr.Start(ra); +{ +public: + typedef void (C::*Callback)(); + + RunnableAdapter(C& object, Callback method): _pObject(&object), _method(method) + { + } + + RunnableAdapter(const RunnableAdapter& ra): _pObject(ra._pObject), _method(ra._method) + { + } + + ~RunnableAdapter() + { + } + + RunnableAdapter& operator = (const RunnableAdapter& ra) + { + _pObject = ra._pObject; + _method = ra._method; + } + + void run() + { + (_pObject->*_method)(); + } + +private: + RunnableAdapter(); + + C* _pObject; + Callback _method; +}; + + +} // namespace Poco + + +#endif // Foundation_RunnableAdapter_INCLUDED diff --git a/Foundation/include/Poco/SHA1Engine.h b/Foundation/include/Poco/SHA1Engine.h index b54265808..795b8205a 100644 --- a/Foundation/include/Poco/SHA1Engine.h +++ b/Foundation/include/Poco/SHA1Engine.h @@ -1,100 +1,100 @@ -// -// SHA1Engine.h -// -// $Id: //poco/1.2/Foundation/include/Poco/SHA1Engine.h#1 $ -// -// Library: Foundation -// Package: Crypt -// Module: SHA1Engine -// -// Definition of class SHA1Engine. -// -// Secure Hash Standard SHA-1 algorithm -// (FIPS 180-1, see http://www.itl.nist.gov/fipspubs/fip180-1.htm) -// -// Based on the public domain implementation by Peter C. Gutmann -// on 2 Sep 1992, modified by Carl Ellison to be SHA-1. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_SHA1Engine_INCLUDED -#define Foundation_SHA1Engine_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/DigestEngine.h" - - -namespace Poco { - - -class Foundation_API SHA1Engine: public DigestEngine - /// This class implementes the SHA-1 message digest algorithm. - /// (FIPS 180-1, see http://www.itl.nist.gov/fipspubs/fip180-1.htm) -{ -public: - enum - { - BLOCK_SIZE = 64, - DIGEST_SIZE = 20 - }; - - SHA1Engine(); - ~SHA1Engine(); - - unsigned digestLength() const; - void reset(); - const DigestEngine::Digest& digest(); - -protected: - void updateImpl(const void* data, unsigned length); - -private: - void transform(); - static void byteReverse(UInt32* buffer, int byteCount); - - typedef UInt8 BYTE; - - struct Context - { - UInt32 digest[5]; // Message digest - UInt32 countLo; // 64-bit bit count - UInt32 countHi; - UInt32 data[16]; // SHA data buffer - UInt32 slop; // # of bytes saved in data[] - }; - - Context _context; - DigestEngine::Digest _digest; -}; - - -} // namespace Poco - - -#endif // Foundation_SHA1Engine_INCLUDED +// +// SHA1Engine.h +// +// $Id: //poco/1.2/Foundation/include/Poco/SHA1Engine.h#1 $ +// +// Library: Foundation +// Package: Crypt +// Module: SHA1Engine +// +// Definition of class SHA1Engine. +// +// Secure Hash Standard SHA-1 algorithm +// (FIPS 180-1, see http://www.itl.nist.gov/fipspubs/fip180-1.htm) +// +// Based on the public domain implementation by Peter C. Gutmann +// on 2 Sep 1992, modified by Carl Ellison to be SHA-1. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_SHA1Engine_INCLUDED +#define Foundation_SHA1Engine_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/DigestEngine.h" + + +namespace Poco { + + +class Foundation_API SHA1Engine: public DigestEngine + /// This class implementes the SHA-1 message digest algorithm. + /// (FIPS 180-1, see http://www.itl.nist.gov/fipspubs/fip180-1.htm) +{ +public: + enum + { + BLOCK_SIZE = 64, + DIGEST_SIZE = 20 + }; + + SHA1Engine(); + ~SHA1Engine(); + + unsigned digestLength() const; + void reset(); + const DigestEngine::Digest& digest(); + +protected: + void updateImpl(const void* data, unsigned length); + +private: + void transform(); + static void byteReverse(UInt32* buffer, int byteCount); + + typedef UInt8 BYTE; + + struct Context + { + UInt32 digest[5]; // Message digest + UInt32 countLo; // 64-bit bit count + UInt32 countHi; + UInt32 data[16]; // SHA data buffer + UInt32 slop; // # of bytes saved in data[] + }; + + Context _context; + DigestEngine::Digest _digest; +}; + + +} // namespace Poco + + +#endif // Foundation_SHA1Engine_INCLUDED diff --git a/Foundation/include/Poco/ScopedLock.h b/Foundation/include/Poco/ScopedLock.h index 12a8b684b..2f88e0625 100644 --- a/Foundation/include/Poco/ScopedLock.h +++ b/Foundation/include/Poco/ScopedLock.h @@ -1,78 +1,78 @@ -// -// ScopedLock.h -// -// $Id: //poco/1.2/Foundation/include/Poco/ScopedLock.h#1 $ -// -// Library: Foundation -// Package: Threading -// Module: Mutex -// -// Definition of the ScopedLock template class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_ScopedLock_INCLUDED -#define Foundation_ScopedLock_INCLUDED - - -#include "Poco/Foundation.h" - - -namespace Poco { - - -template -class ScopedLock - /// A class that simplifies thread synchronization - /// with a mutex. - /// The constructor accepts a Mutex and locks it. - /// The destructor unlocks the mutex. -{ -public: - inline ScopedLock(M& mutex): _mutex(mutex) - { - _mutex.lock(); - } - inline ~ScopedLock() - { - _mutex.unlock(); - } - -private: - M& _mutex; - - ScopedLock(); - ScopedLock(const ScopedLock&); - ScopedLock& operator = (const ScopedLock&); -}; - - -} // namespace Poco - - -#endif // Foundation_ScopedLock_INCLUDED +// +// ScopedLock.h +// +// $Id: //poco/1.2/Foundation/include/Poco/ScopedLock.h#1 $ +// +// Library: Foundation +// Package: Threading +// Module: Mutex +// +// Definition of the ScopedLock template class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_ScopedLock_INCLUDED +#define Foundation_ScopedLock_INCLUDED + + +#include "Poco/Foundation.h" + + +namespace Poco { + + +template +class ScopedLock + /// A class that simplifies thread synchronization + /// with a mutex. + /// The constructor accepts a Mutex and locks it. + /// The destructor unlocks the mutex. +{ +public: + inline ScopedLock(M& mutex): _mutex(mutex) + { + _mutex.lock(); + } + inline ~ScopedLock() + { + _mutex.unlock(); + } + +private: + M& _mutex; + + ScopedLock(); + ScopedLock(const ScopedLock&); + ScopedLock& operator = (const ScopedLock&); +}; + + +} // namespace Poco + + +#endif // Foundation_ScopedLock_INCLUDED diff --git a/Foundation/include/Poco/Semaphore.h b/Foundation/include/Poco/Semaphore.h index ec83fa62c..cf5febb94 100644 --- a/Foundation/include/Poco/Semaphore.h +++ b/Foundation/include/Poco/Semaphore.h @@ -1,157 +1,157 @@ -// -// Semaphore.h -// -// $Id: //poco/1.2/Foundation/include/Poco/Semaphore.h#1 $ -// -// Library: Foundation -// Package: Threading -// Module: Semaphore -// -// Definition of the Semaphore class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_Semaphore_INCLUDED -#define Foundation_Semaphore_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/Exception.h" - - -#if defined(POCO_OS_FAMILY_WINDOWS) -#include "Poco/Semaphore_WIN32.h" -#else -#include "Poco/Semaphore_POSIX.h" -#endif - - -namespace Poco { - - -class Foundation_API Semaphore: private SemaphoreImpl - /// A Semaphore is a synchronization object with the following - /// characteristics: - /// A semaphore has a value that is constrained to be a non-negative - /// integer and two atomic operations. The allowable operations are V - /// (here called set()) and P (here called wait()). A V (set()) operation - /// increases the value of the semaphore by one. - /// A P (wait()) operation decreases the value of the semaphore by one, - /// provided that can be done without violating the constraint that the - /// value be non-negative. A P (wait()) operation that is initiated when - /// the value of the semaphore is 0 suspends the calling thread. - /// The calling thread may continue when the value becomes positive again. -{ -public: - Semaphore(int n); - Semaphore(int n, int max); - /// Creates the semaphore. The current value - /// of the semaphore is given in n. The - /// maximum value of the semaphore is given - /// in max. - /// If only n is given, it must be greater than - /// zero. - /// If both n and max are given, max must be - /// greater than zero, n must be greater than - /// or equal to zero and less than or equal - /// to max. - - ~Semaphore(); - /// Destroys the semaphore. - - void set(); - /// Increments the semaphore's value by one and - /// thus signals the semaphore. Another thread - /// waiting for the semaphore will be able - /// to continue. - - void wait(); - /// Waits for the semaphore to become signalled. - /// To become signalled, a semaphore's value must - /// be greater than zero. - /// Decrements the semaphore's value by one. - - void wait(long milliseconds); - /// Waits for the semaphore to become signalled. - /// To become signalled, a semaphore's value must - /// be greater than zero. - /// Throws a TimeOutException if the semaphore - /// does not become signalled within the specified - /// time interval. - /// Decrements the semaphore's value by one - /// if successful. - - bool tryWait(long milliseconds); - /// Waits for the semaphore to become signalled. - /// To become signalled, a semaphore's value must - /// be greater than zero. - /// Returns true if the semaphore - /// became signalled within the specified - /// time interval, false otherwise. - /// Decrements the semaphore's value by one - /// if successful. - -private: - Semaphore(); - Semaphore(const Semaphore&); - Semaphore& operator = (const Semaphore&); -}; - - -// -// inlines -// -inline void Semaphore::set() -{ - setImpl(); -} - - -inline void Semaphore::wait() -{ - waitImpl(); -} - - -inline void Semaphore::wait(long milliseconds) -{ - if (!waitImpl(milliseconds)) - throw TimeoutException(); -} - - -inline bool Semaphore::tryWait(long milliseconds) -{ - return waitImpl(milliseconds); -} - - -} // namespace Poco - - -#endif // Foundation_Semaphore_INCLUDED +// +// Semaphore.h +// +// $Id: //poco/1.2/Foundation/include/Poco/Semaphore.h#1 $ +// +// Library: Foundation +// Package: Threading +// Module: Semaphore +// +// Definition of the Semaphore class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_Semaphore_INCLUDED +#define Foundation_Semaphore_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Exception.h" + + +#if defined(POCO_OS_FAMILY_WINDOWS) +#include "Poco/Semaphore_WIN32.h" +#else +#include "Poco/Semaphore_POSIX.h" +#endif + + +namespace Poco { + + +class Foundation_API Semaphore: private SemaphoreImpl + /// A Semaphore is a synchronization object with the following + /// characteristics: + /// A semaphore has a value that is constrained to be a non-negative + /// integer and two atomic operations. The allowable operations are V + /// (here called set()) and P (here called wait()). A V (set()) operation + /// increases the value of the semaphore by one. + /// A P (wait()) operation decreases the value of the semaphore by one, + /// provided that can be done without violating the constraint that the + /// value be non-negative. A P (wait()) operation that is initiated when + /// the value of the semaphore is 0 suspends the calling thread. + /// The calling thread may continue when the value becomes positive again. +{ +public: + Semaphore(int n); + Semaphore(int n, int max); + /// Creates the semaphore. The current value + /// of the semaphore is given in n. The + /// maximum value of the semaphore is given + /// in max. + /// If only n is given, it must be greater than + /// zero. + /// If both n and max are given, max must be + /// greater than zero, n must be greater than + /// or equal to zero and less than or equal + /// to max. + + ~Semaphore(); + /// Destroys the semaphore. + + void set(); + /// Increments the semaphore's value by one and + /// thus signals the semaphore. Another thread + /// waiting for the semaphore will be able + /// to continue. + + void wait(); + /// Waits for the semaphore to become signalled. + /// To become signalled, a semaphore's value must + /// be greater than zero. + /// Decrements the semaphore's value by one. + + void wait(long milliseconds); + /// Waits for the semaphore to become signalled. + /// To become signalled, a semaphore's value must + /// be greater than zero. + /// Throws a TimeOutException if the semaphore + /// does not become signalled within the specified + /// time interval. + /// Decrements the semaphore's value by one + /// if successful. + + bool tryWait(long milliseconds); + /// Waits for the semaphore to become signalled. + /// To become signalled, a semaphore's value must + /// be greater than zero. + /// Returns true if the semaphore + /// became signalled within the specified + /// time interval, false otherwise. + /// Decrements the semaphore's value by one + /// if successful. + +private: + Semaphore(); + Semaphore(const Semaphore&); + Semaphore& operator = (const Semaphore&); +}; + + +// +// inlines +// +inline void Semaphore::set() +{ + setImpl(); +} + + +inline void Semaphore::wait() +{ + waitImpl(); +} + + +inline void Semaphore::wait(long milliseconds) +{ + if (!waitImpl(milliseconds)) + throw TimeoutException(); +} + + +inline bool Semaphore::tryWait(long milliseconds) +{ + return waitImpl(milliseconds); +} + + +} // namespace Poco + + +#endif // Foundation_Semaphore_INCLUDED diff --git a/Foundation/include/Poco/Semaphore_POSIX.h b/Foundation/include/Poco/Semaphore_POSIX.h index 3fe06e4f4..9dfa799fb 100644 --- a/Foundation/include/Poco/Semaphore_POSIX.h +++ b/Foundation/include/Poco/Semaphore_POSIX.h @@ -1,97 +1,97 @@ -// -// Semaphore_POSIX.h -// -// $Id: //poco/1.2/Foundation/include/Poco/Semaphore_POSIX.h#1 $ -// -// Library: Foundation -// Package: Threading -// Module: Semaphore -// -// Definition of the SemaphoreImpl class for POSIX Threads. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_Semaphore_POSIX_INCLUDED -#define Foundation_Semaphore_POSIX_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/Exception.h" -#include -#include - - -namespace Poco { - - -class Foundation_API SemaphoreImpl -{ -protected: - SemaphoreImpl(int n, int max); - ~SemaphoreImpl(); - void setImpl(); - void waitImpl(); - bool waitImpl(long milliseconds); - -private: - volatile int _n; - int _max; - pthread_mutex_t _mutex; - pthread_cond_t _cond; -}; - - -// -// inlines -// -inline void SemaphoreImpl::setImpl() -{ - if (pthread_mutex_lock(&_mutex)) - throw SystemException("cannot signal semaphore (lock)"); - if (_n < _max) - { - ++_n; - } - else - { - pthread_mutex_unlock(&_mutex); - throw SystemException("cannot signal semaphore: count would exceed maximum"); - } - if (pthread_cond_signal(&_cond)) - { - pthread_mutex_unlock(&_mutex); - throw SystemException("cannot signal semaphore"); - } - pthread_mutex_unlock(&_mutex); -} - - -} // namespace Poco - - -#endif // Foundation_Semaphore_POSIX_INCLUDED +// +// Semaphore_POSIX.h +// +// $Id: //poco/1.2/Foundation/include/Poco/Semaphore_POSIX.h#1 $ +// +// Library: Foundation +// Package: Threading +// Module: Semaphore +// +// Definition of the SemaphoreImpl class for POSIX Threads. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_Semaphore_POSIX_INCLUDED +#define Foundation_Semaphore_POSIX_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Exception.h" +#include +#include + + +namespace Poco { + + +class Foundation_API SemaphoreImpl +{ +protected: + SemaphoreImpl(int n, int max); + ~SemaphoreImpl(); + void setImpl(); + void waitImpl(); + bool waitImpl(long milliseconds); + +private: + volatile int _n; + int _max; + pthread_mutex_t _mutex; + pthread_cond_t _cond; +}; + + +// +// inlines +// +inline void SemaphoreImpl::setImpl() +{ + if (pthread_mutex_lock(&_mutex)) + throw SystemException("cannot signal semaphore (lock)"); + if (_n < _max) + { + ++_n; + } + else + { + pthread_mutex_unlock(&_mutex); + throw SystemException("cannot signal semaphore: count would exceed maximum"); + } + if (pthread_cond_signal(&_cond)) + { + pthread_mutex_unlock(&_mutex); + throw SystemException("cannot signal semaphore"); + } + pthread_mutex_unlock(&_mutex); +} + + +} // namespace Poco + + +#endif // Foundation_Semaphore_POSIX_INCLUDED diff --git a/Foundation/include/Poco/Semaphore_WIN32.h b/Foundation/include/Poco/Semaphore_WIN32.h index 917776450..d0a49f92a 100644 --- a/Foundation/include/Poco/Semaphore_WIN32.h +++ b/Foundation/include/Poco/Semaphore_WIN32.h @@ -1,80 +1,80 @@ -// -// Semaphore_WIN32.h -// -// $Id: //poco/1.2/Foundation/include/Poco/Semaphore_WIN32.h#1 $ -// -// Library: Foundation -// Package: Threading -// Module: Semaphore -// -// Definition of the SemaphoreImpl class for WIN32. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_Semaphore_WIN32_INCLUDED -#define Foundation_Semaphore_WIN32_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/Exception.h" -#include - - -namespace Poco { - - -class Foundation_API SemaphoreImpl -{ -protected: - SemaphoreImpl(int n, int max); - ~SemaphoreImpl(); - void setImpl(); - void waitImpl(); - bool waitImpl(long milliseconds); - -private: - HANDLE _sema; -}; - - -// -// inlines -// -inline void SemaphoreImpl::setImpl() -{ - if (!ReleaseSemaphore(_sema, 1, NULL)) - { - throw SystemException("cannot signal semaphore"); - } -} - - -} // namespace Poco - - -#endif // Foundation_Semaphore_WIN32_INCLUDED +// +// Semaphore_WIN32.h +// +// $Id: //poco/1.2/Foundation/include/Poco/Semaphore_WIN32.h#1 $ +// +// Library: Foundation +// Package: Threading +// Module: Semaphore +// +// Definition of the SemaphoreImpl class for WIN32. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_Semaphore_WIN32_INCLUDED +#define Foundation_Semaphore_WIN32_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Exception.h" +#include + + +namespace Poco { + + +class Foundation_API SemaphoreImpl +{ +protected: + SemaphoreImpl(int n, int max); + ~SemaphoreImpl(); + void setImpl(); + void waitImpl(); + bool waitImpl(long milliseconds); + +private: + HANDLE _sema; +}; + + +// +// inlines +// +inline void SemaphoreImpl::setImpl() +{ + if (!ReleaseSemaphore(_sema, 1, NULL)) + { + throw SystemException("cannot signal semaphore"); + } +} + + +} // namespace Poco + + +#endif // Foundation_Semaphore_WIN32_INCLUDED diff --git a/Foundation/include/Poco/SharedLibrary.h b/Foundation/include/Poco/SharedLibrary.h index 861a280cf..877466b45 100644 --- a/Foundation/include/Poco/SharedLibrary.h +++ b/Foundation/include/Poco/SharedLibrary.h @@ -1,122 +1,122 @@ -// -// SharedLibrary.h -// -// $Id: //poco/1.2/Foundation/include/Poco/SharedLibrary.h#1 $ -// -// Library: Foundation -// Package: SharedLibrary -// Module: SharedLibrary -// -// Definition of the SharedLibrary class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_SharedLibrary_INCLUDED -#define Foundation_SharedLibrary_INCLUDED - - -#include "Poco/Foundation.h" - - -#if defined(hpux) || defined(_hpux) -#include "Poco/SharedLibrary_HPUX.h" -#elif defined(POCO_OS_FAMILY_UNIX) -#include "Poco/SharedLibrary_UNIX.h" -#elif defined(POCO_OS_FAMILY_WINDOWS) && defined(POCO_WIN32_UTF8) -#include "Poco/SharedLibrary_WIN32U.h" -#elif defined(POCO_OS_FAMILY_WINDOWS) -#include "Poco/SharedLibrary_WIN32.h" -#elif defined(POCO_OS_FAMILY_VMS) -#include "Poco/SharedLibrary_VMS.h" -#endif - - -namespace Poco { - - -class Foundation_API SharedLibrary: private SharedLibraryImpl - /// The SharedLibrary class dynamically - /// loads shared libraries at run-time. -{ -public: - SharedLibrary(); - /// Creates a SharedLibrary object. - - SharedLibrary(const std::string& path); - /// Creates a SharedLibrary object and loads a library - /// from the given path. - - virtual ~SharedLibrary(); - /// Destroys the SharedLibrary. The actual library - /// remains loaded. - - void load(const std::string& path); - /// Loads a shared library from the given path. - /// Throws a LibraryAlreadyLoadedException if - /// a library has already been loaded. - /// Throws a LibraryLoadException if the library - /// cannot be loaded. - - void unload(); - /// Unloads a shared library. - - bool isLoaded() const; - /// Returns true iff a library has been loaded. - - bool hasSymbol(const std::string& name); - /// Returns true iff the loaded library contains - /// a symbol with the given name. - - void* getSymbol(const std::string& name); - /// Returns the address of the symbol with - /// the given name. For functions, this - /// is the entry point of the function. - /// Throws a NotFoundException if the symbol - /// does not exist. - - const std::string& getPath() const; - /// Returns the path of the library, as - /// specified in a call to load() or the - /// constructor. - - static std::string suffix(); - /// Returns the platform-specific filename suffix - /// for shared libraries (including the period). - /// In debug mode, the suffix also includes a - /// "d" to specify the debug version of a library. - -private: - SharedLibrary(const SharedLibrary&); - SharedLibrary& operator = (const SharedLibrary&); -}; - - -} // namespace Poco - - -#endif // Foundation_SharedLibrary_INCLUDED +// +// SharedLibrary.h +// +// $Id: //poco/1.2/Foundation/include/Poco/SharedLibrary.h#1 $ +// +// Library: Foundation +// Package: SharedLibrary +// Module: SharedLibrary +// +// Definition of the SharedLibrary class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_SharedLibrary_INCLUDED +#define Foundation_SharedLibrary_INCLUDED + + +#include "Poco/Foundation.h" + + +#if defined(hpux) || defined(_hpux) +#include "Poco/SharedLibrary_HPUX.h" +#elif defined(POCO_OS_FAMILY_UNIX) +#include "Poco/SharedLibrary_UNIX.h" +#elif defined(POCO_OS_FAMILY_WINDOWS) && defined(POCO_WIN32_UTF8) +#include "Poco/SharedLibrary_WIN32U.h" +#elif defined(POCO_OS_FAMILY_WINDOWS) +#include "Poco/SharedLibrary_WIN32.h" +#elif defined(POCO_OS_FAMILY_VMS) +#include "Poco/SharedLibrary_VMS.h" +#endif + + +namespace Poco { + + +class Foundation_API SharedLibrary: private SharedLibraryImpl + /// The SharedLibrary class dynamically + /// loads shared libraries at run-time. +{ +public: + SharedLibrary(); + /// Creates a SharedLibrary object. + + SharedLibrary(const std::string& path); + /// Creates a SharedLibrary object and loads a library + /// from the given path. + + virtual ~SharedLibrary(); + /// Destroys the SharedLibrary. The actual library + /// remains loaded. + + void load(const std::string& path); + /// Loads a shared library from the given path. + /// Throws a LibraryAlreadyLoadedException if + /// a library has already been loaded. + /// Throws a LibraryLoadException if the library + /// cannot be loaded. + + void unload(); + /// Unloads a shared library. + + bool isLoaded() const; + /// Returns true iff a library has been loaded. + + bool hasSymbol(const std::string& name); + /// Returns true iff the loaded library contains + /// a symbol with the given name. + + void* getSymbol(const std::string& name); + /// Returns the address of the symbol with + /// the given name. For functions, this + /// is the entry point of the function. + /// Throws a NotFoundException if the symbol + /// does not exist. + + const std::string& getPath() const; + /// Returns the path of the library, as + /// specified in a call to load() or the + /// constructor. + + static std::string suffix(); + /// Returns the platform-specific filename suffix + /// for shared libraries (including the period). + /// In debug mode, the suffix also includes a + /// "d" to specify the debug version of a library. + +private: + SharedLibrary(const SharedLibrary&); + SharedLibrary& operator = (const SharedLibrary&); +}; + + +} // namespace Poco + + +#endif // Foundation_SharedLibrary_INCLUDED diff --git a/Foundation/include/Poco/SharedLibrary_HPUX.h b/Foundation/include/Poco/SharedLibrary_HPUX.h index bf4986a62..2ffac136c 100644 --- a/Foundation/include/Poco/SharedLibrary_HPUX.h +++ b/Foundation/include/Poco/SharedLibrary_HPUX.h @@ -1,73 +1,73 @@ -// -// SharedLibrary_HPUX.h -// -// $Id: //poco/1.2/Foundation/include/Poco/SharedLibrary_HPUX.h#1 $ -// -// Library: Foundation -// Package: SharedLibrary -// Module: SharedLibrary -// -// Definition of the SharedLibraryImpl class for HP-UX. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_SharedLibrary_HPUX_INCLUDED -#define Foundation_SharedLibrary_HPUX_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/Mutex.h" -#include - - -namespace Poco { - - -class Foundation_API SharedLibraryImpl -{ -protected: - SharedLibraryImpl(); - ~SharedLibraryImpl(); - void loadImpl(const std::string& path); - void unloadImpl(); - bool isLoadedImpl() const; - void* findSymbolImpl(const std::string& name); - const std::string& getPathImpl() const; - static std::string suffixImpl(); - -private: - std::string _path; - shl_t _handle; - static FastMutex _mutex; -}; - - -} // namespace Poco - - -#endif // Foundation_SharedLibrary_HPUX_INCLUDED +// +// SharedLibrary_HPUX.h +// +// $Id: //poco/1.2/Foundation/include/Poco/SharedLibrary_HPUX.h#1 $ +// +// Library: Foundation +// Package: SharedLibrary +// Module: SharedLibrary +// +// Definition of the SharedLibraryImpl class for HP-UX. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_SharedLibrary_HPUX_INCLUDED +#define Foundation_SharedLibrary_HPUX_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Mutex.h" +#include + + +namespace Poco { + + +class Foundation_API SharedLibraryImpl +{ +protected: + SharedLibraryImpl(); + ~SharedLibraryImpl(); + void loadImpl(const std::string& path); + void unloadImpl(); + bool isLoadedImpl() const; + void* findSymbolImpl(const std::string& name); + const std::string& getPathImpl() const; + static std::string suffixImpl(); + +private: + std::string _path; + shl_t _handle; + static FastMutex _mutex; +}; + + +} // namespace Poco + + +#endif // Foundation_SharedLibrary_HPUX_INCLUDED diff --git a/Foundation/include/Poco/SharedLibrary_UNIX.h b/Foundation/include/Poco/SharedLibrary_UNIX.h index 302593196..67f52fe11 100644 --- a/Foundation/include/Poco/SharedLibrary_UNIX.h +++ b/Foundation/include/Poco/SharedLibrary_UNIX.h @@ -1,72 +1,72 @@ -// -// SharedLibrary_UNIX.h -// -// $Id: //poco/1.2/Foundation/include/Poco/SharedLibrary_UNIX.h#1 $ -// -// Library: Foundation -// Package: SharedLibrary -// Module: SharedLibrary -// -// Definition of the SharedLibraryImpl class for UNIX (dlopen). -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_SharedLibrary_UNIX_INCLUDED -#define Foundation_SharedLibrary_UNIX_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/Mutex.h" - - -namespace Poco { - - -class Foundation_API SharedLibraryImpl -{ -protected: - SharedLibraryImpl(); - ~SharedLibraryImpl(); - void loadImpl(const std::string& path); - void unloadImpl(); - bool isLoadedImpl() const; - void* findSymbolImpl(const std::string& name); - const std::string& getPathImpl() const; - static std::string suffixImpl(); - -private: - std::string _path; - void* _handle; - static FastMutex _mutex; -}; - - -} // namespace Poco - - -#endif // Foundation_SharedLibrary_UNIX_INCLUDED +// +// SharedLibrary_UNIX.h +// +// $Id: //poco/1.2/Foundation/include/Poco/SharedLibrary_UNIX.h#1 $ +// +// Library: Foundation +// Package: SharedLibrary +// Module: SharedLibrary +// +// Definition of the SharedLibraryImpl class for UNIX (dlopen). +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_SharedLibrary_UNIX_INCLUDED +#define Foundation_SharedLibrary_UNIX_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Mutex.h" + + +namespace Poco { + + +class Foundation_API SharedLibraryImpl +{ +protected: + SharedLibraryImpl(); + ~SharedLibraryImpl(); + void loadImpl(const std::string& path); + void unloadImpl(); + bool isLoadedImpl() const; + void* findSymbolImpl(const std::string& name); + const std::string& getPathImpl() const; + static std::string suffixImpl(); + +private: + std::string _path; + void* _handle; + static FastMutex _mutex; +}; + + +} // namespace Poco + + +#endif // Foundation_SharedLibrary_UNIX_INCLUDED diff --git a/Foundation/include/Poco/SharedLibrary_VMS.h b/Foundation/include/Poco/SharedLibrary_VMS.h index 78322703a..6415cadcf 100644 --- a/Foundation/include/Poco/SharedLibrary_VMS.h +++ b/Foundation/include/Poco/SharedLibrary_VMS.h @@ -1,71 +1,71 @@ -// -// SharedLibrary_VMS.h -// -// $Id: //poco/1.2/Foundation/include/Poco/SharedLibrary_VMS.h#1 $ -// -// Library: Foundation -// Package: SharedLibrary -// Module: SharedLibrary -// -// Definition of the SharedLibraryImpl class for VMS (dlopen). -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_SharedLibrary_VMS_INCLUDED -#define Foundation_SharedLibrary_VMS_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/Mutex.h" - - -namespace Poco { - - -class Foundation_API SharedLibraryImpl -{ -protected: - SharedLibraryImpl(); - ~SharedLibraryImpl(); - void loadImpl(const std::string& path); - void unloadImpl(); - bool isLoadedImpl() const; - void* findSymbolImpl(const std::string& name); - const std::string& getPathImpl() const; - static std::string suffixImpl(); - -private: - std::string _path; - static FastMutex _mutex; -}; - - -} // namespace Poco - - -#endif // Foundation_SharedLibrary_VMS_INCLUDED +// +// SharedLibrary_VMS.h +// +// $Id: //poco/1.2/Foundation/include/Poco/SharedLibrary_VMS.h#1 $ +// +// Library: Foundation +// Package: SharedLibrary +// Module: SharedLibrary +// +// Definition of the SharedLibraryImpl class for VMS (dlopen). +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_SharedLibrary_VMS_INCLUDED +#define Foundation_SharedLibrary_VMS_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Mutex.h" + + +namespace Poco { + + +class Foundation_API SharedLibraryImpl +{ +protected: + SharedLibraryImpl(); + ~SharedLibraryImpl(); + void loadImpl(const std::string& path); + void unloadImpl(); + bool isLoadedImpl() const; + void* findSymbolImpl(const std::string& name); + const std::string& getPathImpl() const; + static std::string suffixImpl(); + +private: + std::string _path; + static FastMutex _mutex; +}; + + +} // namespace Poco + + +#endif // Foundation_SharedLibrary_VMS_INCLUDED diff --git a/Foundation/include/Poco/SharedLibrary_WIN32.h b/Foundation/include/Poco/SharedLibrary_WIN32.h index f54a92129..d3ac175d3 100644 --- a/Foundation/include/Poco/SharedLibrary_WIN32.h +++ b/Foundation/include/Poco/SharedLibrary_WIN32.h @@ -1,72 +1,72 @@ -// -// SharedLibrary_WIN32.h -// -// $Id: //poco/1.2/Foundation/include/Poco/SharedLibrary_WIN32.h#1 $ -// -// Library: Foundation -// Package: SharedLibrary -// Module: SharedLibrary -// -// Definition of the SharedLibraryImpl class for Win32. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_SharedLibrary_WIN32_INCLUDED -#define Foundation_SharedLibrary_WIN32_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/Mutex.h" - - -namespace Poco { - - -class Foundation_API SharedLibraryImpl -{ -protected: - SharedLibraryImpl(); - ~SharedLibraryImpl(); - void loadImpl(const std::string& path); - void unloadImpl(); - bool isLoadedImpl() const; - void* findSymbolImpl(const std::string& name); - const std::string& getPathImpl() const; - static std::string suffixImpl(); - -private: - std::string _path; - void* _handle; - static FastMutex _mutex; -}; - - -} // namespace Poco - - -#endif // Foundation_SharedLibrary_WIN32_INCLUDED +// +// SharedLibrary_WIN32.h +// +// $Id: //poco/1.2/Foundation/include/Poco/SharedLibrary_WIN32.h#1 $ +// +// Library: Foundation +// Package: SharedLibrary +// Module: SharedLibrary +// +// Definition of the SharedLibraryImpl class for Win32. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_SharedLibrary_WIN32_INCLUDED +#define Foundation_SharedLibrary_WIN32_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Mutex.h" + + +namespace Poco { + + +class Foundation_API SharedLibraryImpl +{ +protected: + SharedLibraryImpl(); + ~SharedLibraryImpl(); + void loadImpl(const std::string& path); + void unloadImpl(); + bool isLoadedImpl() const; + void* findSymbolImpl(const std::string& name); + const std::string& getPathImpl() const; + static std::string suffixImpl(); + +private: + std::string _path; + void* _handle; + static FastMutex _mutex; +}; + + +} // namespace Poco + + +#endif // Foundation_SharedLibrary_WIN32_INCLUDED diff --git a/Foundation/include/Poco/SharedLibrary_WIN32U.h b/Foundation/include/Poco/SharedLibrary_WIN32U.h index 4a7f4de8d..09a9d214e 100644 --- a/Foundation/include/Poco/SharedLibrary_WIN32U.h +++ b/Foundation/include/Poco/SharedLibrary_WIN32U.h @@ -1,72 +1,72 @@ -// -// SharedLibrary_WIN32U.h -// -// $Id: //poco/1.2/Foundation/include/Poco/SharedLibrary_WIN32U.h#1 $ -// -// Library: Foundation -// Package: SharedLibrary -// Module: SharedLibrary -// -// Definition of the SharedLibraryImpl class for Win32. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_SharedLibrary_WIN32U_INCLUDED -#define Foundation_SharedLibrary_WIN32U_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/Mutex.h" - - -namespace Poco { - - -class Foundation_API SharedLibraryImpl -{ -protected: - SharedLibraryImpl(); - ~SharedLibraryImpl(); - void loadImpl(const std::string& path); - void unloadImpl(); - bool isLoadedImpl() const; - void* findSymbolImpl(const std::string& name); - const std::string& getPathImpl() const; - static std::string suffixImpl(); - -private: - std::string _path; - void* _handle; - static FastMutex _mutex; -}; - - -} // namespace Poco - - -#endif // Foundation_SharedLibrary_WIN32U_INCLUDED +// +// SharedLibrary_WIN32U.h +// +// $Id: //poco/1.2/Foundation/include/Poco/SharedLibrary_WIN32U.h#1 $ +// +// Library: Foundation +// Package: SharedLibrary +// Module: SharedLibrary +// +// Definition of the SharedLibraryImpl class for Win32. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_SharedLibrary_WIN32U_INCLUDED +#define Foundation_SharedLibrary_WIN32U_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Mutex.h" + + +namespace Poco { + + +class Foundation_API SharedLibraryImpl +{ +protected: + SharedLibraryImpl(); + ~SharedLibraryImpl(); + void loadImpl(const std::string& path); + void unloadImpl(); + bool isLoadedImpl() const; + void* findSymbolImpl(const std::string& name); + const std::string& getPathImpl() const; + static std::string suffixImpl(); + +private: + std::string _path; + void* _handle; + static FastMutex _mutex; +}; + + +} // namespace Poco + + +#endif // Foundation_SharedLibrary_WIN32U_INCLUDED diff --git a/Foundation/include/Poco/SharedPtr.h b/Foundation/include/Poco/SharedPtr.h index fa8156d2b..5a082b04f 100644 --- a/Foundation/include/Poco/SharedPtr.h +++ b/Foundation/include/Poco/SharedPtr.h @@ -1,370 +1,370 @@ -// -// SharedPtr.h -// -// $Id: //poco/1.2/Foundation/include/Poco/SharedPtr.h#5 $ -// -// Library: Foundation -// Package: Core -// Module: SharedPtr -// -// Definition of the SharedPtr template class. -// -// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_SharedPtr_INCLUDED -#define Foundation_SharedPtr_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/Exception.h" -#include "Poco/Mutex.h" -#include - - -namespace Poco { - - -class ReferenceCounter - /// Simple ReferenceCounter object, does not delete itself when count reaches 0 -{ -public: - ReferenceCounter(): _cnt(1) - { - } - - void duplicate() - { - FastMutex::ScopedLock lock(_mutex); - ++_cnt; - } - - int release() - { - FastMutex::ScopedLock lock(_mutex); - return --_cnt; - } - -private: - FastMutex _mutex; - int _cnt; -}; - - -template -class SharedPtr - /// SharedPtr is a "smart" pointer for classes implementing - /// reference counting based garbage collection. - /// SharedPtr is thus similar to AutoPtr. Unlike the - /// AutoPtr template, which can only be used with - /// classes that support reference counting, SharedPtr - /// can be used with any class. For this to work, a - /// SharedPtr manages a reference count for the object - /// it manages. - /// - /// SharedPtr works in the following way: - /// If an SharedPtr is assigned an ordinary pointer to - /// an object (via the constructor or the assignment operator), - /// it takes ownership of the object and the object's reference - /// count is initialized to one. - /// If the SharedPtr is assigned another SharedPtr, the - /// object's reference count is incremented by one. - /// The destructor of SharedPtr decrements the object's - /// reference count by one and deletes the object if the - /// reference count reaches zero. - /// SharedPtr supports dereferencing with both the -> - /// and the * operator. An attempt to dereference a null - /// SharedPtr results in a NullPointerException being thrown. - /// SharedPtr also implements all relational operators and - /// a cast operator in case dynamic casting of the encapsulated data types - /// is required. -{ -public: - - SharedPtr(): _pCounter(new ReferenceCounter), _ptr(0) - { - } - - SharedPtr(C* ptr): _pCounter(new ReferenceCounter), _ptr(ptr) - { - } - - template - SharedPtr(const SharedPtr& ptr): _pCounter(ptr._pCounter), _ptr(const_cast(ptr.get())) - { - _pCounter->duplicate(); - } - - SharedPtr(const SharedPtr& ptr): _pCounter(ptr._pCounter), _ptr(ptr._ptr) - { - _pCounter->duplicate(); - } - - ~SharedPtr() - { - release(); - } - - SharedPtr& operator = (C* ptr) - { - if (get() != ptr) - { - ReferenceCounter* pTmp = new ReferenceCounter; - release(); - _pCounter = pTmp; - _ptr = ptr; - } - return *this; - } - - SharedPtr& operator = (const SharedPtr& ptr) - { - if (&ptr != this) - { - SharedPtr tmp(ptr); - swap(tmp); - } - return *this; - } - - template - SharedPtr& operator = (const SharedPtr& ptr) - { - if (ptr.get() != _ptr) - { - SharedPtr tmp(ptr); - swap(tmp); - } - return *this; - } - - template - SharedPtr cast() - /// Casts the SharedPtr via a dynamic cast to the given type. - /// Returns an SharedPtr containing NULL if the cast fails. - /// Example: (assume class Sub: public Super) - /// SharedPtr super(new Sub()); - /// SharedPtr sub = super.cast(); - /// poco_assert (sub.get()); - { - Other* pOther = dynamic_cast (_ptr); - if (pOther) - return SharedPtr (_pCounter, pOther); - return SharedPtr(); - } - - void swap(SharedPtr& ptr) - { - std::swap(_ptr, ptr._ptr); - std::swap(_pCounter, ptr._pCounter); - } - - C* operator -> () - { - return deref(); - } - - const C* operator -> () const - { - return deref(); - } - - C& operator * () - { - return *deref(); - } - - const C& operator * () const - { - return *deref(); - } - - C* get() - { - return _ptr; - } - - bool isNull() const - { - return _ptr == 0; - } - - operator C* () - { - return _ptr; - } - - operator const C* () const - { - return _ptr; - } - - const C* get() const - { - return _ptr; - } - - bool operator == (const SharedPtr& ptr) const - { - return get() == ptr.get(); - } - - bool operator == (const C* ptr) const - { - return get() == ptr; - } - - bool operator == (C* ptr) const - { - return get() == ptr; - } - - bool operator != (const SharedPtr& ptr) const - { - return get() != ptr.get(); - } - - bool operator != (const C* ptr) const - { - return get() != ptr; - } - - bool operator != (C* ptr) const - { - return get() != ptr; - } - - bool operator < (const SharedPtr& ptr) const - { - return get() < ptr.get(); - } - - bool operator < (const C* ptr) const - { - return get() < ptr; - } - - bool operator < (C* ptr) const - { - return get() < ptr; - } - - bool operator <= (const SharedPtr& ptr) const - { - return get() <= ptr.get(); - } - - bool operator <= (const C* ptr) const - { - return get() <= ptr; - } - - bool operator <= (C* ptr) const - { - return get() <= ptr; - } - - bool operator > (const SharedPtr& ptr) const - { - return get() > ptr.get(); - } - - bool operator > (const C* ptr) const - { - return get() > ptr; - } - - bool operator > (C* ptr) const - { - return get() > ptr; - } - - bool operator >= (const SharedPtr& ptr) const - { - return get() >= ptr.get(); - } - - bool operator >= (const C* ptr) const - { - return get() >= ptr; - } - - bool operator >= (C* ptr) const - { - return get() >= ptr; - } - -private: - C* deref() const - { - if (!_ptr) - throw NullPointerException(); - - return _ptr; - } - - void release() - { - poco_assert_dbg (_pCounter); - int i = _pCounter->release(); - if (i == 0) - { - if (_ptr) - delete _ptr; - _ptr = 0; - - delete _pCounter; - _pCounter = 0; - } - } - - SharedPtr(ReferenceCounter* pCounter, C* ptr): _pCounter(pCounter), _ptr(ptr) - /// for cast operation - { - poco_assert_dbg (_pCounter); - _pCounter->duplicate(); - } - -private: - ReferenceCounter* _pCounter; - C* _ptr; - - template friend class SharedPtr; -}; - - -template -inline void swap(SharedPtr& p1, SharedPtr& p2) -{ - p1.swap(p2); -} - - -} // namespace Poco - - -#endif // Foundation_SharedPtr_INCLUDED +// +// SharedPtr.h +// +// $Id: //poco/1.2/Foundation/include/Poco/SharedPtr.h#5 $ +// +// Library: Foundation +// Package: Core +// Module: SharedPtr +// +// Definition of the SharedPtr template class. +// +// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_SharedPtr_INCLUDED +#define Foundation_SharedPtr_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Exception.h" +#include "Poco/Mutex.h" +#include + + +namespace Poco { + + +class ReferenceCounter + /// Simple ReferenceCounter object, does not delete itself when count reaches 0 +{ +public: + ReferenceCounter(): _cnt(1) + { + } + + void duplicate() + { + FastMutex::ScopedLock lock(_mutex); + ++_cnt; + } + + int release() + { + FastMutex::ScopedLock lock(_mutex); + return --_cnt; + } + +private: + FastMutex _mutex; + int _cnt; +}; + + +template +class SharedPtr + /// SharedPtr is a "smart" pointer for classes implementing + /// reference counting based garbage collection. + /// SharedPtr is thus similar to AutoPtr. Unlike the + /// AutoPtr template, which can only be used with + /// classes that support reference counting, SharedPtr + /// can be used with any class. For this to work, a + /// SharedPtr manages a reference count for the object + /// it manages. + /// + /// SharedPtr works in the following way: + /// If an SharedPtr is assigned an ordinary pointer to + /// an object (via the constructor or the assignment operator), + /// it takes ownership of the object and the object's reference + /// count is initialized to one. + /// If the SharedPtr is assigned another SharedPtr, the + /// object's reference count is incremented by one. + /// The destructor of SharedPtr decrements the object's + /// reference count by one and deletes the object if the + /// reference count reaches zero. + /// SharedPtr supports dereferencing with both the -> + /// and the * operator. An attempt to dereference a null + /// SharedPtr results in a NullPointerException being thrown. + /// SharedPtr also implements all relational operators and + /// a cast operator in case dynamic casting of the encapsulated data types + /// is required. +{ +public: + + SharedPtr(): _pCounter(new ReferenceCounter), _ptr(0) + { + } + + SharedPtr(C* ptr): _pCounter(new ReferenceCounter), _ptr(ptr) + { + } + + template + SharedPtr(const SharedPtr& ptr): _pCounter(ptr._pCounter), _ptr(const_cast(ptr.get())) + { + _pCounter->duplicate(); + } + + SharedPtr(const SharedPtr& ptr): _pCounter(ptr._pCounter), _ptr(ptr._ptr) + { + _pCounter->duplicate(); + } + + ~SharedPtr() + { + release(); + } + + SharedPtr& operator = (C* ptr) + { + if (get() != ptr) + { + ReferenceCounter* pTmp = new ReferenceCounter; + release(); + _pCounter = pTmp; + _ptr = ptr; + } + return *this; + } + + SharedPtr& operator = (const SharedPtr& ptr) + { + if (&ptr != this) + { + SharedPtr tmp(ptr); + swap(tmp); + } + return *this; + } + + template + SharedPtr& operator = (const SharedPtr& ptr) + { + if (ptr.get() != _ptr) + { + SharedPtr tmp(ptr); + swap(tmp); + } + return *this; + } + + template + SharedPtr cast() + /// Casts the SharedPtr via a dynamic cast to the given type. + /// Returns an SharedPtr containing NULL if the cast fails. + /// Example: (assume class Sub: public Super) + /// SharedPtr super(new Sub()); + /// SharedPtr sub = super.cast(); + /// poco_assert (sub.get()); + { + Other* pOther = dynamic_cast (_ptr); + if (pOther) + return SharedPtr (_pCounter, pOther); + return SharedPtr(); + } + + void swap(SharedPtr& ptr) + { + std::swap(_ptr, ptr._ptr); + std::swap(_pCounter, ptr._pCounter); + } + + C* operator -> () + { + return deref(); + } + + const C* operator -> () const + { + return deref(); + } + + C& operator * () + { + return *deref(); + } + + const C& operator * () const + { + return *deref(); + } + + C* get() + { + return _ptr; + } + + bool isNull() const + { + return _ptr == 0; + } + + operator C* () + { + return _ptr; + } + + operator const C* () const + { + return _ptr; + } + + const C* get() const + { + return _ptr; + } + + bool operator == (const SharedPtr& ptr) const + { + return get() == ptr.get(); + } + + bool operator == (const C* ptr) const + { + return get() == ptr; + } + + bool operator == (C* ptr) const + { + return get() == ptr; + } + + bool operator != (const SharedPtr& ptr) const + { + return get() != ptr.get(); + } + + bool operator != (const C* ptr) const + { + return get() != ptr; + } + + bool operator != (C* ptr) const + { + return get() != ptr; + } + + bool operator < (const SharedPtr& ptr) const + { + return get() < ptr.get(); + } + + bool operator < (const C* ptr) const + { + return get() < ptr; + } + + bool operator < (C* ptr) const + { + return get() < ptr; + } + + bool operator <= (const SharedPtr& ptr) const + { + return get() <= ptr.get(); + } + + bool operator <= (const C* ptr) const + { + return get() <= ptr; + } + + bool operator <= (C* ptr) const + { + return get() <= ptr; + } + + bool operator > (const SharedPtr& ptr) const + { + return get() > ptr.get(); + } + + bool operator > (const C* ptr) const + { + return get() > ptr; + } + + bool operator > (C* ptr) const + { + return get() > ptr; + } + + bool operator >= (const SharedPtr& ptr) const + { + return get() >= ptr.get(); + } + + bool operator >= (const C* ptr) const + { + return get() >= ptr; + } + + bool operator >= (C* ptr) const + { + return get() >= ptr; + } + +private: + C* deref() const + { + if (!_ptr) + throw NullPointerException(); + + return _ptr; + } + + void release() + { + poco_assert_dbg (_pCounter); + int i = _pCounter->release(); + if (i == 0) + { + if (_ptr) + delete _ptr; + _ptr = 0; + + delete _pCounter; + _pCounter = 0; + } + } + + SharedPtr(ReferenceCounter* pCounter, C* ptr): _pCounter(pCounter), _ptr(ptr) + /// for cast operation + { + poco_assert_dbg (_pCounter); + _pCounter->duplicate(); + } + +private: + ReferenceCounter* _pCounter; + C* _ptr; + + template friend class SharedPtr; +}; + + +template +inline void swap(SharedPtr& p1, SharedPtr& p2) +{ + p1.swap(p2); +} + + +} // namespace Poco + + +#endif // Foundation_SharedPtr_INCLUDED diff --git a/Foundation/include/Poco/SignalHandler.h b/Foundation/include/Poco/SignalHandler.h index 83941d0ec..36476274e 100644 --- a/Foundation/include/Poco/SignalHandler.h +++ b/Foundation/include/Poco/SignalHandler.h @@ -1,144 +1,144 @@ -// -// SignalHandler.h -// -// $Id: //poco/1.2/Foundation/include/Poco/SignalHandler.h#1 $ -// -// Library: Foundation -// Package: Threading -// Module: SignalHandler -// -// Definition of the SignalHandler class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_SignalHandler_INCLUDED -#define Foundation_SignalHandler_INCLUDED - - -#include "Poco/Foundation.h" - - -#if defined(POCO_OS_FAMILY_UNIX) - - -#include -#include - - -namespace Poco { - - -class Foundation_API SignalHandler - /// This helper class simplifies the handling of POSIX signals. - /// - /// The class provides a signal handler (installed with - /// installHandlers()) that translates certain POSIX - /// signals (SIGILL, SIGBUS, SIGSEGV, SIGSYS) into - /// C++ exceptions. - /// - /// Internally, a stack of sigjmp_buf structs is maintained for - /// each thread. The constructor pushes a new sigjmp_buf onto - /// the current thread's stack. The destructor pops the sigjmp_buf - /// from the stack. - /// - /// The poco_throw_on_signal macro creates an instance of SignalHandler - /// on the stack, which results in a new sigjmp_buf being created. - /// The sigjmp_buf is then set-up with sigsetjmp(). - /// - /// The handleSignal() method, which is invoked when a signal arrives, - /// checks if a sigjmp_buf is available for the current thread. - /// If so, siglongjmp() is used to jump out of the signal handler. - /// - /// Typical usage is as follows: - /// - /// try - /// { - /// poco_throw_on_signal; - /// ... - /// } - /// catch (Poco::SignalException&) - /// { - /// ... - /// } - /// - /// The best way to deal with a SignalException is to log as much context - /// information as possible, to aid in debugging, and then to exit. -{ -public: - SignalHandler(); - /// Creates the SignalHandler. - - ~SignalHandler(); - /// Destroys the SignalHandler. - - sigjmp_buf& jumpBuffer(); - /// Returns the top-most sigjmp_buf for the current thread. - - static void throwSignalException(int sig); - /// Throws a SignalException with a textual description - /// of the given signal as argument. - - static void install(); - /// Installs signal handlers for SIGILL, SIGBUS, SIGSEGV - /// and SIGSYS. - -protected: - static void handleSignal(int sig); - /// The actual signal handler. - - struct JumpBuffer - /// sigjmp_buf cannot be used to instantiate a std::vector, - /// so we provide a wrapper struct. - { - sigjmp_buf buf; - }; - typedef std::vector JumpBufferVec; - - static JumpBufferVec& jumpBufferVec(); - /// Returns the JumpBufferVec for the current thread. - -private: - static JumpBufferVec _jumpBufferVec; - - friend class ThreadImpl; -}; - - -#define poco_throw_on_signal \ - Poco::SignalHandler _poco_signalHandler; \ - int _poco_signal = sigsetjmp(_poco_signalHandler.jumpBuffer(), 1); \ - if (_poco_signal) _poco_signalHandler.throwSignalException(_poco_signal); - - -} // namespace Poco - - -#endif // POCO_OS_FAMILY_UNIX - - -#endif // Foundation_SignalHandler_INCLUDED +// +// SignalHandler.h +// +// $Id: //poco/1.2/Foundation/include/Poco/SignalHandler.h#1 $ +// +// Library: Foundation +// Package: Threading +// Module: SignalHandler +// +// Definition of the SignalHandler class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_SignalHandler_INCLUDED +#define Foundation_SignalHandler_INCLUDED + + +#include "Poco/Foundation.h" + + +#if defined(POCO_OS_FAMILY_UNIX) + + +#include +#include + + +namespace Poco { + + +class Foundation_API SignalHandler + /// This helper class simplifies the handling of POSIX signals. + /// + /// The class provides a signal handler (installed with + /// installHandlers()) that translates certain POSIX + /// signals (SIGILL, SIGBUS, SIGSEGV, SIGSYS) into + /// C++ exceptions. + /// + /// Internally, a stack of sigjmp_buf structs is maintained for + /// each thread. The constructor pushes a new sigjmp_buf onto + /// the current thread's stack. The destructor pops the sigjmp_buf + /// from the stack. + /// + /// The poco_throw_on_signal macro creates an instance of SignalHandler + /// on the stack, which results in a new sigjmp_buf being created. + /// The sigjmp_buf is then set-up with sigsetjmp(). + /// + /// The handleSignal() method, which is invoked when a signal arrives, + /// checks if a sigjmp_buf is available for the current thread. + /// If so, siglongjmp() is used to jump out of the signal handler. + /// + /// Typical usage is as follows: + /// + /// try + /// { + /// poco_throw_on_signal; + /// ... + /// } + /// catch (Poco::SignalException&) + /// { + /// ... + /// } + /// + /// The best way to deal with a SignalException is to log as much context + /// information as possible, to aid in debugging, and then to exit. +{ +public: + SignalHandler(); + /// Creates the SignalHandler. + + ~SignalHandler(); + /// Destroys the SignalHandler. + + sigjmp_buf& jumpBuffer(); + /// Returns the top-most sigjmp_buf for the current thread. + + static void throwSignalException(int sig); + /// Throws a SignalException with a textual description + /// of the given signal as argument. + + static void install(); + /// Installs signal handlers for SIGILL, SIGBUS, SIGSEGV + /// and SIGSYS. + +protected: + static void handleSignal(int sig); + /// The actual signal handler. + + struct JumpBuffer + /// sigjmp_buf cannot be used to instantiate a std::vector, + /// so we provide a wrapper struct. + { + sigjmp_buf buf; + }; + typedef std::vector JumpBufferVec; + + static JumpBufferVec& jumpBufferVec(); + /// Returns the JumpBufferVec for the current thread. + +private: + static JumpBufferVec _jumpBufferVec; + + friend class ThreadImpl; +}; + + +#define poco_throw_on_signal \ + Poco::SignalHandler _poco_signalHandler; \ + int _poco_signal = sigsetjmp(_poco_signalHandler.jumpBuffer(), 1); \ + if (_poco_signal) _poco_signalHandler.throwSignalException(_poco_signal); + + +} // namespace Poco + + +#endif // POCO_OS_FAMILY_UNIX + + +#endif // Foundation_SignalHandler_INCLUDED diff --git a/Foundation/include/Poco/SimpleFileChannel.h b/Foundation/include/Poco/SimpleFileChannel.h index 09f04d8d4..288652d6c 100644 --- a/Foundation/include/Poco/SimpleFileChannel.h +++ b/Foundation/include/Poco/SimpleFileChannel.h @@ -1,156 +1,156 @@ -// -// SimpleFileChannel.h -// -// $Id: //poco/1.2/Foundation/include/Poco/SimpleFileChannel.h#1 $ -// -// Library: Foundation -// Package: Logging -// Module: SimpleFileChannel -// -// Definition of the SimpleFileChannel class. -// -// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_SimpleFileChannel_INCLUDED -#define Foundation_SimpleFileChannel_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/Channel.h" -#include "Poco/Timestamp.h" -#include "Poco/Mutex.h" - - -namespace Poco { - - -class LogFile; - - -class Foundation_API SimpleFileChannel: public Channel - /// A Channel that writes to a file. This class only - /// supports simple log file rotation. - /// - /// For more features, see the FileChannel class. - /// - /// Only the message's text is written, followed - /// by a newline. - /// - /// Chain this channel to a FormattingChannel with an - /// appropriate Formatter to control what is in the text. - /// - /// Log file rotation based on log file size is supported. - /// - /// If rotation is enabled, the SimpleFileChannel will - /// alternate between two log files. If the size of - /// the primary log file exceeds a specified limit, - /// the secondary log file will be used, and vice - /// versa. - /// - /// Log rotation is configured with the "rotation" - /// property, which supports the following values: - /// * never: no log rotation - /// * : the file is rotated when its size exceeds - /// bytes. - /// * K: the file is rotated when its size exceeds - /// Kilobytes. - /// * M: the file is rotated when its size exceeds - /// Megabytes. - /// - /// The path of the (primary) log file can be specified with - /// the "path" property. Optionally, the path of the secondary - /// log file can be specified with the "secondaryPath" property. - /// - /// If no secondary path is specified, the secondary path will - /// default to .1. -{ -public: - SimpleFileChannel(); - /// Creates the FileChannel. - - SimpleFileChannel(const std::string& path); - /// Creates the FileChannel for a file with the given path. - - void open(); - /// Opens the FileChannel and creates the log file if necessary. - - void close(); - /// Closes the FileChannel. - - void log(const Message& msg); - /// Logs the given message to the file. - - void setProperty(const std::string& name, const std::string& value); - /// Sets the property with the given name. - /// - /// The following properties are supported: - /// * path: The primary log file's path. - /// * secondaryPath: The secondary log file's path. - /// * rotation: The log file's rotation mode. See the - /// SimpleFileChannel class for details. - - std::string getProperty(const std::string& name) const; - /// Returns the value of the property with the given name. - /// See setProperty() for a description of the supported - /// properties. - - Timestamp creationDate() const; - /// Returns the log file's creation date. - - UInt64 size() const; - /// Returns the log file's current size in bytes. - - const std::string& path() const; - /// Returns the log file's primary path. - - const std::string& secondaryPath() const; - /// Returns the log file's secondary path. - - static const std::string PROP_PATH; - static const std::string PROP_SECONDARYPATH; - static const std::string PROP_ROTATION; - -protected: - ~SimpleFileChannel(); - void setRotation(const std::string& rotation); - void rotate(); - -private: - std::string _path; - std::string _secondaryPath; - std::string _rotation; - UInt64 _limit; - LogFile* _pFile; - FastMutex _mutex; -}; - - -} // namespace Poco - - -#endif // Foundation_SimpleFileChannel_INCLUDED +// +// SimpleFileChannel.h +// +// $Id: //poco/1.2/Foundation/include/Poco/SimpleFileChannel.h#1 $ +// +// Library: Foundation +// Package: Logging +// Module: SimpleFileChannel +// +// Definition of the SimpleFileChannel class. +// +// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_SimpleFileChannel_INCLUDED +#define Foundation_SimpleFileChannel_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Channel.h" +#include "Poco/Timestamp.h" +#include "Poco/Mutex.h" + + +namespace Poco { + + +class LogFile; + + +class Foundation_API SimpleFileChannel: public Channel + /// A Channel that writes to a file. This class only + /// supports simple log file rotation. + /// + /// For more features, see the FileChannel class. + /// + /// Only the message's text is written, followed + /// by a newline. + /// + /// Chain this channel to a FormattingChannel with an + /// appropriate Formatter to control what is in the text. + /// + /// Log file rotation based on log file size is supported. + /// + /// If rotation is enabled, the SimpleFileChannel will + /// alternate between two log files. If the size of + /// the primary log file exceeds a specified limit, + /// the secondary log file will be used, and vice + /// versa. + /// + /// Log rotation is configured with the "rotation" + /// property, which supports the following values: + /// * never: no log rotation + /// * : the file is rotated when its size exceeds + /// bytes. + /// * K: the file is rotated when its size exceeds + /// Kilobytes. + /// * M: the file is rotated when its size exceeds + /// Megabytes. + /// + /// The path of the (primary) log file can be specified with + /// the "path" property. Optionally, the path of the secondary + /// log file can be specified with the "secondaryPath" property. + /// + /// If no secondary path is specified, the secondary path will + /// default to .1. +{ +public: + SimpleFileChannel(); + /// Creates the FileChannel. + + SimpleFileChannel(const std::string& path); + /// Creates the FileChannel for a file with the given path. + + void open(); + /// Opens the FileChannel and creates the log file if necessary. + + void close(); + /// Closes the FileChannel. + + void log(const Message& msg); + /// Logs the given message to the file. + + void setProperty(const std::string& name, const std::string& value); + /// Sets the property with the given name. + /// + /// The following properties are supported: + /// * path: The primary log file's path. + /// * secondaryPath: The secondary log file's path. + /// * rotation: The log file's rotation mode. See the + /// SimpleFileChannel class for details. + + std::string getProperty(const std::string& name) const; + /// Returns the value of the property with the given name. + /// See setProperty() for a description of the supported + /// properties. + + Timestamp creationDate() const; + /// Returns the log file's creation date. + + UInt64 size() const; + /// Returns the log file's current size in bytes. + + const std::string& path() const; + /// Returns the log file's primary path. + + const std::string& secondaryPath() const; + /// Returns the log file's secondary path. + + static const std::string PROP_PATH; + static const std::string PROP_SECONDARYPATH; + static const std::string PROP_ROTATION; + +protected: + ~SimpleFileChannel(); + void setRotation(const std::string& rotation); + void rotate(); + +private: + std::string _path; + std::string _secondaryPath; + std::string _rotation; + UInt64 _limit; + LogFile* _pFile; + FastMutex _mutex; +}; + + +} // namespace Poco + + +#endif // Foundation_SimpleFileChannel_INCLUDED diff --git a/Foundation/include/Poco/SimpleHashTable.h b/Foundation/include/Poco/SimpleHashTable.h index 40c9ec248..6c8f05fa5 100644 --- a/Foundation/include/Poco/SimpleHashTable.h +++ b/Foundation/include/Poco/SimpleHashTable.h @@ -1,407 +1,407 @@ -// -// SimpleHashTable.h -// -// $Id: //poco/1.2/Foundation/include/Poco/SimpleHashTable.h#2 $ -// -// Library: Foundation -// Package: Core -// Module: SimpleHashTable -// -// Definition of the SimpleHashTable class. -// -// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_SimpleHashTable_INCLUDED -#define Foundation_SimpleHashTable_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/Exception.h" -#include "Poco/HashFunction.h" -#include "Poco/HashStatistic.h" -#include -#include -#include - - -namespace Poco { - - -template< class Key, class Value, class KeyHashFunction = HashFunction< Key> > -class SimpleHashTable - /// A SimpleHashTable stores a key value pair that can be looked up via a hashed key. - /// - /// In comparision to a HashTable, this class handles collisions by sequentially searching the next - /// free location. This also means that the maximum size of this table is limited, i.e. if the hash table - /// is full, it will throw an exception and that this class does not support remove operations. - /// On the plus side it is faster than the HashTable. - /// - /// This class is NOT thread safe. -{ -public: - class HashEntry - { - public: - Key key; - Value value; - HashEntry(const Key k, const Value v): - key(k), - value(v) - { - } - }; - - typedef HashEntry** HashTableVector; - - SimpleHashTable(UInt32 initialSize = 251): _entries(0), _size(0), _maxCapacity(initialSize) - /// Creates the SimpleHashTable. - { - _entries = new HashEntry*[initialSize]; - memset(_entries, '\0', sizeof(HashEntry*)*initialSize); - } - - SimpleHashTable(const SimpleHashTable& ht): - _entries (new HashEntry*[ht._maxCapacity]), - _size(ht._size), - _maxCapacity(ht._maxCapacity) - { - for (int i = 0; i < _maxCapacity; ++i) - { - if (ht._entries[i]) - _entries[i] = new HashEntry(*ht._entries[i]); - else - _entries[i] = 0; - } - } - - ~SimpleHashTable() - /// Destroys the SimpleHashTable. - { - clear(); - } - - SimpleHashTable& operator = (const SimpleHashTable& ht) - { - if (this != &ht) - { - clear(); - _maxCapacity = ht._maxCapacity; - delete[] _entries; - _entries = new HashEntry*[_maxCapacity]; - _size = ht._size; - - for (int i = 0; i < _maxCapacity; ++i) - { - if (ht._entries[i]) - _entries[i] = new HashEntry(*ht._entries[i]); - else - _entries[i] = 0; - } - } - return *this; - } - - void clear() - { - if (!_entries) - return; - for (int i = 0; i < _maxCapacity; ++i) - { - if (_entries[i]) - delete _entries[i]; - } - delete[] _entries; - _entries = 0; - _size = 0; - _maxCapacity = 0; - } - - UInt32 insert(const Key& key, const Value& value) - /// Returns the hash value of the inserted item. - /// Throws an exception if the entry was already inserted - { - UInt32 hsh = hash(key); - insertRaw(key, hsh, value); - return hsh; - } - - void insertRaw(const Key& key, UInt32 hsh, const Value& value) - /// Returns the hash value of the inserted item. - /// Throws an exception if the entry was already inserted - { - if (!_entries[hsh]) - _entries[hsh] = new HashEntry(key, value); - else - { - UInt32 origHash = hsh; - while (_entries[hsh % _maxCapacity]) - { - poco_assert_dbg(_entries[hsh % _maxCapacity]->key != key); - if (hsh - origHash > _maxCapacity) - throw PoolOverflowException("SimpleHashTable full"); - hsh++; - } - _entries[hsh % _maxCapacity] = new HashEntry(key, value); - } - _size++; - } - - UInt32 update(const Key& key, const Value& value) - /// Returns the hash value of the inserted item. - /// Replaces an existing entry if it finds one - { - UInt32 hsh = hash(key); - updateRaw(key, hsh, value); - return hsh; - } - - void updateRaw(const Key& key, UInt32 hsh, const Value& value) - /// Returns the hash value of the inserted item. - /// Replaces an existing entry if it finds one - { - if (!_entries[hsh]) - _entries[hsh] = new HashEntry(key, value); - else - { - UInt32 origHash = hsh; - while (_entries[hsh % _maxCapacity]) - { - if (_entries[hsh % _maxCapacity]->key == key) - { - _entries[hsh % _maxCapacity]->value = value; - return; - } - if (hsh - origHash > _maxCapacity) - throw PoolOverflowException("SimpleHashTable full"); - hsh++; - } - _entries[hsh % _maxCapacity] = new HashEntry(key, value); - } - _size++; - } - - UInt32 hash(const Key& key) const - { - return KeyHashFunction::hash(key, _maxCapacity); - } - - const Value& get(const Key& key) const - /// Throws an exception if the value does not exist - { - UInt32 hsh = hash(key); - return getRaw(key, hsh); - } - - const Value& getRaw(const Key& key, UInt32 hsh) const - /// Throws an exception if the value does not exist - { - UInt32 origHash = hsh; - while (true) - { - if (_entries[hsh % _maxCapacity]) - { - if (_entries[hsh % _maxCapacity]->key == key) - { - return _entries[hsh % _maxCapacity]->value; - } - } - else - throw InvalidArgumentException("value not found"); - if (hsh - origHash > _maxCapacity) - throw InvalidArgumentException("value not found"); - hsh++; - } - } - - const Key& getKeyRaw(const Key& key, UInt32 hsh) - /// Throws an exception if the key does not exist. returns a reference to the internally - /// stored key. Useful when someone does an insert and wants for performance reason only to store - /// a pointer to the key in another collection - { - UInt32 origHash = hsh; - while (true) - { - if (_entries[hsh % _maxCapacity]) - { - if (_entries[hsh % _maxCapacity]->key == key) - { - return _entries[hsh % _maxCapacity]->key; - } - } - else - throw InvalidArgumentException("key not found"); - - if (hsh - origHash > _maxCapacity) - throw InvalidArgumentException("key not found"); - hsh++; - } - } - - bool get(const Key& key, Value& v) const - /// Sets v to the found value, returns false if no value was found - { - UInt32 hsh = hash(key); - return getRaw(key, hsh, v); - } - - bool getRaw(const Key& key, UInt32 hsh, Value& v) const - /// Sets v to the found value, returns false if no value was found - { - UInt32 origHash = hsh; - while (true) - { - if (_entries[hsh % _maxCapacity]) - { - if (_entries[hsh % _maxCapacity]->key == key) - { - v = _entries[hsh % _maxCapacity]->value; - return true; - } - } - else - return false; - if (hsh - origHash > _maxCapacity) - return false; - hsh++; - } - } - - bool exists(const Key& key) - { - UInt32 hsh = hash(key); - return existsRaw(key, hsh); - } - - bool existsRaw(const Key& key, UInt32 hsh) - { - UInt32 origHash = hsh; - while (true) - { - if (_entries[hsh % _maxCapacity]) - { - if (_entries[hsh % _maxCapacity]->key == key) - { - return true; - } - } - else - return false; - if (hsh - origHash > _maxCapacity) - return false; - hsh++; - } - } - - size_t size() const - /// Returns the number of elements already inserted into the SimpleHashTable - { - return _size; - } - - UInt32 maxCapacity() const - { - return _maxCapacity; - } - - void resize(UInt32 newSize) - /// Resizes the hashtable, rehashes all existing entries. Expensive! - { - if (_maxCapacity != newSize) - { - HashTableVector cpy = _entries; - _entries = 0; - UInt32 oldSize = _maxCapacity; - _maxCapacity = newSize; - _entries = new HashEntry*[_maxCapacity]; - memset(_entries, '\0', sizeof(HashEntry*)*_maxCapacity); - - if (_size == 0) - { - // no data was yet inserted - delete[] cpy; - return; - } - _size = 0; - for (int i=0; i < oldSize; ++i) - { - if (cpy[i]) - { - insert(cpy[i]->key, cpy[i]->value); - delete cpy[i]; - } - } - delete[] cpy; - } - } - - HashStatistic currentState(bool details = false) const - /// Returns the current internal state - { - UInt32 numberOfEntries = (UInt32)_size; - UInt32 numZeroEntries = 0; - UInt32 maxEntriesPerHash = 0; - std::vector detailedEntriesPerHash; - #ifdef _DEBUG - UInt32 totalSize = 0; - #endif - for (int i=0; i < _maxCapacity; ++i) - { - if (_entries[i]) - { - maxEntriesPerHash = 1; - UInt32 size = 1; - if (details) - detailedEntriesPerHash.push_back(size); - #ifdef DEBUG - totalSize += size; - #endif - } - else - { - numZeroEntries++; - if (details) - detailedEntriesPerHash.push_back(0); - } - } - #ifdef DEBUG - poco_assert_dbg(totalSize == numberOfEntries); - #endif - return HashStatistic(_maxCapacity, numberOfEntries, numZeroEntries, maxEntriesPerHash, detailedEntriesPerHash); - } - -private: - HashTableVector _entries; - size_t _size; - UInt32 _maxCapacity; -}; - - -} // namespace Poco - - -#endif // Foundation_HashTable_INCLUDED +// +// SimpleHashTable.h +// +// $Id: //poco/1.2/Foundation/include/Poco/SimpleHashTable.h#2 $ +// +// Library: Foundation +// Package: Core +// Module: SimpleHashTable +// +// Definition of the SimpleHashTable class. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_SimpleHashTable_INCLUDED +#define Foundation_SimpleHashTable_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Exception.h" +#include "Poco/HashFunction.h" +#include "Poco/HashStatistic.h" +#include +#include +#include + + +namespace Poco { + + +template< class Key, class Value, class KeyHashFunction = HashFunction< Key> > +class SimpleHashTable + /// A SimpleHashTable stores a key value pair that can be looked up via a hashed key. + /// + /// In comparision to a HashTable, this class handles collisions by sequentially searching the next + /// free location. This also means that the maximum size of this table is limited, i.e. if the hash table + /// is full, it will throw an exception and that this class does not support remove operations. + /// On the plus side it is faster than the HashTable. + /// + /// This class is NOT thread safe. +{ +public: + class HashEntry + { + public: + Key key; + Value value; + HashEntry(const Key k, const Value v): + key(k), + value(v) + { + } + }; + + typedef HashEntry** HashTableVector; + + SimpleHashTable(UInt32 initialSize = 251): _entries(0), _size(0), _maxCapacity(initialSize) + /// Creates the SimpleHashTable. + { + _entries = new HashEntry*[initialSize]; + memset(_entries, '\0', sizeof(HashEntry*)*initialSize); + } + + SimpleHashTable(const SimpleHashTable& ht): + _entries (new HashEntry*[ht._maxCapacity]), + _size(ht._size), + _maxCapacity(ht._maxCapacity) + { + for (int i = 0; i < _maxCapacity; ++i) + { + if (ht._entries[i]) + _entries[i] = new HashEntry(*ht._entries[i]); + else + _entries[i] = 0; + } + } + + ~SimpleHashTable() + /// Destroys the SimpleHashTable. + { + clear(); + } + + SimpleHashTable& operator = (const SimpleHashTable& ht) + { + if (this != &ht) + { + clear(); + _maxCapacity = ht._maxCapacity; + delete[] _entries; + _entries = new HashEntry*[_maxCapacity]; + _size = ht._size; + + for (int i = 0; i < _maxCapacity; ++i) + { + if (ht._entries[i]) + _entries[i] = new HashEntry(*ht._entries[i]); + else + _entries[i] = 0; + } + } + return *this; + } + + void clear() + { + if (!_entries) + return; + for (int i = 0; i < _maxCapacity; ++i) + { + if (_entries[i]) + delete _entries[i]; + } + delete[] _entries; + _entries = 0; + _size = 0; + _maxCapacity = 0; + } + + UInt32 insert(const Key& key, const Value& value) + /// Returns the hash value of the inserted item. + /// Throws an exception if the entry was already inserted + { + UInt32 hsh = hash(key); + insertRaw(key, hsh, value); + return hsh; + } + + void insertRaw(const Key& key, UInt32 hsh, const Value& value) + /// Returns the hash value of the inserted item. + /// Throws an exception if the entry was already inserted + { + if (!_entries[hsh]) + _entries[hsh] = new HashEntry(key, value); + else + { + UInt32 origHash = hsh; + while (_entries[hsh % _maxCapacity]) + { + poco_assert_dbg(_entries[hsh % _maxCapacity]->key != key); + if (hsh - origHash > _maxCapacity) + throw PoolOverflowException("SimpleHashTable full"); + hsh++; + } + _entries[hsh % _maxCapacity] = new HashEntry(key, value); + } + _size++; + } + + UInt32 update(const Key& key, const Value& value) + /// Returns the hash value of the inserted item. + /// Replaces an existing entry if it finds one + { + UInt32 hsh = hash(key); + updateRaw(key, hsh, value); + return hsh; + } + + void updateRaw(const Key& key, UInt32 hsh, const Value& value) + /// Returns the hash value of the inserted item. + /// Replaces an existing entry if it finds one + { + if (!_entries[hsh]) + _entries[hsh] = new HashEntry(key, value); + else + { + UInt32 origHash = hsh; + while (_entries[hsh % _maxCapacity]) + { + if (_entries[hsh % _maxCapacity]->key == key) + { + _entries[hsh % _maxCapacity]->value = value; + return; + } + if (hsh - origHash > _maxCapacity) + throw PoolOverflowException("SimpleHashTable full"); + hsh++; + } + _entries[hsh % _maxCapacity] = new HashEntry(key, value); + } + _size++; + } + + UInt32 hash(const Key& key) const + { + return KeyHashFunction::hash(key, _maxCapacity); + } + + const Value& get(const Key& key) const + /// Throws an exception if the value does not exist + { + UInt32 hsh = hash(key); + return getRaw(key, hsh); + } + + const Value& getRaw(const Key& key, UInt32 hsh) const + /// Throws an exception if the value does not exist + { + UInt32 origHash = hsh; + while (true) + { + if (_entries[hsh % _maxCapacity]) + { + if (_entries[hsh % _maxCapacity]->key == key) + { + return _entries[hsh % _maxCapacity]->value; + } + } + else + throw InvalidArgumentException("value not found"); + if (hsh - origHash > _maxCapacity) + throw InvalidArgumentException("value not found"); + hsh++; + } + } + + const Key& getKeyRaw(const Key& key, UInt32 hsh) + /// Throws an exception if the key does not exist. returns a reference to the internally + /// stored key. Useful when someone does an insert and wants for performance reason only to store + /// a pointer to the key in another collection + { + UInt32 origHash = hsh; + while (true) + { + if (_entries[hsh % _maxCapacity]) + { + if (_entries[hsh % _maxCapacity]->key == key) + { + return _entries[hsh % _maxCapacity]->key; + } + } + else + throw InvalidArgumentException("key not found"); + + if (hsh - origHash > _maxCapacity) + throw InvalidArgumentException("key not found"); + hsh++; + } + } + + bool get(const Key& key, Value& v) const + /// Sets v to the found value, returns false if no value was found + { + UInt32 hsh = hash(key); + return getRaw(key, hsh, v); + } + + bool getRaw(const Key& key, UInt32 hsh, Value& v) const + /// Sets v to the found value, returns false if no value was found + { + UInt32 origHash = hsh; + while (true) + { + if (_entries[hsh % _maxCapacity]) + { + if (_entries[hsh % _maxCapacity]->key == key) + { + v = _entries[hsh % _maxCapacity]->value; + return true; + } + } + else + return false; + if (hsh - origHash > _maxCapacity) + return false; + hsh++; + } + } + + bool exists(const Key& key) + { + UInt32 hsh = hash(key); + return existsRaw(key, hsh); + } + + bool existsRaw(const Key& key, UInt32 hsh) + { + UInt32 origHash = hsh; + while (true) + { + if (_entries[hsh % _maxCapacity]) + { + if (_entries[hsh % _maxCapacity]->key == key) + { + return true; + } + } + else + return false; + if (hsh - origHash > _maxCapacity) + return false; + hsh++; + } + } + + size_t size() const + /// Returns the number of elements already inserted into the SimpleHashTable + { + return _size; + } + + UInt32 maxCapacity() const + { + return _maxCapacity; + } + + void resize(UInt32 newSize) + /// Resizes the hashtable, rehashes all existing entries. Expensive! + { + if (_maxCapacity != newSize) + { + HashTableVector cpy = _entries; + _entries = 0; + UInt32 oldSize = _maxCapacity; + _maxCapacity = newSize; + _entries = new HashEntry*[_maxCapacity]; + memset(_entries, '\0', sizeof(HashEntry*)*_maxCapacity); + + if (_size == 0) + { + // no data was yet inserted + delete[] cpy; + return; + } + _size = 0; + for (int i=0; i < oldSize; ++i) + { + if (cpy[i]) + { + insert(cpy[i]->key, cpy[i]->value); + delete cpy[i]; + } + } + delete[] cpy; + } + } + + HashStatistic currentState(bool details = false) const + /// Returns the current internal state + { + UInt32 numberOfEntries = (UInt32)_size; + UInt32 numZeroEntries = 0; + UInt32 maxEntriesPerHash = 0; + std::vector detailedEntriesPerHash; + #ifdef _DEBUG + UInt32 totalSize = 0; + #endif + for (int i=0; i < _maxCapacity; ++i) + { + if (_entries[i]) + { + maxEntriesPerHash = 1; + UInt32 size = 1; + if (details) + detailedEntriesPerHash.push_back(size); + #ifdef DEBUG + totalSize += size; + #endif + } + else + { + numZeroEntries++; + if (details) + detailedEntriesPerHash.push_back(0); + } + } + #ifdef DEBUG + poco_assert_dbg(totalSize == numberOfEntries); + #endif + return HashStatistic(_maxCapacity, numberOfEntries, numZeroEntries, maxEntriesPerHash, detailedEntriesPerHash); + } + +private: + HashTableVector _entries; + size_t _size; + UInt32 _maxCapacity; +}; + + +} // namespace Poco + + +#endif // Foundation_HashTable_INCLUDED diff --git a/Foundation/include/Poco/SingletonHolder.h b/Foundation/include/Poco/SingletonHolder.h index d0c34af4f..83c074753 100644 --- a/Foundation/include/Poco/SingletonHolder.h +++ b/Foundation/include/Poco/SingletonHolder.h @@ -1,89 +1,89 @@ -// -// SingletonHolder.h -// -// $Id: //poco/1.2/Foundation/include/Poco/SingletonHolder.h#1 $ -// -// Library: Foundation -// Package: Core -// Module: SingletonHolder -// -// Definition of the SingletonHolder template. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_SingletonHolder_INCLUDED -#define Foundation_SingletonHolder_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/Mutex.h" - - -namespace Poco { - - -template -class SingletonHolder - /// This is a helper template class for managing - /// singleton objects allocated on the heap. - /// The class ensures proper deletion (including - /// calling of the destructor) of singleton objects - /// when the application that created them terminates. -{ -public: - SingletonHolder() - /// Creates the SingletonHolder. - { - _pS = 0; - } - ~SingletonHolder() - /// Destroys the SingletonHolder and the singleton - /// object that it holds. - { - delete _pS; - } - S* get() - /// Returns a pointer to the singleton object - /// hold by the SingletonHolder. The first call - /// to get will create the singleton. - { - FastMutex::ScopedLock lock(_m); - if (!_pS) _pS = new S; - return _pS; - } - -private: - S* _pS; - FastMutex _m; -}; - - -} // namespace Poco - - -#endif // Foundation_SingletonHolder_INCLUDED +// +// SingletonHolder.h +// +// $Id: //poco/1.2/Foundation/include/Poco/SingletonHolder.h#1 $ +// +// Library: Foundation +// Package: Core +// Module: SingletonHolder +// +// Definition of the SingletonHolder template. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_SingletonHolder_INCLUDED +#define Foundation_SingletonHolder_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Mutex.h" + + +namespace Poco { + + +template +class SingletonHolder + /// This is a helper template class for managing + /// singleton objects allocated on the heap. + /// The class ensures proper deletion (including + /// calling of the destructor) of singleton objects + /// when the application that created them terminates. +{ +public: + SingletonHolder() + /// Creates the SingletonHolder. + { + _pS = 0; + } + ~SingletonHolder() + /// Destroys the SingletonHolder and the singleton + /// object that it holds. + { + delete _pS; + } + S* get() + /// Returns a pointer to the singleton object + /// hold by the SingletonHolder. The first call + /// to get will create the singleton. + { + FastMutex::ScopedLock lock(_m); + if (!_pS) _pS = new S; + return _pS; + } + +private: + S* _pS; + FastMutex _m; +}; + + +} // namespace Poco + + +#endif // Foundation_SingletonHolder_INCLUDED diff --git a/Foundation/include/Poco/SplitterChannel.h b/Foundation/include/Poco/SplitterChannel.h index cff1e0a0f..840957884 100644 --- a/Foundation/include/Poco/SplitterChannel.h +++ b/Foundation/include/Poco/SplitterChannel.h @@ -1,99 +1,99 @@ -// -// SplitterChannel.h -// -// $Id: //poco/1.2/Foundation/include/Poco/SplitterChannel.h#2 $ -// -// Library: Foundation -// Package: Logging -// Module: SplitterChannel -// -// Definition of the SplitterChannel class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_SplitterChannel_INCLUDED -#define Foundation_SplitterChannel_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/Channel.h" -#include "Poco/Mutex.h" -#include - - -namespace Poco { - - -class Foundation_API SplitterChannel: public Channel - /// This channel sends a message to multiple - /// channels simultaneously. -{ -public: - SplitterChannel(); - /// Creates the SplitterChannel. - - void addChannel(Channel* pChannel); - /// Attaches a channel, which may not be null. - - void removeChannel(Channel* pChannel); - /// Removes a channel. - - void log(const Message& msg); - /// Sends the given Message to all - /// attaches channels. - - void setProperty(const std::string& name, const std::string& value); - /// Sets or changes a configuration property. - /// - /// Only the "channel" property is supported, which allows - /// adding a comma-separated list of channels via the LoggingRegistry. - /// The "channel" property is set-only. - /// To simplify file-based configuration, all property - /// names starting with "channel" are treated as "channel". - - void close(); - /// Removes all channels. - - int count() const; - /// Returns the number of channels in the SplitterChannel. - -protected: - ~SplitterChannel(); - -private: - typedef std::vector ChannelVec; - - ChannelVec _channels; - mutable FastMutex _mutex; -}; - - -} // namespace Poco - - -#endif // Foundation_SplitterChannel_INCLUDED +// +// SplitterChannel.h +// +// $Id: //poco/1.2/Foundation/include/Poco/SplitterChannel.h#2 $ +// +// Library: Foundation +// Package: Logging +// Module: SplitterChannel +// +// Definition of the SplitterChannel class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_SplitterChannel_INCLUDED +#define Foundation_SplitterChannel_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Channel.h" +#include "Poco/Mutex.h" +#include + + +namespace Poco { + + +class Foundation_API SplitterChannel: public Channel + /// This channel sends a message to multiple + /// channels simultaneously. +{ +public: + SplitterChannel(); + /// Creates the SplitterChannel. + + void addChannel(Channel* pChannel); + /// Attaches a channel, which may not be null. + + void removeChannel(Channel* pChannel); + /// Removes a channel. + + void log(const Message& msg); + /// Sends the given Message to all + /// attaches channels. + + void setProperty(const std::string& name, const std::string& value); + /// Sets or changes a configuration property. + /// + /// Only the "channel" property is supported, which allows + /// adding a comma-separated list of channels via the LoggingRegistry. + /// The "channel" property is set-only. + /// To simplify file-based configuration, all property + /// names starting with "channel" are treated as "channel". + + void close(); + /// Removes all channels. + + int count() const; + /// Returns the number of channels in the SplitterChannel. + +protected: + ~SplitterChannel(); + +private: + typedef std::vector ChannelVec; + + ChannelVec _channels; + mutable FastMutex _mutex; +}; + + +} // namespace Poco + + +#endif // Foundation_SplitterChannel_INCLUDED diff --git a/Foundation/include/Poco/Stopwatch.h b/Foundation/include/Poco/Stopwatch.h index 45471d756..51112b263 100644 --- a/Foundation/include/Poco/Stopwatch.h +++ b/Foundation/include/Poco/Stopwatch.h @@ -1,124 +1,124 @@ -// -// Stopwatch.h -// -// $Id: //poco/1.2/Foundation/include/Poco/Stopwatch.h#1 $ -// -// Library: Foundation -// Package: DateTime -// Module: Stopwatch -// -// Definition of the Stopwatch class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_Stopwatch_INCLUDED -#define Foundation_Stopwatch_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/Timestamp.h" - - -namespace Poco { - - -class Foundation_API Stopwatch - /// A simple facility to measure time intervals - /// with microsecond resolution. -{ -public: - Stopwatch(); - ~Stopwatch(); - - void start(); - /// Starts (or restarts) the stopwatch. - - void stop(); - /// Stops or pauses the stopwatch. - - void reset(); - /// Resets the stopwatch. - - void restart(); - /// Resets and starts the stopwatch. - - Timestamp::TimeDiff elapsed() const; - /// Returns the elapsed time in microseconds - /// since the stopwatch started. - - int elapsedSeconds() const; - /// Returns the number of seconds elapsed - /// since the stopwatch started. - - static Timestamp::TimeVal resolution(); - /// Returns the resolution of the stopwatch. - -private: - Stopwatch(const Stopwatch&); - Stopwatch& operator = (const Stopwatch&); - - Timestamp _start; - Timestamp::TimeDiff _elapsed; - bool _running; -}; - - -// -// inlines -// -inline void Stopwatch::start() -{ - _start.update(); - _running = true; -} - - -inline void Stopwatch::stop() -{ - Timestamp current; - _elapsed += current - _start; - _running = false; -} - - -inline int Stopwatch::elapsedSeconds() const -{ - return int(elapsed()/resolution()); -} - - -inline Timestamp::TimeVal Stopwatch::resolution() -{ - return Timestamp::resolution(); -} - - -} // namespace Poco - - -#endif // Foundation_Stopwatch_INCLUDED +// +// Stopwatch.h +// +// $Id: //poco/1.2/Foundation/include/Poco/Stopwatch.h#1 $ +// +// Library: Foundation +// Package: DateTime +// Module: Stopwatch +// +// Definition of the Stopwatch class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_Stopwatch_INCLUDED +#define Foundation_Stopwatch_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Timestamp.h" + + +namespace Poco { + + +class Foundation_API Stopwatch + /// A simple facility to measure time intervals + /// with microsecond resolution. +{ +public: + Stopwatch(); + ~Stopwatch(); + + void start(); + /// Starts (or restarts) the stopwatch. + + void stop(); + /// Stops or pauses the stopwatch. + + void reset(); + /// Resets the stopwatch. + + void restart(); + /// Resets and starts the stopwatch. + + Timestamp::TimeDiff elapsed() const; + /// Returns the elapsed time in microseconds + /// since the stopwatch started. + + int elapsedSeconds() const; + /// Returns the number of seconds elapsed + /// since the stopwatch started. + + static Timestamp::TimeVal resolution(); + /// Returns the resolution of the stopwatch. + +private: + Stopwatch(const Stopwatch&); + Stopwatch& operator = (const Stopwatch&); + + Timestamp _start; + Timestamp::TimeDiff _elapsed; + bool _running; +}; + + +// +// inlines +// +inline void Stopwatch::start() +{ + _start.update(); + _running = true; +} + + +inline void Stopwatch::stop() +{ + Timestamp current; + _elapsed += current - _start; + _running = false; +} + + +inline int Stopwatch::elapsedSeconds() const +{ + return int(elapsed()/resolution()); +} + + +inline Timestamp::TimeVal Stopwatch::resolution() +{ + return Timestamp::resolution(); +} + + +} // namespace Poco + + +#endif // Foundation_Stopwatch_INCLUDED diff --git a/Foundation/include/Poco/StrategyCollection.h b/Foundation/include/Poco/StrategyCollection.h index 96b4f7273..dfc9cc97f 100644 --- a/Foundation/include/Poco/StrategyCollection.h +++ b/Foundation/include/Poco/StrategyCollection.h @@ -1,155 +1,155 @@ -// -// StrategyCollection.h -// -// $Id: //poco/1.2/Foundation/include/Poco/StrategyCollection.h#2 $ -// -// Library: Foundation -// Package: Cache -// Module: StrategyCollection -// -// Definition of the StrategyCollection class. -// -// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_StrategyCollection_INCLUDED -#define Foundation_StrategyCollection_INCLUDED - - -#include "Poco/KeyValueArgs.h" -#include "Poco/ValidArgs.h" -#include "Poco/AbstractStrategy.h" -#include "Poco/SharedPtr.h" -#include - - -namespace Poco { - - -template -class StrategyCollection: public AbstractStrategy - /// An StrategyCollection is a decorator masking n collections as a single one -{ -public: - typedef std::vector > > Strategies; - typedef typename Strategies::iterator Iterator; - typedef typename Strategies::const_iterator ConstIterator; - -public: - StrategyCollection() - { - } - - ~StrategyCollection() - { - } - - void pushBack(AbstractStrategy* pStrat) - /// Adds an AbstractStrategy to the collection. Class takes ownership of pointer - { - _strategies.push_back(SharedPtr >(pStrat)); - } - - void popBack() - /// Removes the last added AbstractStrategy from the collection. - { - _strategies.pop_back(); - } - - void onAdd(const void* pSender, const KeyValueArgs & key) - /// Adds the key to the strategy. - /// If for the key already an entry exists, it will be overwritten. - { - Iterator it = _strategies.begin(); - Iterator endIt = _strategies.end(); - for (; it != endIt; ++it) - { - (*it)->onAdd(pSender, key); - } - } - - void onRemove(const void* pSender, const TKey& key) - /// Removes an entry from the strategy. If the entry is not found - /// the remove is ignored. - { - Iterator it = _strategies.begin(); - Iterator endIt = _strategies.end(); - for (; it != endIt; ++it) - { - (*it)->onRemove(pSender, key); - } - } - - void onGet(const void* pSender, const TKey& key) - { - Iterator it = _strategies.begin(); - Iterator endIt = _strategies.end(); - for (; it != endIt; ++it) - { - (*it)->onGet(pSender, key); - } - } - - void onClear(const void* pSender, const EventArgs& args) - { - Iterator it = _strategies.begin(); - Iterator endIt = _strategies.end(); - for (; it != endIt; ++it) - { - (*it)->onClear(pSender, args); - } - } - - void onIsValid(const void* pSender, ValidArgs& key) - { - Iterator it = _strategies.begin(); - Iterator endIt = _strategies.end(); - for (; it != endIt && key.isValid(); ++it) - { - (*it)->onIsValid(pSender, key); - } - } - - void onReplace(const void* pSender, std::set& elemsToRemove) - { - Iterator it = _strategies.begin(); - Iterator endIt = _strategies.end(); - for (; it != endIt; ++it) - { - (*it)->onReplace(pSender, elemsToRemove); - } - } - -protected: - Strategies _strategies; -}; - - -} // namespace Poco - - -#endif +// +// StrategyCollection.h +// +// $Id: //poco/1.2/Foundation/include/Poco/StrategyCollection.h#2 $ +// +// Library: Foundation +// Package: Cache +// Module: StrategyCollection +// +// Definition of the StrategyCollection class. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_StrategyCollection_INCLUDED +#define Foundation_StrategyCollection_INCLUDED + + +#include "Poco/KeyValueArgs.h" +#include "Poco/ValidArgs.h" +#include "Poco/AbstractStrategy.h" +#include "Poco/SharedPtr.h" +#include + + +namespace Poco { + + +template +class StrategyCollection: public AbstractStrategy + /// An StrategyCollection is a decorator masking n collections as a single one +{ +public: + typedef std::vector > > Strategies; + typedef typename Strategies::iterator Iterator; + typedef typename Strategies::const_iterator ConstIterator; + +public: + StrategyCollection() + { + } + + ~StrategyCollection() + { + } + + void pushBack(AbstractStrategy* pStrat) + /// Adds an AbstractStrategy to the collection. Class takes ownership of pointer + { + _strategies.push_back(SharedPtr >(pStrat)); + } + + void popBack() + /// Removes the last added AbstractStrategy from the collection. + { + _strategies.pop_back(); + } + + void onAdd(const void* pSender, const KeyValueArgs & key) + /// Adds the key to the strategy. + /// If for the key already an entry exists, it will be overwritten. + { + Iterator it = _strategies.begin(); + Iterator endIt = _strategies.end(); + for (; it != endIt; ++it) + { + (*it)->onAdd(pSender, key); + } + } + + void onRemove(const void* pSender, const TKey& key) + /// Removes an entry from the strategy. If the entry is not found + /// the remove is ignored. + { + Iterator it = _strategies.begin(); + Iterator endIt = _strategies.end(); + for (; it != endIt; ++it) + { + (*it)->onRemove(pSender, key); + } + } + + void onGet(const void* pSender, const TKey& key) + { + Iterator it = _strategies.begin(); + Iterator endIt = _strategies.end(); + for (; it != endIt; ++it) + { + (*it)->onGet(pSender, key); + } + } + + void onClear(const void* pSender, const EventArgs& args) + { + Iterator it = _strategies.begin(); + Iterator endIt = _strategies.end(); + for (; it != endIt; ++it) + { + (*it)->onClear(pSender, args); + } + } + + void onIsValid(const void* pSender, ValidArgs& key) + { + Iterator it = _strategies.begin(); + Iterator endIt = _strategies.end(); + for (; it != endIt && key.isValid(); ++it) + { + (*it)->onIsValid(pSender, key); + } + } + + void onReplace(const void* pSender, std::set& elemsToRemove) + { + Iterator it = _strategies.begin(); + Iterator endIt = _strategies.end(); + for (; it != endIt; ++it) + { + (*it)->onReplace(pSender, elemsToRemove); + } + } + +protected: + Strategies _strategies; +}; + + +} // namespace Poco + + +#endif diff --git a/Foundation/include/Poco/StreamChannel.h b/Foundation/include/Poco/StreamChannel.h index 06348ce96..e74a2bf4a 100644 --- a/Foundation/include/Poco/StreamChannel.h +++ b/Foundation/include/Poco/StreamChannel.h @@ -1,81 +1,81 @@ -// -// StreamChannel.h -// -// $Id: //poco/1.2/Foundation/include/Poco/StreamChannel.h#1 $ -// -// Library: Foundation -// Package: Logging -// Module: StreamChannel -// -// Definition of the StreamChannel class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_StreamChannel_INCLUDED -#define Foundation_StreamChannel_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/Channel.h" -#include "Poco/Mutex.h" -#include - - -namespace Poco { - - -class Foundation_API StreamChannel: public Channel - /// A channel that writes to an ostream. - /// - /// Only the message's text is written, followed - /// by a newline. - /// - /// Chain this channel to a FormattingChannel with an - /// appropriate Formatter to control what is contained - /// in the text. -{ -public: - StreamChannel(std::ostream& str); - /// Creates the channel. - - void log(const Message& msg); - /// Logs the given message to the channel's stream. - -protected: - virtual ~StreamChannel(); - -private: - std::ostream& _str; - FastMutex _mutex; -}; - - -} // namespace Poco - - -#endif // Foundation_StreamChannel_INCLUDED +// +// StreamChannel.h +// +// $Id: //poco/1.2/Foundation/include/Poco/StreamChannel.h#1 $ +// +// Library: Foundation +// Package: Logging +// Module: StreamChannel +// +// Definition of the StreamChannel class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_StreamChannel_INCLUDED +#define Foundation_StreamChannel_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Channel.h" +#include "Poco/Mutex.h" +#include + + +namespace Poco { + + +class Foundation_API StreamChannel: public Channel + /// A channel that writes to an ostream. + /// + /// Only the message's text is written, followed + /// by a newline. + /// + /// Chain this channel to a FormattingChannel with an + /// appropriate Formatter to control what is contained + /// in the text. +{ +public: + StreamChannel(std::ostream& str); + /// Creates the channel. + + void log(const Message& msg); + /// Logs the given message to the channel's stream. + +protected: + virtual ~StreamChannel(); + +private: + std::ostream& _str; + FastMutex _mutex; +}; + + +} // namespace Poco + + +#endif // Foundation_StreamChannel_INCLUDED diff --git a/Foundation/include/Poco/StreamConverter.h b/Foundation/include/Poco/StreamConverter.h index e01f6e543..ae7cad1c9 100644 --- a/Foundation/include/Poco/StreamConverter.h +++ b/Foundation/include/Poco/StreamConverter.h @@ -1,150 +1,150 @@ -// -// StreamConverter.h -// -// $Id: //poco/1.2/Foundation/include/Poco/StreamConverter.h#1 $ -// -// Library: Foundation -// Package: Text -// Module: StreamConverter -// -// Definition of the StreamConverter class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_StreamConverter_INCLUDED -#define Foundation_StreamConverter_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/TextEncoding.h" -#include "Poco/UnbufferedStreamBuf.h" -#include -#include - - -namespace Poco { - - -class Foundation_API StreamConverterBuf: public UnbufferedStreamBuf - /// A StreamConverter converts streams from one encoding (inEncoding) - /// into another (outEncoding). - /// If a character cannot be represented in outEncoding, defaultChar - /// is used instead. - /// If a byte sequence is not valid in inEncoding, defaultChar is used - /// instead and the encoding error count is incremented. -{ -public: - StreamConverterBuf(std::istream& istr, const TextEncoding& inEncoding, const TextEncoding& outEncoding, int defaultChar = '?'); - /// Creates the StreamConverterBuf and connects it - /// to the given input stream. - - StreamConverterBuf(std::ostream& ostr, const TextEncoding& inEncoding, const TextEncoding& outEncoding, int defaultChar = '?'); - /// Creates the StreamConverterBuf and connects it - /// to the given output stream. - - ~StreamConverterBuf(); - /// Destroys the StreamConverterBuf. - - int errors() const; - /// Returns the number of encoding errors encountered. - -protected: - int readFromDevice(); - int writeToDevice(char c); - -private: - std::istream* _pIstr; - std::ostream* _pOstr; - const TextEncoding& _inEncoding; - const TextEncoding& _outEncoding; - int _defaultChar; - unsigned char _buffer[TextEncoding::MAX_SEQUENCE_LENGTH]; - int _sequenceLength; - int _pos; - int _errors; -}; - - -class Foundation_API StreamConverterIOS: public virtual std::ios - /// The base class for InputStreamConverter and OutputStreamConverter. - /// - /// This class is needed to ensure the correct initialization - /// order of the stream buffer and base classes. -{ -public: - StreamConverterIOS(std::istream& istr, const TextEncoding& inEncoding, const TextEncoding& outEncoding, int defaultChar = '?'); - StreamConverterIOS(std::ostream& ostr, const TextEncoding& inEncoding, const TextEncoding& outEncoding, int defaultChar = '?'); - ~StreamConverterIOS(); - StreamConverterBuf* rdbuf(); - int errors() const; - -protected: - StreamConverterBuf _buf; -}; - - -class Foundation_API InputStreamConverter: public StreamConverterIOS, public std::istream - /// This stream converts all characters read from the - /// underlying istream from one character encoding into another. - /// If a character cannot be represented in outEncoding, defaultChar - /// is used instead. - /// If a byte sequence read from the underlying stream is not valid in inEncoding, - /// defaultChar is used instead and the encoding error count is incremented. -{ -public: - InputStreamConverter(std::istream& istr, const TextEncoding& inEncoding, const TextEncoding& outEncoding, int defaultChar = '?'); - /// Creates the InputStreamConverter and connects it - /// to the given input stream. - - ~InputStreamConverter(); - /// Destroys the stream. -}; - - -class Foundation_API OutputStreamConverter: public StreamConverterIOS, public std::ostream - /// This stream converts all characters written to the - /// underlying ostream from one character encoding into another. - /// If a character cannot be represented in outEncoding, defaultChar - /// is used instead. - /// If a byte sequence written to the stream is not valid in inEncoding, - /// defaultChar is used instead and the encoding error count is incremented. -{ -public: - OutputStreamConverter(std::ostream& ostr, const TextEncoding& inEncoding, const TextEncoding& outEncoding, int defaultChar = '?'); - /// Creates the OutputStreamConverter and connects it - /// to the given input stream. - - ~OutputStreamConverter(); - /// Destroys the CountingOutputStream. -}; - - -} // namespace Poco - - -#endif // Foundation_StreamConverter_INCLUDED +// +// StreamConverter.h +// +// $Id: //poco/1.2/Foundation/include/Poco/StreamConverter.h#1 $ +// +// Library: Foundation +// Package: Text +// Module: StreamConverter +// +// Definition of the StreamConverter class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_StreamConverter_INCLUDED +#define Foundation_StreamConverter_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/TextEncoding.h" +#include "Poco/UnbufferedStreamBuf.h" +#include +#include + + +namespace Poco { + + +class Foundation_API StreamConverterBuf: public UnbufferedStreamBuf + /// A StreamConverter converts streams from one encoding (inEncoding) + /// into another (outEncoding). + /// If a character cannot be represented in outEncoding, defaultChar + /// is used instead. + /// If a byte sequence is not valid in inEncoding, defaultChar is used + /// instead and the encoding error count is incremented. +{ +public: + StreamConverterBuf(std::istream& istr, const TextEncoding& inEncoding, const TextEncoding& outEncoding, int defaultChar = '?'); + /// Creates the StreamConverterBuf and connects it + /// to the given input stream. + + StreamConverterBuf(std::ostream& ostr, const TextEncoding& inEncoding, const TextEncoding& outEncoding, int defaultChar = '?'); + /// Creates the StreamConverterBuf and connects it + /// to the given output stream. + + ~StreamConverterBuf(); + /// Destroys the StreamConverterBuf. + + int errors() const; + /// Returns the number of encoding errors encountered. + +protected: + int readFromDevice(); + int writeToDevice(char c); + +private: + std::istream* _pIstr; + std::ostream* _pOstr; + const TextEncoding& _inEncoding; + const TextEncoding& _outEncoding; + int _defaultChar; + unsigned char _buffer[TextEncoding::MAX_SEQUENCE_LENGTH]; + int _sequenceLength; + int _pos; + int _errors; +}; + + +class Foundation_API StreamConverterIOS: public virtual std::ios + /// The base class for InputStreamConverter and OutputStreamConverter. + /// + /// This class is needed to ensure the correct initialization + /// order of the stream buffer and base classes. +{ +public: + StreamConverterIOS(std::istream& istr, const TextEncoding& inEncoding, const TextEncoding& outEncoding, int defaultChar = '?'); + StreamConverterIOS(std::ostream& ostr, const TextEncoding& inEncoding, const TextEncoding& outEncoding, int defaultChar = '?'); + ~StreamConverterIOS(); + StreamConverterBuf* rdbuf(); + int errors() const; + +protected: + StreamConverterBuf _buf; +}; + + +class Foundation_API InputStreamConverter: public StreamConverterIOS, public std::istream + /// This stream converts all characters read from the + /// underlying istream from one character encoding into another. + /// If a character cannot be represented in outEncoding, defaultChar + /// is used instead. + /// If a byte sequence read from the underlying stream is not valid in inEncoding, + /// defaultChar is used instead and the encoding error count is incremented. +{ +public: + InputStreamConverter(std::istream& istr, const TextEncoding& inEncoding, const TextEncoding& outEncoding, int defaultChar = '?'); + /// Creates the InputStreamConverter and connects it + /// to the given input stream. + + ~InputStreamConverter(); + /// Destroys the stream. +}; + + +class Foundation_API OutputStreamConverter: public StreamConverterIOS, public std::ostream + /// This stream converts all characters written to the + /// underlying ostream from one character encoding into another. + /// If a character cannot be represented in outEncoding, defaultChar + /// is used instead. + /// If a byte sequence written to the stream is not valid in inEncoding, + /// defaultChar is used instead and the encoding error count is incremented. +{ +public: + OutputStreamConverter(std::ostream& ostr, const TextEncoding& inEncoding, const TextEncoding& outEncoding, int defaultChar = '?'); + /// Creates the OutputStreamConverter and connects it + /// to the given input stream. + + ~OutputStreamConverter(); + /// Destroys the CountingOutputStream. +}; + + +} // namespace Poco + + +#endif // Foundation_StreamConverter_INCLUDED diff --git a/Foundation/include/Poco/StreamCopier.h b/Foundation/include/Poco/StreamCopier.h index 920b80380..b572949df 100644 --- a/Foundation/include/Poco/StreamCopier.h +++ b/Foundation/include/Poco/StreamCopier.h @@ -1,76 +1,76 @@ -// -// StreamCopier.h -// -// $Id: //poco/1.2/Foundation/include/Poco/StreamCopier.h#1 $ -// -// Library: Foundation -// Package: Streams -// Module: StreamCopier -// -// Definition of class StreamCopier. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_StreamCopier_INCLUDED -#define Foundation_StreamCopier_INCLUDED - - -#include "Poco/Foundation.h" -#include -#include - - -namespace Poco { - - -class Foundation_API StreamCopier - /// This class provides static methods to copy the contents from one stream - /// into another. -{ -public: - static std::streamsize copyStream(std::istream& istr, std::ostream& ostr, unsigned bufferSize = 8192); - /// Writes all bytes readable from istr to ostr, using an internal buffer. - /// - /// Returns the number of bytes copied. - - static std::streamsize copyStreamUnbuffered(std::istream& istr, std::ostream& ostr); - /// Writes all bytes readable from istr to ostr. - /// - /// Returns the number of bytes copied. - - static std::streamsize copyToString(std::istream& istr, std::string& str, unsigned bufferSize = 8192); - /// Appends all bytes readable from istr to the given string, using an internal buffer. - /// - /// Returns the number of bytes copied. -}; - - -} // namespace Poco - - -#endif // Foundation_StreamCopier_INCLUDED +// +// StreamCopier.h +// +// $Id: //poco/1.2/Foundation/include/Poco/StreamCopier.h#1 $ +// +// Library: Foundation +// Package: Streams +// Module: StreamCopier +// +// Definition of class StreamCopier. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_StreamCopier_INCLUDED +#define Foundation_StreamCopier_INCLUDED + + +#include "Poco/Foundation.h" +#include +#include + + +namespace Poco { + + +class Foundation_API StreamCopier + /// This class provides static methods to copy the contents from one stream + /// into another. +{ +public: + static std::streamsize copyStream(std::istream& istr, std::ostream& ostr, unsigned bufferSize = 8192); + /// Writes all bytes readable from istr to ostr, using an internal buffer. + /// + /// Returns the number of bytes copied. + + static std::streamsize copyStreamUnbuffered(std::istream& istr, std::ostream& ostr); + /// Writes all bytes readable from istr to ostr. + /// + /// Returns the number of bytes copied. + + static std::streamsize copyToString(std::istream& istr, std::string& str, unsigned bufferSize = 8192); + /// Appends all bytes readable from istr to the given string, using an internal buffer. + /// + /// Returns the number of bytes copied. +}; + + +} // namespace Poco + + +#endif // Foundation_StreamCopier_INCLUDED diff --git a/Foundation/include/Poco/StreamTokenizer.h b/Foundation/include/Poco/StreamTokenizer.h index a2c7f2901..e65da1863 100644 --- a/Foundation/include/Poco/StreamTokenizer.h +++ b/Foundation/include/Poco/StreamTokenizer.h @@ -1,119 +1,119 @@ -// -// StreamTokenizer.h -// -// $Id: //poco/1.2/Foundation/include/Poco/StreamTokenizer.h#1 $ -// -// Library: Foundation -// Package: Streams -// Module: StreamTokenizer -// -// Definition of the StreamTokenizer class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_StreamTokenizer_INCLUDED -#define Foundation_StreamTokenizer_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/Token.h" -#include -#include - - -namespace Poco { - - -class Foundation_API StreamTokenizer - /// A stream tokenizer splits an input stream - /// into a sequence of tokens of different kinds. - /// Various token kinds can be registered with - /// the tokenizer. -{ -public: - StreamTokenizer(); - /// Creates a StreamTokenizer with no attached stream. - - StreamTokenizer(std::istream& istr); - /// Creates a StreamTokenizer with no attached stream. - - virtual ~StreamTokenizer(); - /// Destroys the StreamTokenizer and deletes all - /// registered tokens. - - void attachToStream(std::istream& istr); - /// Attaches the tokenizer to an input stream. - - void addToken(Token* pToken); - /// Adds a token class to the tokenizer. The - /// tokenizer takes ownership of the token and - /// deletes it when no longer needed. Comment - /// and whitespace tokens will be marked as - /// ignorable, which means that next() will not - /// return them. - - void addToken(Token* pToken, bool ignore); - /// Adds a token class to the tokenizer. The - /// tokenizer takes ownership of the token and - /// deletes it when no longer needed. - /// If ignore is true, the token will be marked - /// as ignorable, which means that next() will - /// not return it. - - const Token* next(); - /// Extracts the next token from the input stream. - /// Returns a pointer to an EOFToken if there are - /// no more characters to read. - /// Returns a pointer to an InvalidToken if an - /// invalid character is encountered. - /// If a token is marked as ignorable, it will not - /// be returned, and the next token will be - /// examined. - /// Never returns a NULL pointer. - /// You must not delete the token returned by next(). - -private: - struct TokenInfo - { - Token* pToken; - bool ignore; - }; - - typedef std::vector TokenVec; - - TokenVec _tokens; - std::istream* _pIstr; - InvalidToken _invalidToken; - EOFToken _eofToken; -}; - - -} // namespace Poco - - -#endif // Foundation_StreamTokenizer_INCLUDED +// +// StreamTokenizer.h +// +// $Id: //poco/1.2/Foundation/include/Poco/StreamTokenizer.h#1 $ +// +// Library: Foundation +// Package: Streams +// Module: StreamTokenizer +// +// Definition of the StreamTokenizer class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_StreamTokenizer_INCLUDED +#define Foundation_StreamTokenizer_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Token.h" +#include +#include + + +namespace Poco { + + +class Foundation_API StreamTokenizer + /// A stream tokenizer splits an input stream + /// into a sequence of tokens of different kinds. + /// Various token kinds can be registered with + /// the tokenizer. +{ +public: + StreamTokenizer(); + /// Creates a StreamTokenizer with no attached stream. + + StreamTokenizer(std::istream& istr); + /// Creates a StreamTokenizer with no attached stream. + + virtual ~StreamTokenizer(); + /// Destroys the StreamTokenizer and deletes all + /// registered tokens. + + void attachToStream(std::istream& istr); + /// Attaches the tokenizer to an input stream. + + void addToken(Token* pToken); + /// Adds a token class to the tokenizer. The + /// tokenizer takes ownership of the token and + /// deletes it when no longer needed. Comment + /// and whitespace tokens will be marked as + /// ignorable, which means that next() will not + /// return them. + + void addToken(Token* pToken, bool ignore); + /// Adds a token class to the tokenizer. The + /// tokenizer takes ownership of the token and + /// deletes it when no longer needed. + /// If ignore is true, the token will be marked + /// as ignorable, which means that next() will + /// not return it. + + const Token* next(); + /// Extracts the next token from the input stream. + /// Returns a pointer to an EOFToken if there are + /// no more characters to read. + /// Returns a pointer to an InvalidToken if an + /// invalid character is encountered. + /// If a token is marked as ignorable, it will not + /// be returned, and the next token will be + /// examined. + /// Never returns a NULL pointer. + /// You must not delete the token returned by next(). + +private: + struct TokenInfo + { + Token* pToken; + bool ignore; + }; + + typedef std::vector TokenVec; + + TokenVec _tokens; + std::istream* _pIstr; + InvalidToken _invalidToken; + EOFToken _eofToken; +}; + + +} // namespace Poco + + +#endif // Foundation_StreamTokenizer_INCLUDED diff --git a/Foundation/include/Poco/StreamUtil.h b/Foundation/include/Poco/StreamUtil.h index 4d9f4c8a7..e46f3ed46 100644 --- a/Foundation/include/Poco/StreamUtil.h +++ b/Foundation/include/Poco/StreamUtil.h @@ -1,101 +1,101 @@ -// -// StreamUtil.h -// -// $Id: //poco/1.2/Foundation/include/Poco/StreamUtil.h#1 $ -// -// Library: Foundation -// Package: Streams -// Module: StreamUtil -// -// Stream implementation support. -// -// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_StreamUtil_INCLUDED -#define Foundation_StreamUtil_INCLUDED - - -#include "Poco/Foundation.h" - - -// poco_ios_init -// -// This is a workaround for a bug in the Microsoft -// implementation of iostreams. -// -// Calling basic_ios::init() multiple times for the -// same basic_ios instance results in a memory leak -// caused by the ios' locale being allocated more than -// once, each time overwriting the old pointer. -// This usually occurs in the following scenario: -// -// class MyStreamBuf: public std::streambuf -// { -// ... -// }; -// -// class MyIOS: public virtual std::ios -// { -// public: -// MyIOS() -// { -// init(&_buf); -// } -// protected: -// MyStreamBuf _buf; -// }; -// -// class MyIStream: public MyIOS, public std::istream -// { -// ... -// }; -// -// In this scenario, std::ios::init() is called twice -// (the first time by the MyIOS constructor, the second -// time by the std::istream constructor), resulting in -// two locale objects being allocated, the pointer second -// one overwriting the pointer to the first one and thus -// causing a memory leak. -// -// The workaround is to call init() only once for each -// stream object - by the istream, ostream or iostream -// constructor, and not calling init() in ios-derived -// base classes. -// -// Some stream implementations, however, require that -// init() is called in the MyIOS constructor. -// Therefore we replace each call to init() with -// the following macro: -#if defined(_MSC_VER) && (!defined(_STLP_MSVC) || defined(_STLP_NO_OWN_IOSTREAMS)) -#define poco_ios_init(buf) -#else -#define poco_ios_init(buf) init(buf) -#endif - - -#endif // Foundation_StreamUtil_INCLUDED +// +// StreamUtil.h +// +// $Id: //poco/1.2/Foundation/include/Poco/StreamUtil.h#1 $ +// +// Library: Foundation +// Package: Streams +// Module: StreamUtil +// +// Stream implementation support. +// +// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_StreamUtil_INCLUDED +#define Foundation_StreamUtil_INCLUDED + + +#include "Poco/Foundation.h" + + +// poco_ios_init +// +// This is a workaround for a bug in the Microsoft +// implementation of iostreams. +// +// Calling basic_ios::init() multiple times for the +// same basic_ios instance results in a memory leak +// caused by the ios' locale being allocated more than +// once, each time overwriting the old pointer. +// This usually occurs in the following scenario: +// +// class MyStreamBuf: public std::streambuf +// { +// ... +// }; +// +// class MyIOS: public virtual std::ios +// { +// public: +// MyIOS() +// { +// init(&_buf); +// } +// protected: +// MyStreamBuf _buf; +// }; +// +// class MyIStream: public MyIOS, public std::istream +// { +// ... +// }; +// +// In this scenario, std::ios::init() is called twice +// (the first time by the MyIOS constructor, the second +// time by the std::istream constructor), resulting in +// two locale objects being allocated, the pointer second +// one overwriting the pointer to the first one and thus +// causing a memory leak. +// +// The workaround is to call init() only once for each +// stream object - by the istream, ostream or iostream +// constructor, and not calling init() in ios-derived +// base classes. +// +// Some stream implementations, however, require that +// init() is called in the MyIOS constructor. +// Therefore we replace each call to init() with +// the following macro: +#if defined(_MSC_VER) && (!defined(_STLP_MSVC) || defined(_STLP_NO_OWN_IOSTREAMS)) +#define poco_ios_init(buf) +#else +#define poco_ios_init(buf) init(buf) +#endif + + +#endif // Foundation_StreamUtil_INCLUDED diff --git a/Foundation/include/Poco/String.h b/Foundation/include/Poco/String.h index a5b8ac954..21890a18d 100644 --- a/Foundation/include/Poco/String.h +++ b/Foundation/include/Poco/String.h @@ -1,505 +1,505 @@ -// -// String.h -// -// $Id: //poco/1.2/Foundation/include/Poco/String.h#1 $ -// -// Library: Foundation -// Package: Core -// Module: String -// -// String utility functions. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_String_INCLUDED -#define Foundation_String_INCLUDED - - -#include "Poco/Foundation.h" -#include - - -namespace Poco { - - -template -S trimLeft(const S& str) - /// Returns a copy of str with all leading - /// whitespace removed. -{ - std::locale loc; - typename S::const_iterator it = str.begin(); - typename S::const_iterator end = str.end(); - - while (it != end && isspace(*it, loc)) ++it; - return S(it, end); -} - - -template -S& trimLeftInPlace(S& str) - /// Removes all leading whitespace in str. -{ - std::locale loc; - typename S::iterator it = str.begin(); - typename S::iterator end = str.end(); - - while (it != end && isspace(*it, loc)) ++it; - str.erase(str.begin(), it); - return str; -} - - -template -S trimRight(const S& str) - /// Returns a copy of str with all trailing - /// whitespace removed. -{ - std::locale loc; - int pos = int(str.size()) - 1; - - while (pos >= 0 && isspace(str[pos], loc)) --pos; - return S(str, 0, pos + 1); -} - - -template -S& trimRightInPlace(S& str) - /// Removes all trailing whitespace in str. -{ - std::locale loc; - int pos = int(str.size()) - 1; - - while (pos >= 0 && isspace(str[pos], loc)) --pos; - str.resize(pos + 1); - - return str; -} - - -template -S trim(const S& str) - /// Returns a copy of str with all leading and - /// trailing whitespace removed. -{ - std::locale loc; - int first = 0; - int last = int(str.size()) - 1; - - while (first <= last && isspace(str[first], loc)) ++first; - while (last >= first && isspace(str[last], loc)) --last; - - return S(str, first, last - first + 1); -} - - -template -S& trimInPlace(S& str) - /// Removes all leading and trailing whitespace in str. -{ - std::locale loc; - int first = 0; - int last = int(str.size()) - 1; - - while (first <= last && isspace(str[first], loc)) ++first; - while (last >= first && isspace(str[last], loc)) --last; - - str.resize(last + 1); - str.erase(0, first); - - return str; -} - - -template -S toUpper(const S& str) - /// Returns a copy of str containing all upper-case characters. -{ - std::locale loc; - typename S::const_iterator it = str.begin(); - typename S::const_iterator end = str.end(); - - S result; - result.reserve(str.size()); - while (it != end) result += toupper(*it++, loc); - return result; -} - - -template -S& toUpperInPlace(S& str) - /// Replaces all characters in str with their upper-case counterparts. -{ - std::locale loc; - typename S::iterator it = str.begin(); - typename S::iterator end = str.end(); - - while (it != end) { *it = toupper(*it, loc); ++it; } - return str; -} - - -template -S toLower(const S& str) - /// Returns a copy of str containing all lower-case characters. -{ - std::locale loc; - typename S::const_iterator it = str.begin(); - typename S::const_iterator end = str.end(); - - S result; - result.reserve(str.size()); - while (it != end) result += tolower(*it++, loc); - return result; -} - - -template -S& toLowerInPlace(S& str) - /// Replaces all characters in str with their lower-case counterparts. -{ - std::locale loc; - typename S::iterator it = str.begin(); - typename S::iterator end = str.end(); - - while (it != end) { *it = tolower(*it, loc); ++it; } - return str; -} - - -#if !defined(POCO_NO_TEMPLATE_ICOMPARE) - - -template -int icompare( - const S& str, - typename S::size_type pos, - typename S::size_type n, - It it2, - It end2) - /// Case-insensitive string comparison -{ - typename S::size_type sz = str.size(); - if (pos > sz) pos = sz; - if (pos + n > sz) n = sz - pos; - It it1 = str.begin() + pos; - It end1 = str.begin() + pos + n; - std::locale loc; - while (it1 != end1 && it2 != end2) - { - typename S::value_type c1 = tolower(*it1, loc); - typename S::value_type c2 = tolower(*it2, loc); - if (c1 < c2) - return -1; - else if (c1 > c2) - return 1; - ++it1; ++it2; - } - - if (it1 == end1) - return it2 == end2 ? 0 : -1; - else - return 1; -} - - -template -int icompare(const S& str1, const S& str2) -{ - return icompare(str1, 0, str1.size(), str2.begin(), str2.end()); -} - - -template -int icompare(const S& str1, typename S::size_type n1, const S& str2, typename S::size_type n2) -{ - if (n2 > str2.size()) n2 = str2.size(); - return icompare(str1, 0, n1, str2.begin(), str2.begin() + n2); -} - - -template -int icompare(const S& str1, typename S::size_type n, const S& str2) -{ - if (n > str2.size()) n = str2.size(); - return icompare(str1, 0, n, str2.begin(), str2.begin() + n); -} - - -template -int icompare(const S& str1, typename S::size_type pos, typename S::size_type n, const S& str2) -{ - return icompare(str1, pos, n, str2.begin(), str2.end()); -} - - -template -int icompare( - const S& str1, - typename S::size_type pos1, - typename S::size_type n1, - const S& str2, - typename S::size_type pos2, - typename S::size_type n2) -{ - typename S::size_type sz2 = str2.size(); - if (pos2 > sz2) pos2 = sz2; - if (pos2 + n2 > sz2) n2 = sz2 - pos2; - return icompare(str1, pos1, n1, str2.begin() + pos2, str2.begin() + pos2 + n2); -} - - -template -int icompare( - const S& str1, - typename S::size_type pos1, - typename S::size_type n, - const S& str2, - typename S::size_type pos2) -{ - typename S::size_type sz2 = str2.size(); - if (pos2 > sz2) pos2 = sz2; - if (pos2 + n > sz2) n = sz2 - pos2; - return icompare(str1, pos1, n, str2.begin() + pos2, str2.begin() + pos2 + n); -} - - -template -int icompare( - const S& str, - typename S::size_type pos, - typename S::size_type n, - const typename S::value_type* ptr) -{ - poco_check_ptr (ptr); - typename S::size_type sz = str.size(); - if (pos > sz) pos = sz; - if (pos + n > sz) n = sz - pos; - typename S::const_iterator it = str.begin() + pos; - typename S::const_iterator end = str.begin() + pos + n; - std::locale loc; - while (it != end && *ptr) - { - typename S::value_type c1 = tolower(*it, loc); - typename S::value_type c2 = tolower(*ptr, loc); - if (c1 < c2) - return -1; - else if (c1 > c2) - return 1; - ++it; ++ptr; - } - - if (it == end) - return *ptr == 0 ? 0 : -1; - else - return 1; -} - - -template -int icompare( - const S& str, - typename S::size_type pos, - const typename S::value_type* ptr) -{ - return icompare(str, pos, str.size() - pos, ptr); -} - - -template -int icompare( - const S& str, - const typename S::value_type* ptr) -{ - return icompare(str, 0, str.size(), ptr); -} - - -#else - - -int Foundation_API icompare(const std::string& str, std::string::size_type pos, std::string::size_type n, std::string::const_iterator it2, std::string::const_iterator end2); -int Foundation_API icompare(const std::string& str1, const std::string& str2); -int Foundation_API icompare(const std::string& str1, std::string::size_type n1, const std::string& str2, std::string::size_type n2); -int Foundation_API icompare(const std::string& str1, std::string::size_type n, const std::string& str2); -int Foundation_API icompare(const std::string& str1, std::string::size_type pos, std::string::size_type n, const std::string& str2); -int Foundation_API icompare(const std::string& str1, std::string::size_type pos1, std::string::size_type n1, const std::string& str2, std::string::size_type pos2, std::string::size_type n2); -int Foundation_API icompare(const std::string& str1, std::string::size_type pos1, std::string::size_type n, const std::string& str2, std::string::size_type pos2); -int Foundation_API icompare(const std::string& str, std::string::size_type pos, std::string::size_type n, const std::string::value_type* ptr); -int Foundation_API icompare(const std::string& str, std::string::size_type pos, const std::string::value_type* ptr); -int Foundation_API icompare(const std::string& str, const std::string::value_type* ptr); - - -#endif - - -template -S translate(const S& str, const S& from, const S& to) - /// Returns a copy of str with all characters in - /// from replaced by the corresponding (by position) - /// characters in to. If there is no corresponding - /// character in to, the character is removed from - /// the copy. -{ - S result; - result.reserve(str.size()); - typename S::const_iterator it = str.begin(); - typename S::const_iterator end = str.end(); - typename S::size_type toSize = to.size(); - while (it != end) - { - typename S::size_type pos = from.find(*it); - if (pos == S::npos) - { - result += *it; - } - else - { - if (pos < toSize) result += to[pos]; - } - ++it; - } - return result; -} - - -template -S translate(const S& str, const typename S::value_type* from, const typename S::value_type* to) -{ - poco_check_ptr (from); - poco_check_ptr (to); - return translate(str, S(from), S(to)); -} - - -template -S& translateInPlace(S& str, const S& from, const S& to) - /// Replaces in str all occurences of characters in from - /// with the corresponding (by position) characters in to. - /// If there is no corresponding character, the character - /// is removed. -{ - str = translate(str, from, to); - return str; -} - - -template -S translateInPlace(S& str, const typename S::value_type* from, const typename S::value_type* to) -{ - poco_check_ptr (from); - poco_check_ptr (to); - str = translate(str, S(from), S(to)); - return str; -} - - -template -S cat(const S& s1, const S& s2) - /// Concatenates two strings. -{ - S result = s1; - result.reserve(s1.size() + s2.size()); - result.append(s2); - return result; -} - - -template -S cat(const S& s1, const S& s2, const S& s3) - /// Concatenates three strings. -{ - S result = s1; - result.reserve(s1.size() + s2.size() + s3.size()); - result.append(s2); - result.append(s3); - return result; -} - - -template -S cat(const S& s1, const S& s2, const S& s3, const S& s4) - /// Concatenates four strings. -{ - S result = s1; - result.reserve(s1.size() + s2.size() + s3.size() + s4.size()); - result.append(s2); - result.append(s3); - result.append(s4); - return result; -} - - -template -S cat(const S& s1, const S& s2, const S& s3, const S& s4, const S& s5) - /// Concatenates five strings. -{ - S result = s1; - result.reserve(s1.size() + s2.size() + s3.size() + s4.size() + s5.size()); - result.append(s2); - result.append(s3); - result.append(s4); - result.append(s5); - return result; -} - - -template -S cat(const S& s1, const S& s2, const S& s3, const S& s4, const S& s5, const S& s6) - /// Concatenates six strings. -{ - S result = s1; - result.reserve(s1.size() + s2.size() + s3.size() + s4.size() + s5.size() + s6.size()); - result.append(s2); - result.append(s3); - result.append(s4); - result.append(s5); - result.append(s6); - return result; -} - - -template -S cat(const S& delim, const It& begin, const It& end) - /// Concatenates a sequence of strings, delimited - /// by the string given in delim. -{ - S result; - for (It it = begin; it != end; ++it) - { - if (!result.empty()) result.append(delim); - result += *it; - } - return result; -} - - -} // namespace Poco - - -#endif // Foundation_String_INCLUDED +// +// String.h +// +// $Id: //poco/1.2/Foundation/include/Poco/String.h#1 $ +// +// Library: Foundation +// Package: Core +// Module: String +// +// String utility functions. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_String_INCLUDED +#define Foundation_String_INCLUDED + + +#include "Poco/Foundation.h" +#include + + +namespace Poco { + + +template +S trimLeft(const S& str) + /// Returns a copy of str with all leading + /// whitespace removed. +{ + std::locale loc; + typename S::const_iterator it = str.begin(); + typename S::const_iterator end = str.end(); + + while (it != end && isspace(*it, loc)) ++it; + return S(it, end); +} + + +template +S& trimLeftInPlace(S& str) + /// Removes all leading whitespace in str. +{ + std::locale loc; + typename S::iterator it = str.begin(); + typename S::iterator end = str.end(); + + while (it != end && isspace(*it, loc)) ++it; + str.erase(str.begin(), it); + return str; +} + + +template +S trimRight(const S& str) + /// Returns a copy of str with all trailing + /// whitespace removed. +{ + std::locale loc; + int pos = int(str.size()) - 1; + + while (pos >= 0 && isspace(str[pos], loc)) --pos; + return S(str, 0, pos + 1); +} + + +template +S& trimRightInPlace(S& str) + /// Removes all trailing whitespace in str. +{ + std::locale loc; + int pos = int(str.size()) - 1; + + while (pos >= 0 && isspace(str[pos], loc)) --pos; + str.resize(pos + 1); + + return str; +} + + +template +S trim(const S& str) + /// Returns a copy of str with all leading and + /// trailing whitespace removed. +{ + std::locale loc; + int first = 0; + int last = int(str.size()) - 1; + + while (first <= last && isspace(str[first], loc)) ++first; + while (last >= first && isspace(str[last], loc)) --last; + + return S(str, first, last - first + 1); +} + + +template +S& trimInPlace(S& str) + /// Removes all leading and trailing whitespace in str. +{ + std::locale loc; + int first = 0; + int last = int(str.size()) - 1; + + while (first <= last && isspace(str[first], loc)) ++first; + while (last >= first && isspace(str[last], loc)) --last; + + str.resize(last + 1); + str.erase(0, first); + + return str; +} + + +template +S toUpper(const S& str) + /// Returns a copy of str containing all upper-case characters. +{ + std::locale loc; + typename S::const_iterator it = str.begin(); + typename S::const_iterator end = str.end(); + + S result; + result.reserve(str.size()); + while (it != end) result += toupper(*it++, loc); + return result; +} + + +template +S& toUpperInPlace(S& str) + /// Replaces all characters in str with their upper-case counterparts. +{ + std::locale loc; + typename S::iterator it = str.begin(); + typename S::iterator end = str.end(); + + while (it != end) { *it = toupper(*it, loc); ++it; } + return str; +} + + +template +S toLower(const S& str) + /// Returns a copy of str containing all lower-case characters. +{ + std::locale loc; + typename S::const_iterator it = str.begin(); + typename S::const_iterator end = str.end(); + + S result; + result.reserve(str.size()); + while (it != end) result += tolower(*it++, loc); + return result; +} + + +template +S& toLowerInPlace(S& str) + /// Replaces all characters in str with their lower-case counterparts. +{ + std::locale loc; + typename S::iterator it = str.begin(); + typename S::iterator end = str.end(); + + while (it != end) { *it = tolower(*it, loc); ++it; } + return str; +} + + +#if !defined(POCO_NO_TEMPLATE_ICOMPARE) + + +template +int icompare( + const S& str, + typename S::size_type pos, + typename S::size_type n, + It it2, + It end2) + /// Case-insensitive string comparison +{ + typename S::size_type sz = str.size(); + if (pos > sz) pos = sz; + if (pos + n > sz) n = sz - pos; + It it1 = str.begin() + pos; + It end1 = str.begin() + pos + n; + std::locale loc; + while (it1 != end1 && it2 != end2) + { + typename S::value_type c1 = tolower(*it1, loc); + typename S::value_type c2 = tolower(*it2, loc); + if (c1 < c2) + return -1; + else if (c1 > c2) + return 1; + ++it1; ++it2; + } + + if (it1 == end1) + return it2 == end2 ? 0 : -1; + else + return 1; +} + + +template +int icompare(const S& str1, const S& str2) +{ + return icompare(str1, 0, str1.size(), str2.begin(), str2.end()); +} + + +template +int icompare(const S& str1, typename S::size_type n1, const S& str2, typename S::size_type n2) +{ + if (n2 > str2.size()) n2 = str2.size(); + return icompare(str1, 0, n1, str2.begin(), str2.begin() + n2); +} + + +template +int icompare(const S& str1, typename S::size_type n, const S& str2) +{ + if (n > str2.size()) n = str2.size(); + return icompare(str1, 0, n, str2.begin(), str2.begin() + n); +} + + +template +int icompare(const S& str1, typename S::size_type pos, typename S::size_type n, const S& str2) +{ + return icompare(str1, pos, n, str2.begin(), str2.end()); +} + + +template +int icompare( + const S& str1, + typename S::size_type pos1, + typename S::size_type n1, + const S& str2, + typename S::size_type pos2, + typename S::size_type n2) +{ + typename S::size_type sz2 = str2.size(); + if (pos2 > sz2) pos2 = sz2; + if (pos2 + n2 > sz2) n2 = sz2 - pos2; + return icompare(str1, pos1, n1, str2.begin() + pos2, str2.begin() + pos2 + n2); +} + + +template +int icompare( + const S& str1, + typename S::size_type pos1, + typename S::size_type n, + const S& str2, + typename S::size_type pos2) +{ + typename S::size_type sz2 = str2.size(); + if (pos2 > sz2) pos2 = sz2; + if (pos2 + n > sz2) n = sz2 - pos2; + return icompare(str1, pos1, n, str2.begin() + pos2, str2.begin() + pos2 + n); +} + + +template +int icompare( + const S& str, + typename S::size_type pos, + typename S::size_type n, + const typename S::value_type* ptr) +{ + poco_check_ptr (ptr); + typename S::size_type sz = str.size(); + if (pos > sz) pos = sz; + if (pos + n > sz) n = sz - pos; + typename S::const_iterator it = str.begin() + pos; + typename S::const_iterator end = str.begin() + pos + n; + std::locale loc; + while (it != end && *ptr) + { + typename S::value_type c1 = tolower(*it, loc); + typename S::value_type c2 = tolower(*ptr, loc); + if (c1 < c2) + return -1; + else if (c1 > c2) + return 1; + ++it; ++ptr; + } + + if (it == end) + return *ptr == 0 ? 0 : -1; + else + return 1; +} + + +template +int icompare( + const S& str, + typename S::size_type pos, + const typename S::value_type* ptr) +{ + return icompare(str, pos, str.size() - pos, ptr); +} + + +template +int icompare( + const S& str, + const typename S::value_type* ptr) +{ + return icompare(str, 0, str.size(), ptr); +} + + +#else + + +int Foundation_API icompare(const std::string& str, std::string::size_type pos, std::string::size_type n, std::string::const_iterator it2, std::string::const_iterator end2); +int Foundation_API icompare(const std::string& str1, const std::string& str2); +int Foundation_API icompare(const std::string& str1, std::string::size_type n1, const std::string& str2, std::string::size_type n2); +int Foundation_API icompare(const std::string& str1, std::string::size_type n, const std::string& str2); +int Foundation_API icompare(const std::string& str1, std::string::size_type pos, std::string::size_type n, const std::string& str2); +int Foundation_API icompare(const std::string& str1, std::string::size_type pos1, std::string::size_type n1, const std::string& str2, std::string::size_type pos2, std::string::size_type n2); +int Foundation_API icompare(const std::string& str1, std::string::size_type pos1, std::string::size_type n, const std::string& str2, std::string::size_type pos2); +int Foundation_API icompare(const std::string& str, std::string::size_type pos, std::string::size_type n, const std::string::value_type* ptr); +int Foundation_API icompare(const std::string& str, std::string::size_type pos, const std::string::value_type* ptr); +int Foundation_API icompare(const std::string& str, const std::string::value_type* ptr); + + +#endif + + +template +S translate(const S& str, const S& from, const S& to) + /// Returns a copy of str with all characters in + /// from replaced by the corresponding (by position) + /// characters in to. If there is no corresponding + /// character in to, the character is removed from + /// the copy. +{ + S result; + result.reserve(str.size()); + typename S::const_iterator it = str.begin(); + typename S::const_iterator end = str.end(); + typename S::size_type toSize = to.size(); + while (it != end) + { + typename S::size_type pos = from.find(*it); + if (pos == S::npos) + { + result += *it; + } + else + { + if (pos < toSize) result += to[pos]; + } + ++it; + } + return result; +} + + +template +S translate(const S& str, const typename S::value_type* from, const typename S::value_type* to) +{ + poco_check_ptr (from); + poco_check_ptr (to); + return translate(str, S(from), S(to)); +} + + +template +S& translateInPlace(S& str, const S& from, const S& to) + /// Replaces in str all occurences of characters in from + /// with the corresponding (by position) characters in to. + /// If there is no corresponding character, the character + /// is removed. +{ + str = translate(str, from, to); + return str; +} + + +template +S translateInPlace(S& str, const typename S::value_type* from, const typename S::value_type* to) +{ + poco_check_ptr (from); + poco_check_ptr (to); + str = translate(str, S(from), S(to)); + return str; +} + + +template +S cat(const S& s1, const S& s2) + /// Concatenates two strings. +{ + S result = s1; + result.reserve(s1.size() + s2.size()); + result.append(s2); + return result; +} + + +template +S cat(const S& s1, const S& s2, const S& s3) + /// Concatenates three strings. +{ + S result = s1; + result.reserve(s1.size() + s2.size() + s3.size()); + result.append(s2); + result.append(s3); + return result; +} + + +template +S cat(const S& s1, const S& s2, const S& s3, const S& s4) + /// Concatenates four strings. +{ + S result = s1; + result.reserve(s1.size() + s2.size() + s3.size() + s4.size()); + result.append(s2); + result.append(s3); + result.append(s4); + return result; +} + + +template +S cat(const S& s1, const S& s2, const S& s3, const S& s4, const S& s5) + /// Concatenates five strings. +{ + S result = s1; + result.reserve(s1.size() + s2.size() + s3.size() + s4.size() + s5.size()); + result.append(s2); + result.append(s3); + result.append(s4); + result.append(s5); + return result; +} + + +template +S cat(const S& s1, const S& s2, const S& s3, const S& s4, const S& s5, const S& s6) + /// Concatenates six strings. +{ + S result = s1; + result.reserve(s1.size() + s2.size() + s3.size() + s4.size() + s5.size() + s6.size()); + result.append(s2); + result.append(s3); + result.append(s4); + result.append(s5); + result.append(s6); + return result; +} + + +template +S cat(const S& delim, const It& begin, const It& end) + /// Concatenates a sequence of strings, delimited + /// by the string given in delim. +{ + S result; + for (It it = begin; it != end; ++it) + { + if (!result.empty()) result.append(delim); + result += *it; + } + return result; +} + + +} // namespace Poco + + +#endif // Foundation_String_INCLUDED diff --git a/Foundation/include/Poco/StringTokenizer.h b/Foundation/include/Poco/StringTokenizer.h index 401c89668..252ed8e96 100644 --- a/Foundation/include/Poco/StringTokenizer.h +++ b/Foundation/include/Poco/StringTokenizer.h @@ -1,130 +1,130 @@ -// -// StringTokenizer.h -// -// $Id: //poco/1.2/Foundation/include/Poco/StringTokenizer.h#1 $ -// -// Library: Foundation -// Package: Core -// Module: StringTokenizer -// -// Definition of the StringTokenizer class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_StringTokenizer_INCLUDED -#define Foundation_StringTokenizer_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/Exception.h" -#include - - -namespace Poco { - - -class Foundation_API StringTokenizer - /// A simple tokenizer that splits a string into - /// tokens, which are separated by separator characters. - /// An iterator is used to iterate over all tokens. -{ -public: - enum Options - { - TOK_IGNORE_EMPTY = 1, /// ignore empty tokens - TOK_TRIM = 2 /// remove leading and trailing whitespace from tokens - }; - - typedef std::vector::const_iterator Iterator; - - StringTokenizer(const std::string& str, const std::string& separators, int options = 0); - /// Splits the given string into tokens. The tokens are expected to be - /// separated by one of the separator characters given in separators. - /// Additionally, options can be specified: - /// * TOK_IGNORE_EMPTY: empty tokens are ignored - /// * TOK_TRIM: trailing and leading whitespace is removed from tokens. - /// An empty token at the end of str is always ignored. For example, - /// a StringTokenizer with the following arguments: - /// StringTokenizer(",ab,cd,", ","); - /// will produce three tokens, "", "ab" and "cd". - - ~StringTokenizer(); - /// Destroys the tokenizer. - - Iterator begin() const; - Iterator end() const; - - const std::string& operator [] (int index) const; - /// Returns the index'th token. - /// Throws a RangeException if the index is out of range. - - int count() const; - /// Returns the number of tokens. - -private: - StringTokenizer(const StringTokenizer&); - StringTokenizer& operator = (const StringTokenizer&); - - std::vector _tokens; -}; - - -// -// inlines -// - - -inline StringTokenizer::Iterator StringTokenizer::begin() const -{ - return _tokens.begin(); -} - - -inline StringTokenizer::Iterator StringTokenizer::end() const -{ - return _tokens.end(); -} - - -inline const std::string& StringTokenizer::operator [] (int index) const -{ - if (index < 0 || index >= _tokens.size()) throw RangeException(); - return _tokens[index]; -} - - -inline int StringTokenizer::count() const -{ - return (int) _tokens.size(); -} - - -} // namespace Poco - - -#endif // Foundation_StringTokenizer_INCLUDED +// +// StringTokenizer.h +// +// $Id: //poco/1.2/Foundation/include/Poco/StringTokenizer.h#1 $ +// +// Library: Foundation +// Package: Core +// Module: StringTokenizer +// +// Definition of the StringTokenizer class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_StringTokenizer_INCLUDED +#define Foundation_StringTokenizer_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Exception.h" +#include + + +namespace Poco { + + +class Foundation_API StringTokenizer + /// A simple tokenizer that splits a string into + /// tokens, which are separated by separator characters. + /// An iterator is used to iterate over all tokens. +{ +public: + enum Options + { + TOK_IGNORE_EMPTY = 1, /// ignore empty tokens + TOK_TRIM = 2 /// remove leading and trailing whitespace from tokens + }; + + typedef std::vector::const_iterator Iterator; + + StringTokenizer(const std::string& str, const std::string& separators, int options = 0); + /// Splits the given string into tokens. The tokens are expected to be + /// separated by one of the separator characters given in separators. + /// Additionally, options can be specified: + /// * TOK_IGNORE_EMPTY: empty tokens are ignored + /// * TOK_TRIM: trailing and leading whitespace is removed from tokens. + /// An empty token at the end of str is always ignored. For example, + /// a StringTokenizer with the following arguments: + /// StringTokenizer(",ab,cd,", ","); + /// will produce three tokens, "", "ab" and "cd". + + ~StringTokenizer(); + /// Destroys the tokenizer. + + Iterator begin() const; + Iterator end() const; + + const std::string& operator [] (int index) const; + /// Returns the index'th token. + /// Throws a RangeException if the index is out of range. + + int count() const; + /// Returns the number of tokens. + +private: + StringTokenizer(const StringTokenizer&); + StringTokenizer& operator = (const StringTokenizer&); + + std::vector _tokens; +}; + + +// +// inlines +// + + +inline StringTokenizer::Iterator StringTokenizer::begin() const +{ + return _tokens.begin(); +} + + +inline StringTokenizer::Iterator StringTokenizer::end() const +{ + return _tokens.end(); +} + + +inline const std::string& StringTokenizer::operator [] (int index) const +{ + if (index < 0 || index >= _tokens.size()) throw RangeException(); + return _tokens[index]; +} + + +inline int StringTokenizer::count() const +{ + return (int) _tokens.size(); +} + + +} // namespace Poco + + +#endif // Foundation_StringTokenizer_INCLUDED diff --git a/Foundation/include/Poco/SynchronizedObject.h b/Foundation/include/Poco/SynchronizedObject.h index 0e3ff5cd7..9d147646f 100644 --- a/Foundation/include/Poco/SynchronizedObject.h +++ b/Foundation/include/Poco/SynchronizedObject.h @@ -1,153 +1,153 @@ -// -// SynchronizedObject.h -// -// $Id: //poco/1.2/Foundation/include/Poco/SynchronizedObject.h#1 $ -// -// Library: Foundation -// Package: Threading -// Module: SynchronizedObject -// -// Definition of the SynchronizedObject class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_SynchronizedObject_INCLUDED -#define Foundation_SynchronizedObject_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/Mutex.h" -#include "Poco/Event.h" - - -namespace Poco { - - -class Foundation_API SynchronizedObject - /// This class aggregates a Mutex and an Event - /// and can act as a base class for all objects - /// requiring synchronization in a multithreaded - /// scenario. -{ -public: - typedef Poco::ScopedLock ScopedLock; - - SynchronizedObject(); - /// Creates the object. - - virtual ~SynchronizedObject(); - /// Destroys the object. - - void lock() const; - /// Locks the object. Blocks if the object - /// is locked by another thread. - - bool tryLock() const; - /// Tries to lock the object. Returns false immediately - /// if the object is already locked by another thread - /// Returns true if the object was successfully locked. - - void unlock() const; - /// Unlocks the object so that it can be locked by - /// other threads. - - void notify() const; - /// Signals the object. - /// Exactly only one thread waiting for the object - /// can resume execution. - - void wait() const; - /// Waits for the object to become signalled. - - void wait(long milliseconds) const; - /// Waits for the object to become signalled. - /// Throws a TimeOutException if the object - /// does not become signalled within the specified - /// time interval. - - bool tryWait(long milliseconds) const; - /// Waits for the object to become signalled. - /// Returns true if the object - /// became signalled within the specified - /// time interval, false otherwise. - -private: - mutable Mutex _mutex; - mutable Event _event; -}; - - -// -// inlines -// -inline void SynchronizedObject::lock() const -{ - _mutex.lock(); -} - - -inline bool SynchronizedObject::tryLock() const -{ - return _mutex.tryLock(); -} - - -inline void SynchronizedObject::unlock() const -{ - _mutex.unlock(); -} - - -inline void SynchronizedObject::notify() const -{ - _event.set(); -} - - -inline void SynchronizedObject::wait() const -{ - _event.wait(); -} - - -inline void SynchronizedObject::wait(long milliseconds) const -{ - _event.wait(milliseconds); -} - - -inline bool SynchronizedObject::tryWait(long milliseconds) const -{ - return _event.tryWait(milliseconds); -} - - -} // namespace Poco - - -#endif // Foundation_SynchronizedObject_INCLUDED +// +// SynchronizedObject.h +// +// $Id: //poco/1.2/Foundation/include/Poco/SynchronizedObject.h#1 $ +// +// Library: Foundation +// Package: Threading +// Module: SynchronizedObject +// +// Definition of the SynchronizedObject class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_SynchronizedObject_INCLUDED +#define Foundation_SynchronizedObject_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Mutex.h" +#include "Poco/Event.h" + + +namespace Poco { + + +class Foundation_API SynchronizedObject + /// This class aggregates a Mutex and an Event + /// and can act as a base class for all objects + /// requiring synchronization in a multithreaded + /// scenario. +{ +public: + typedef Poco::ScopedLock ScopedLock; + + SynchronizedObject(); + /// Creates the object. + + virtual ~SynchronizedObject(); + /// Destroys the object. + + void lock() const; + /// Locks the object. Blocks if the object + /// is locked by another thread. + + bool tryLock() const; + /// Tries to lock the object. Returns false immediately + /// if the object is already locked by another thread + /// Returns true if the object was successfully locked. + + void unlock() const; + /// Unlocks the object so that it can be locked by + /// other threads. + + void notify() const; + /// Signals the object. + /// Exactly only one thread waiting for the object + /// can resume execution. + + void wait() const; + /// Waits for the object to become signalled. + + void wait(long milliseconds) const; + /// Waits for the object to become signalled. + /// Throws a TimeOutException if the object + /// does not become signalled within the specified + /// time interval. + + bool tryWait(long milliseconds) const; + /// Waits for the object to become signalled. + /// Returns true if the object + /// became signalled within the specified + /// time interval, false otherwise. + +private: + mutable Mutex _mutex; + mutable Event _event; +}; + + +// +// inlines +// +inline void SynchronizedObject::lock() const +{ + _mutex.lock(); +} + + +inline bool SynchronizedObject::tryLock() const +{ + return _mutex.tryLock(); +} + + +inline void SynchronizedObject::unlock() const +{ + _mutex.unlock(); +} + + +inline void SynchronizedObject::notify() const +{ + _event.set(); +} + + +inline void SynchronizedObject::wait() const +{ + _event.wait(); +} + + +inline void SynchronizedObject::wait(long milliseconds) const +{ + _event.wait(milliseconds); +} + + +inline bool SynchronizedObject::tryWait(long milliseconds) const +{ + return _event.tryWait(milliseconds); +} + + +} // namespace Poco + + +#endif // Foundation_SynchronizedObject_INCLUDED diff --git a/Foundation/include/Poco/SyslogChannel.h b/Foundation/include/Poco/SyslogChannel.h index 831265165..ef32b1378 100644 --- a/Foundation/include/Poco/SyslogChannel.h +++ b/Foundation/include/Poco/SyslogChannel.h @@ -1,131 +1,131 @@ -// -// SyslogChannel.h -// -// $Id: //poco/1.2/Foundation/include/Poco/SyslogChannel.h#1 $ -// -// Library: Foundation -// Package: Logging -// Module: SyslogChannel -// -// Definition of the SyslogChannel class specific to UNIX. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_SyslogChannel_INCLUDED -#define Foundation_SyslogChannel_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/Channel.h" - - -namespace Poco { - - -class Foundation_API SyslogChannel: public Channel - /// This Unix-only channel works with the Unix syslog service. -{ -public: - enum Option - { - SYSLOG_PID = 0x01, /// log the pid with each message - SYSLOG_CONS = 0x02, /// log on the console if errors in sending - SYSLOG_NDELAY = 0x08, /// don't delay open - SYSLOG_PERROR = 0x20 /// log to stderr as well (not supported on all platforms) - }; - - enum Facility - { - SYSLOG_KERN = ( 0<<3), /// kernel messages - SYSLOG_USER = ( 1<<3), /// random user-level messages - SYSLOG_MAIL = ( 2<<3), /// mail system - SYSLOG_DAEMON = ( 3<<3), /// system daemons - SYSLOG_AUTH = ( 4<<3), /// security/authorization messages - SYSLOG_SYSLOG = ( 5<<3), /// messages generated internally by syslogd - SYSLOG_LPR = ( 6<<3), /// line printer subsystem - SYSLOG_NEWS = ( 7<<3), /// network news subsystem - SYSLOG_UUCP = ( 8<<3), /// UUCP subsystem - SYSLOG_CRON = ( 9<<3), /// clock daemon - SYSLOG_AUTHPRIV = (10<<3), /// security/authorization messages (private) - SYSLOG_FTP = (11<<3), /// ftp daemon - SYSLOG_LOCAL0 = (16<<3), /// reserved for local use - SYSLOG_LOCAL1 = (17<<3), /// reserved for local use - SYSLOG_LOCAL2 = (18<<3), /// reserved for local use - SYSLOG_LOCAL3 = (19<<3), /// reserved for local use - SYSLOG_LOCAL4 = (20<<3), /// reserved for local use - SYSLOG_LOCAL5 = (21<<3), /// reserved for local use - SYSLOG_LOCAL6 = (22<<3), /// reserved for local use - SYSLOG_LOCAL7 = (23<<3) /// reserved for local use - }; - - SyslogChannel(); - /// Creates a SyslogChannel. - - SyslogChannel(const std::string& name, int options = SYSLOG_CONS, int facility = SYSLOG_USER); - /// Creates a SyslogChannel with the given name, options and facility. - - void open(); - /// Opens the SyslogChannel. - - void close(); - /// Closes the SyslogChannel. - - void log(const Message& msg); - /// Sens the message's text to the syslog service. - - void setProperty(const std::string& name, const std::string& value); - /// Sets the property with the given value. - /// - /// The following properties are supported: - /// * name: The name used to identify the source of log messages. - /// * facility: The facility added to each log message. See the Facility enumeration for a list of supported values. - /// * options: The logging options. See the Option enumeration for a list of supported values. - - std::string getProperty(const std::string& name) const; - /// Returns the value of the property with the given name. - - static const std::string PROP_NAME; - static const std::string PROP_FACILITY; - static const std::string PROP_OPTIONS; - -protected: - ~SyslogChannel(); - static int getPrio(const Message& msg); - -private: - std::string _name; - int _options; - int _facility; - bool _open; -}; - - -} // namespace Poco - - -#endif // Foundation_SyslogChannel_INCLUDED +// +// SyslogChannel.h +// +// $Id: //poco/1.2/Foundation/include/Poco/SyslogChannel.h#1 $ +// +// Library: Foundation +// Package: Logging +// Module: SyslogChannel +// +// Definition of the SyslogChannel class specific to UNIX. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_SyslogChannel_INCLUDED +#define Foundation_SyslogChannel_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Channel.h" + + +namespace Poco { + + +class Foundation_API SyslogChannel: public Channel + /// This Unix-only channel works with the Unix syslog service. +{ +public: + enum Option + { + SYSLOG_PID = 0x01, /// log the pid with each message + SYSLOG_CONS = 0x02, /// log on the console if errors in sending + SYSLOG_NDELAY = 0x08, /// don't delay open + SYSLOG_PERROR = 0x20 /// log to stderr as well (not supported on all platforms) + }; + + enum Facility + { + SYSLOG_KERN = ( 0<<3), /// kernel messages + SYSLOG_USER = ( 1<<3), /// random user-level messages + SYSLOG_MAIL = ( 2<<3), /// mail system + SYSLOG_DAEMON = ( 3<<3), /// system daemons + SYSLOG_AUTH = ( 4<<3), /// security/authorization messages + SYSLOG_SYSLOG = ( 5<<3), /// messages generated internally by syslogd + SYSLOG_LPR = ( 6<<3), /// line printer subsystem + SYSLOG_NEWS = ( 7<<3), /// network news subsystem + SYSLOG_UUCP = ( 8<<3), /// UUCP subsystem + SYSLOG_CRON = ( 9<<3), /// clock daemon + SYSLOG_AUTHPRIV = (10<<3), /// security/authorization messages (private) + SYSLOG_FTP = (11<<3), /// ftp daemon + SYSLOG_LOCAL0 = (16<<3), /// reserved for local use + SYSLOG_LOCAL1 = (17<<3), /// reserved for local use + SYSLOG_LOCAL2 = (18<<3), /// reserved for local use + SYSLOG_LOCAL3 = (19<<3), /// reserved for local use + SYSLOG_LOCAL4 = (20<<3), /// reserved for local use + SYSLOG_LOCAL5 = (21<<3), /// reserved for local use + SYSLOG_LOCAL6 = (22<<3), /// reserved for local use + SYSLOG_LOCAL7 = (23<<3) /// reserved for local use + }; + + SyslogChannel(); + /// Creates a SyslogChannel. + + SyslogChannel(const std::string& name, int options = SYSLOG_CONS, int facility = SYSLOG_USER); + /// Creates a SyslogChannel with the given name, options and facility. + + void open(); + /// Opens the SyslogChannel. + + void close(); + /// Closes the SyslogChannel. + + void log(const Message& msg); + /// Sens the message's text to the syslog service. + + void setProperty(const std::string& name, const std::string& value); + /// Sets the property with the given value. + /// + /// The following properties are supported: + /// * name: The name used to identify the source of log messages. + /// * facility: The facility added to each log message. See the Facility enumeration for a list of supported values. + /// * options: The logging options. See the Option enumeration for a list of supported values. + + std::string getProperty(const std::string& name) const; + /// Returns the value of the property with the given name. + + static const std::string PROP_NAME; + static const std::string PROP_FACILITY; + static const std::string PROP_OPTIONS; + +protected: + ~SyslogChannel(); + static int getPrio(const Message& msg); + +private: + std::string _name; + int _options; + int _facility; + bool _open; +}; + + +} // namespace Poco + + +#endif // Foundation_SyslogChannel_INCLUDED diff --git a/Foundation/include/Poco/Task.h b/Foundation/include/Poco/Task.h index 3bc62a9b7..5632d1a37 100644 --- a/Foundation/include/Poco/Task.h +++ b/Foundation/include/Poco/Task.h @@ -1,207 +1,207 @@ -// -// Task.h -// -// $Id: //poco/1.2/Foundation/include/Poco/Task.h#1 $ -// -// Library: Foundation -// Package: Tasks -// Module: Tasks -// -// Definition of the Task class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_Task_INCLUDED -#define Foundation_Task_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/Runnable.h" -#include "Poco/RefCountedObject.h" -#include "Poco/Mutex.h" -#include "Poco/Event.h" - - -namespace Poco { - - -class TaskManager; -class Notification; -class NotificationCenter; - - -class Foundation_API Task: public Runnable, public RefCountedObject - /// A Task is a subclass of Runnable that has a name - /// and supports progress reporting and cancellation. - /// - /// A TaskManager object can be used to take care of the - /// lifecycle of a Task. -{ -public: - enum TaskState - { - TASK_IDLE, - TASK_STARTING, - TASK_RUNNING, - TASK_CANCELLING, - TASK_FINISHED - }; - - Task(const std::string& name); - /// Creates the Task. - - const std::string& name() const; - /// Returns the task's name. - - float progress() const; - /// Returns the task's progress. - /// The value will be between 0.0 (just started) - /// and 1.0 (completed). - - void cancel(); - /// Requests the task to cancel itself. For cancellation - /// to work, the task's runTask() method must periodically - /// call isCancelled() and react accordingly. - - bool isCancelled() const; - /// Returns true if cancellation of the task has been - /// requested. - /// - /// A Task's runTask() method should periodically - /// call this method and stop whatever it is doing in an - /// orderly way when this method returns true. - - TaskState state() const; - /// Returns the task's current state. - - void reset(); - /// Sets the task's progress to zero and clears the - /// cancel flag. - - virtual void runTask() = 0; - /// Do whatever the task needs to do. Must - /// be overridden by subclasses. - - void run(); - /// Calls the task's runTask() method and notifies the owner - /// of the task's start and completion. - -protected: - bool sleep(long milliseconds); - /// Suspends the current thread for the specified - /// amount of time. - /// - /// If the task is cancelled while it is sleeping, - /// sleep() will return immediately and the return - /// value will be true. If the time interval - /// passes without the task being cancelled, the - /// return value is false. - /// - /// A Task should use this method in favor of Thread::sleep(). - - void setProgress(float progress); - /// Sets the task's progress. - /// The value should be between 0.0 (just started) - /// and 1.0 (completed). - - virtual void postNotification(Notification* pNf); - /// Posts a notification to the task manager's - /// notification center. - /// - /// A task can use this method to post custom - /// notifications about its progress. - - void setOwner(TaskManager* pOwner); - /// Sets the (optional) owner of the task. - - TaskManager* getOwner() const; - /// Returns the owner of the task, which may be NULL. - - void setState(TaskState state); - /// Sets the task's state. - - virtual ~Task(); - /// Destroys the Task. - -private: - Task(); - Task(const Task&); - Task& operator = (const Task&); - - std::string _name; - TaskManager* _pOwner; - float _progress; - TaskState _state; - Event _cancelEvent; - mutable FastMutex _mutex; - - friend class TaskManager; -}; - - -// -// inlines -// -inline const std::string& Task::name() const -{ - return _name; -} - - -inline float Task::progress() const -{ - FastMutex::ScopedLock lock(_mutex); - - return _progress; -} - - -inline bool Task::isCancelled() const -{ - return _state == TASK_CANCELLING; -} - - -inline Task::TaskState Task::state() const -{ - return _state; -} - - -inline TaskManager* Task::getOwner() const -{ - FastMutex::ScopedLock lock(_mutex); - - return _pOwner; -} - - -} // namespace Poco - - -#endif // Foundation_Task_INCLUDED +// +// Task.h +// +// $Id: //poco/1.2/Foundation/include/Poco/Task.h#1 $ +// +// Library: Foundation +// Package: Tasks +// Module: Tasks +// +// Definition of the Task class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_Task_INCLUDED +#define Foundation_Task_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Runnable.h" +#include "Poco/RefCountedObject.h" +#include "Poco/Mutex.h" +#include "Poco/Event.h" + + +namespace Poco { + + +class TaskManager; +class Notification; +class NotificationCenter; + + +class Foundation_API Task: public Runnable, public RefCountedObject + /// A Task is a subclass of Runnable that has a name + /// and supports progress reporting and cancellation. + /// + /// A TaskManager object can be used to take care of the + /// lifecycle of a Task. +{ +public: + enum TaskState + { + TASK_IDLE, + TASK_STARTING, + TASK_RUNNING, + TASK_CANCELLING, + TASK_FINISHED + }; + + Task(const std::string& name); + /// Creates the Task. + + const std::string& name() const; + /// Returns the task's name. + + float progress() const; + /// Returns the task's progress. + /// The value will be between 0.0 (just started) + /// and 1.0 (completed). + + void cancel(); + /// Requests the task to cancel itself. For cancellation + /// to work, the task's runTask() method must periodically + /// call isCancelled() and react accordingly. + + bool isCancelled() const; + /// Returns true if cancellation of the task has been + /// requested. + /// + /// A Task's runTask() method should periodically + /// call this method and stop whatever it is doing in an + /// orderly way when this method returns true. + + TaskState state() const; + /// Returns the task's current state. + + void reset(); + /// Sets the task's progress to zero and clears the + /// cancel flag. + + virtual void runTask() = 0; + /// Do whatever the task needs to do. Must + /// be overridden by subclasses. + + void run(); + /// Calls the task's runTask() method and notifies the owner + /// of the task's start and completion. + +protected: + bool sleep(long milliseconds); + /// Suspends the current thread for the specified + /// amount of time. + /// + /// If the task is cancelled while it is sleeping, + /// sleep() will return immediately and the return + /// value will be true. If the time interval + /// passes without the task being cancelled, the + /// return value is false. + /// + /// A Task should use this method in favor of Thread::sleep(). + + void setProgress(float progress); + /// Sets the task's progress. + /// The value should be between 0.0 (just started) + /// and 1.0 (completed). + + virtual void postNotification(Notification* pNf); + /// Posts a notification to the task manager's + /// notification center. + /// + /// A task can use this method to post custom + /// notifications about its progress. + + void setOwner(TaskManager* pOwner); + /// Sets the (optional) owner of the task. + + TaskManager* getOwner() const; + /// Returns the owner of the task, which may be NULL. + + void setState(TaskState state); + /// Sets the task's state. + + virtual ~Task(); + /// Destroys the Task. + +private: + Task(); + Task(const Task&); + Task& operator = (const Task&); + + std::string _name; + TaskManager* _pOwner; + float _progress; + TaskState _state; + Event _cancelEvent; + mutable FastMutex _mutex; + + friend class TaskManager; +}; + + +// +// inlines +// +inline const std::string& Task::name() const +{ + return _name; +} + + +inline float Task::progress() const +{ + FastMutex::ScopedLock lock(_mutex); + + return _progress; +} + + +inline bool Task::isCancelled() const +{ + return _state == TASK_CANCELLING; +} + + +inline Task::TaskState Task::state() const +{ + return _state; +} + + +inline TaskManager* Task::getOwner() const +{ + FastMutex::ScopedLock lock(_mutex); + + return _pOwner; +} + + +} // namespace Poco + + +#endif // Foundation_Task_INCLUDED diff --git a/Foundation/include/Poco/TaskManager.h b/Foundation/include/Poco/TaskManager.h index 1048568bd..de10084af 100644 --- a/Foundation/include/Poco/TaskManager.h +++ b/Foundation/include/Poco/TaskManager.h @@ -1,153 +1,153 @@ -// -// TaskManager.h -// -// $Id: //poco/1.2/Foundation/include/Poco/TaskManager.h#1 $ -// -// Library: Foundation -// Package: Tasks -// Module: Tasks -// -// Definition of the TaskManager class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_TaskManager_INCLUDED -#define Foundation_TaskManager_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/Mutex.h" -#include "Poco/Task.h" -#include "Poco/AutoPtr.h" -#include "Poco/NotificationCenter.h" -#include "Poco/Timestamp.h" -#include - - -namespace Poco { - - -class Notification; -class ThreadPool; -class Exception; - - -class Foundation_API TaskManager - /// The TaskManager manages a collection of tasks - /// and monitors their lifetime. - /// - /// A TaskManager has a built-in NotificationCenter that - /// is used to send out notifications on task progress - /// and task states. See the TaskNotification class and its - /// subclasses for the various events that result in a notification. - /// To keep the number of notifications small, a TaskProgressNotification - /// will only be sent out once in 100 milliseconds. -{ -public: - typedef AutoPtr TaskPtr; - typedef std::list TaskList; - - TaskManager(); - /// Creates the TaskManager, using the - /// default ThreadPool. - - TaskManager(ThreadPool& pool); - /// Creates the TaskManager, using the - /// given ThreadPool. - - ~TaskManager(); - /// Destroys the TaskManager. - - void start(Task* pTask); - /// Starts the given task in a thread obtained - /// from the thread pool. - /// - /// The TaskManager takes ownership of the Task object - /// and deletes it when it it finished. - - void cancelAll(); - /// Requests cancellation of all tasks. - - void joinAll(); - /// Waits for the completion of all the threads - /// in the TaskManager's thread pool. - - TaskList taskList() const; - /// Returns a copy of the internal task list. - - int count() const; - /// Returns the number of tasks in the internal task list. - - void addObserver(const AbstractObserver& observer); - /// Registers an observer with the NotificationCenter. - /// Usage: - /// Observer obs(*this, &MyClass::handleNotification); - /// notificationCenter.addObserver(obs); - - void removeObserver(const AbstractObserver& observer); - /// Unregisters an observer with the NotificationCenter. - - static const int MIN_PROGRESS_NOTIFICATION_INTERVAL; - -protected: - void postNotification(Notification* pNf); - /// Posts a notification to the task manager's - /// notification center. - - void taskStarted(Task* pTask); - void taskProgress(Task* pTask, float progress); - void taskCancelled(Task* pTask); - void taskFinished(Task* pTask); - void taskFailed(Task* pTask, const Exception& exc); - -private: - ThreadPool& _threadPool; - TaskList _taskList; - Timestamp _lastProgressNotification; - NotificationCenter _nc; - mutable FastMutex _mutex; - - friend class Task; -}; - - -// -// inlines -// -inline int TaskManager::count() const -{ - FastMutex::ScopedLock lock(_mutex); - - return (int) _taskList.size(); -} - - -} // namespace Poco - - -#endif // Foundation_TaskManager_INCLUDED +// +// TaskManager.h +// +// $Id: //poco/1.2/Foundation/include/Poco/TaskManager.h#1 $ +// +// Library: Foundation +// Package: Tasks +// Module: Tasks +// +// Definition of the TaskManager class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_TaskManager_INCLUDED +#define Foundation_TaskManager_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Mutex.h" +#include "Poco/Task.h" +#include "Poco/AutoPtr.h" +#include "Poco/NotificationCenter.h" +#include "Poco/Timestamp.h" +#include + + +namespace Poco { + + +class Notification; +class ThreadPool; +class Exception; + + +class Foundation_API TaskManager + /// The TaskManager manages a collection of tasks + /// and monitors their lifetime. + /// + /// A TaskManager has a built-in NotificationCenter that + /// is used to send out notifications on task progress + /// and task states. See the TaskNotification class and its + /// subclasses for the various events that result in a notification. + /// To keep the number of notifications small, a TaskProgressNotification + /// will only be sent out once in 100 milliseconds. +{ +public: + typedef AutoPtr TaskPtr; + typedef std::list TaskList; + + TaskManager(); + /// Creates the TaskManager, using the + /// default ThreadPool. + + TaskManager(ThreadPool& pool); + /// Creates the TaskManager, using the + /// given ThreadPool. + + ~TaskManager(); + /// Destroys the TaskManager. + + void start(Task* pTask); + /// Starts the given task in a thread obtained + /// from the thread pool. + /// + /// The TaskManager takes ownership of the Task object + /// and deletes it when it it finished. + + void cancelAll(); + /// Requests cancellation of all tasks. + + void joinAll(); + /// Waits for the completion of all the threads + /// in the TaskManager's thread pool. + + TaskList taskList() const; + /// Returns a copy of the internal task list. + + int count() const; + /// Returns the number of tasks in the internal task list. + + void addObserver(const AbstractObserver& observer); + /// Registers an observer with the NotificationCenter. + /// Usage: + /// Observer obs(*this, &MyClass::handleNotification); + /// notificationCenter.addObserver(obs); + + void removeObserver(const AbstractObserver& observer); + /// Unregisters an observer with the NotificationCenter. + + static const int MIN_PROGRESS_NOTIFICATION_INTERVAL; + +protected: + void postNotification(Notification* pNf); + /// Posts a notification to the task manager's + /// notification center. + + void taskStarted(Task* pTask); + void taskProgress(Task* pTask, float progress); + void taskCancelled(Task* pTask); + void taskFinished(Task* pTask); + void taskFailed(Task* pTask, const Exception& exc); + +private: + ThreadPool& _threadPool; + TaskList _taskList; + Timestamp _lastProgressNotification; + NotificationCenter _nc; + mutable FastMutex _mutex; + + friend class Task; +}; + + +// +// inlines +// +inline int TaskManager::count() const +{ + FastMutex::ScopedLock lock(_mutex); + + return (int) _taskList.size(); +} + + +} // namespace Poco + + +#endif // Foundation_TaskManager_INCLUDED diff --git a/Foundation/include/Poco/TaskNotification.h b/Foundation/include/Poco/TaskNotification.h index 8a97e411c..eb7acd70c 100644 --- a/Foundation/include/Poco/TaskNotification.h +++ b/Foundation/include/Poco/TaskNotification.h @@ -1,192 +1,192 @@ -// -// TaskNotification.h -// -// $Id: //poco/1.2/Foundation/include/Poco/TaskNotification.h#1 $ -// -// Library: Foundation -// Package: Tasks -// Module: Tasks -// -// Definition of the TaskNotification class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_TaskNotification_INCLUDED -#define Foundation_TaskNotification_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/Notification.h" -#include "Poco/Task.h" - - -namespace Poco { - - -class Foundation_API TaskNotification: public Notification - /// Base class for TaskManager notifications. -{ -public: - TaskNotification(Task* pTask); - /// Creates the TaskNotification. - - Task* task() const; - /// Returns the subject of the notification. - -protected: - virtual ~TaskNotification(); - /// Destroys the TaskNotification. - -private: - Task* _pTask; -}; - - -class Foundation_API TaskStartedNotification: public TaskNotification - /// This notification is posted by the TaskManager for - /// every task that has been started. -{ -public: - TaskStartedNotification(Task* pTask); - -protected: - ~TaskStartedNotification(); -}; - - -class Foundation_API TaskCancelledNotification: public TaskNotification - /// This notification is posted by the TaskManager for - /// every task that has been cancelled. -{ -public: - TaskCancelledNotification(Task* pTask); - -protected: - ~TaskCancelledNotification(); -}; - - -class Foundation_API TaskFinishedNotification: public TaskNotification - /// This notification is posted by the TaskManager for - /// every task that has finished. -{ -public: - TaskFinishedNotification(Task* pTask); - -protected: - ~TaskFinishedNotification(); -}; - - -class Foundation_API TaskFailedNotification: public TaskNotification - /// This notification is posted by the TaskManager for - /// every task that has failed with an exception. -{ -public: - TaskFailedNotification(Task* pTask, const Exception& exc); - - const Exception& reason() const; - -protected: - ~TaskFailedNotification(); - -private: - Exception* _pException; -}; - - -class Foundation_API TaskProgressNotification: public TaskNotification - /// This notification is posted by the TaskManager for - /// every task that has failed with an exception. -{ -public: - TaskProgressNotification(Task* pTask, float progress); - - float progress() const; - -protected: - ~TaskProgressNotification(); - -private: - float _progress; -}; - - -template -class TaskCustomNotification: public TaskNotification - /// This is a template for "custom" notification. - /// Unlike other notifications, this notification - /// is instantiated and posted by the task itself. - /// The purpose is to provide generic notifiation - /// mechanism between the task and its observer(s). -{ -public: - TaskCustomNotification(Task* pTask, C& custom): - TaskNotification(pTask), - _custom(custom) - { - } - - const C& custom() const - { - return _custom; - } - -protected: - ~TaskCustomNotification(){}; - -private: - C _custom; -}; - - -// -// inlines -// -inline Task* TaskNotification::task() const -{ - return _pTask; -} - - -inline const Exception& TaskFailedNotification::reason() const -{ - return *_pException; -} - - -inline float TaskProgressNotification::progress() const -{ - return _progress; -} - - -} // namespace Poco - - -#endif // Foundation_TaskNotification_INCLUDED +// +// TaskNotification.h +// +// $Id: //poco/1.2/Foundation/include/Poco/TaskNotification.h#1 $ +// +// Library: Foundation +// Package: Tasks +// Module: Tasks +// +// Definition of the TaskNotification class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_TaskNotification_INCLUDED +#define Foundation_TaskNotification_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Notification.h" +#include "Poco/Task.h" + + +namespace Poco { + + +class Foundation_API TaskNotification: public Notification + /// Base class for TaskManager notifications. +{ +public: + TaskNotification(Task* pTask); + /// Creates the TaskNotification. + + Task* task() const; + /// Returns the subject of the notification. + +protected: + virtual ~TaskNotification(); + /// Destroys the TaskNotification. + +private: + Task* _pTask; +}; + + +class Foundation_API TaskStartedNotification: public TaskNotification + /// This notification is posted by the TaskManager for + /// every task that has been started. +{ +public: + TaskStartedNotification(Task* pTask); + +protected: + ~TaskStartedNotification(); +}; + + +class Foundation_API TaskCancelledNotification: public TaskNotification + /// This notification is posted by the TaskManager for + /// every task that has been cancelled. +{ +public: + TaskCancelledNotification(Task* pTask); + +protected: + ~TaskCancelledNotification(); +}; + + +class Foundation_API TaskFinishedNotification: public TaskNotification + /// This notification is posted by the TaskManager for + /// every task that has finished. +{ +public: + TaskFinishedNotification(Task* pTask); + +protected: + ~TaskFinishedNotification(); +}; + + +class Foundation_API TaskFailedNotification: public TaskNotification + /// This notification is posted by the TaskManager for + /// every task that has failed with an exception. +{ +public: + TaskFailedNotification(Task* pTask, const Exception& exc); + + const Exception& reason() const; + +protected: + ~TaskFailedNotification(); + +private: + Exception* _pException; +}; + + +class Foundation_API TaskProgressNotification: public TaskNotification + /// This notification is posted by the TaskManager for + /// every task that has failed with an exception. +{ +public: + TaskProgressNotification(Task* pTask, float progress); + + float progress() const; + +protected: + ~TaskProgressNotification(); + +private: + float _progress; +}; + + +template +class TaskCustomNotification: public TaskNotification + /// This is a template for "custom" notification. + /// Unlike other notifications, this notification + /// is instantiated and posted by the task itself. + /// The purpose is to provide generic notifiation + /// mechanism between the task and its observer(s). +{ +public: + TaskCustomNotification(Task* pTask, C& custom): + TaskNotification(pTask), + _custom(custom) + { + } + + const C& custom() const + { + return _custom; + } + +protected: + ~TaskCustomNotification(){}; + +private: + C _custom; +}; + + +// +// inlines +// +inline Task* TaskNotification::task() const +{ + return _pTask; +} + + +inline const Exception& TaskFailedNotification::reason() const +{ + return *_pException; +} + + +inline float TaskProgressNotification::progress() const +{ + return _progress; +} + + +} // namespace Poco + + +#endif // Foundation_TaskNotification_INCLUDED diff --git a/Foundation/include/Poco/TeeStream.h b/Foundation/include/Poco/TeeStream.h index 8f05c8529..dfd151d5c 100644 --- a/Foundation/include/Poco/TeeStream.h +++ b/Foundation/include/Poco/TeeStream.h @@ -1,154 +1,154 @@ -// -// TeeStream.h -// -// $Id: //poco/1.2/Foundation/include/Poco/TeeStream.h#1 $ -// -// Library: Foundation -// Package: Streams -// Module: TeeStream -// -// Definition of the TeeStream class. -// -// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_TeeStream_INCLUDED -#define Foundation_TeeStream_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/UnbufferedStreamBuf.h" -#include -#include -#include - - -namespace Poco { - - -class Foundation_API TeeStreamBuf: public UnbufferedStreamBuf - /// This stream buffer copies all data written to or - /// read from it to one or multiple output streams. -{ -public: - TeeStreamBuf(); - /// Creates an unconnected CountingStreamBuf. - /// Use addStream() to attach output streams. - - TeeStreamBuf(std::istream& istr); - /// Creates the CountingStreamBuf and connects it - /// to the given input stream. - - TeeStreamBuf(std::ostream& ostr); - /// Creates the CountingStreamBuf and connects it - /// to the given output stream. - - ~TeeStreamBuf(); - /// Destroys the CountingStream. - - void addStream(std::ostream& ostr); - /// Adds the given output stream. - -protected: - int readFromDevice(); - int writeToDevice(char c); - -private: - typedef std::vector StreamVec; - - std::istream* _pIstr; - StreamVec _streams; -}; - - -class Foundation_API TeeIOS: public virtual std::ios - /// The base class for TeeInputStream and TeeOutputStream. - /// - /// This class is needed to ensure the correct initialization - /// order of the stream buffer and base classes. -{ -public: - TeeIOS(); - /// Creates the basic stream and leaves it unconnected. - - TeeIOS(std::istream& istr); - /// Creates the basic stream and connects it - /// to the given input stream. - - TeeIOS(std::ostream& ostr); - /// Creates the basic stream and connects it - /// to the given output stream. - - ~TeeIOS(); - /// Destroys the stream. - - void addStream(std::ostream& ostr); - /// Adds the given output stream. - - TeeStreamBuf* rdbuf(); - /// Returns a pointer to the underlying streambuf. - -protected: - TeeStreamBuf _buf; -}; - - -class Foundation_API TeeInputStream: public TeeIOS, public std::istream - /// This stream copies all characters read through it - /// to one or multiple output streams. -{ -public: - TeeInputStream(std::istream& istr); - /// Creates the TeeInputStream and connects it - /// to the given input stream. - - ~TeeInputStream(); - /// Destroys the TeeInputStream. -}; - - -class Foundation_API TeeOutputStream: public TeeIOS, public std::ostream - /// This stream copies all characters written to it - /// to one or multiple output streams. -{ -public: - TeeOutputStream(); - /// Creates an unconnected TeeOutputStream. - - TeeOutputStream(std::ostream& ostr); - /// Creates the TeeOutputStream and connects it - /// to the given input stream. - - ~TeeOutputStream(); - /// Destroys the TeeOutputStream. -}; - - -} // namespace Poco - - -#endif // Foundation_TeeStream_INCLUDED +// +// TeeStream.h +// +// $Id: //poco/1.2/Foundation/include/Poco/TeeStream.h#1 $ +// +// Library: Foundation +// Package: Streams +// Module: TeeStream +// +// Definition of the TeeStream class. +// +// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_TeeStream_INCLUDED +#define Foundation_TeeStream_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/UnbufferedStreamBuf.h" +#include +#include +#include + + +namespace Poco { + + +class Foundation_API TeeStreamBuf: public UnbufferedStreamBuf + /// This stream buffer copies all data written to or + /// read from it to one or multiple output streams. +{ +public: + TeeStreamBuf(); + /// Creates an unconnected CountingStreamBuf. + /// Use addStream() to attach output streams. + + TeeStreamBuf(std::istream& istr); + /// Creates the CountingStreamBuf and connects it + /// to the given input stream. + + TeeStreamBuf(std::ostream& ostr); + /// Creates the CountingStreamBuf and connects it + /// to the given output stream. + + ~TeeStreamBuf(); + /// Destroys the CountingStream. + + void addStream(std::ostream& ostr); + /// Adds the given output stream. + +protected: + int readFromDevice(); + int writeToDevice(char c); + +private: + typedef std::vector StreamVec; + + std::istream* _pIstr; + StreamVec _streams; +}; + + +class Foundation_API TeeIOS: public virtual std::ios + /// The base class for TeeInputStream and TeeOutputStream. + /// + /// This class is needed to ensure the correct initialization + /// order of the stream buffer and base classes. +{ +public: + TeeIOS(); + /// Creates the basic stream and leaves it unconnected. + + TeeIOS(std::istream& istr); + /// Creates the basic stream and connects it + /// to the given input stream. + + TeeIOS(std::ostream& ostr); + /// Creates the basic stream and connects it + /// to the given output stream. + + ~TeeIOS(); + /// Destroys the stream. + + void addStream(std::ostream& ostr); + /// Adds the given output stream. + + TeeStreamBuf* rdbuf(); + /// Returns a pointer to the underlying streambuf. + +protected: + TeeStreamBuf _buf; +}; + + +class Foundation_API TeeInputStream: public TeeIOS, public std::istream + /// This stream copies all characters read through it + /// to one or multiple output streams. +{ +public: + TeeInputStream(std::istream& istr); + /// Creates the TeeInputStream and connects it + /// to the given input stream. + + ~TeeInputStream(); + /// Destroys the TeeInputStream. +}; + + +class Foundation_API TeeOutputStream: public TeeIOS, public std::ostream + /// This stream copies all characters written to it + /// to one or multiple output streams. +{ +public: + TeeOutputStream(); + /// Creates an unconnected TeeOutputStream. + + TeeOutputStream(std::ostream& ostr); + /// Creates the TeeOutputStream and connects it + /// to the given input stream. + + ~TeeOutputStream(); + /// Destroys the TeeOutputStream. +}; + + +} // namespace Poco + + +#endif // Foundation_TeeStream_INCLUDED diff --git a/Foundation/include/Poco/TemporaryFile.h b/Foundation/include/Poco/TemporaryFile.h index 7feb73357..8fc213371 100644 --- a/Foundation/include/Poco/TemporaryFile.h +++ b/Foundation/include/Poco/TemporaryFile.h @@ -1,102 +1,102 @@ -// -// TemporaryFile.h -// -// $Id: //poco/1.2/Foundation/include/Poco/TemporaryFile.h#1 $ -// -// Library: Foundation -// Package: Filesystem -// Module: TemporaryFile -// -// Definition of the TemporaryFile class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_TemporaryFile_INCLUDED -#define Foundation_TemporaryFile_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/File.h" - - -namespace Poco { - - -class Foundation_API TemporaryFile: public File - /// The TemporaryFile class helps with the handling - /// of temporary files. - /// A unique name for the temporary file is - /// automatically chosen and the file is placed - /// in the directory reserved for temporary - /// files (see Path::temp()). - /// Obtain the path by calling the path() method - /// (inherited from File). - /// - /// The TemporaryFile class does not actually - /// create the file - this is up to the application. - /// The class does, however, delete the temporary - /// file - either in the destructor, or immediately - /// before the application terminates. -{ -public: - TemporaryFile(); - /// Creates the TemporaryFile. - - ~TemporaryFile(); - /// Destroys the TemporaryFile and - /// deletes the corresponding file on - /// disk unless keep() or keepUntilExit() - /// has been called. - - void keep(); - /// Disables automatic deletion of the file in - /// the destructor. - - void keepUntilExit(); - /// Disables automatic deletion of the file in - /// the destructor, but registers the file - /// for deletion at process termination. - - static void registerForDeletion(const std::string& path); - /// Registers the given file for deletion - /// at process termination. - - static std::string tempName(); - /// Returns a unique path name for a temporary - /// file in the system's scratch directory - /// (see Path::temp()). - -private: - bool _keep; -}; - - -} // namespace Poco - - -#endif // Foundation_TemporaryFile_INCLUDED +// +// TemporaryFile.h +// +// $Id: //poco/1.2/Foundation/include/Poco/TemporaryFile.h#1 $ +// +// Library: Foundation +// Package: Filesystem +// Module: TemporaryFile +// +// Definition of the TemporaryFile class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_TemporaryFile_INCLUDED +#define Foundation_TemporaryFile_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/File.h" + + +namespace Poco { + + +class Foundation_API TemporaryFile: public File + /// The TemporaryFile class helps with the handling + /// of temporary files. + /// A unique name for the temporary file is + /// automatically chosen and the file is placed + /// in the directory reserved for temporary + /// files (see Path::temp()). + /// Obtain the path by calling the path() method + /// (inherited from File). + /// + /// The TemporaryFile class does not actually + /// create the file - this is up to the application. + /// The class does, however, delete the temporary + /// file - either in the destructor, or immediately + /// before the application terminates. +{ +public: + TemporaryFile(); + /// Creates the TemporaryFile. + + ~TemporaryFile(); + /// Destroys the TemporaryFile and + /// deletes the corresponding file on + /// disk unless keep() or keepUntilExit() + /// has been called. + + void keep(); + /// Disables automatic deletion of the file in + /// the destructor. + + void keepUntilExit(); + /// Disables automatic deletion of the file in + /// the destructor, but registers the file + /// for deletion at process termination. + + static void registerForDeletion(const std::string& path); + /// Registers the given file for deletion + /// at process termination. + + static std::string tempName(); + /// Returns a unique path name for a temporary + /// file in the system's scratch directory + /// (see Path::temp()). + +private: + bool _keep; +}; + + +} // namespace Poco + + +#endif // Foundation_TemporaryFile_INCLUDED diff --git a/Foundation/include/Poco/TextConverter.h b/Foundation/include/Poco/TextConverter.h index 20dfc3345..49b5b823c 100644 --- a/Foundation/include/Poco/TextConverter.h +++ b/Foundation/include/Poco/TextConverter.h @@ -1,94 +1,94 @@ -// -// TextConverter.h -// -// $Id: //poco/1.2/Foundation/include/Poco/TextConverter.h#1 $ -// -// Library: Foundation -// Package: Text -// Module: TextConverter -// -// Definition of the TextConverter class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_TextConverter_INCLUDED -#define Foundation_TextConverter_INCLUDED - - -#include "Poco/Foundation.h" - - -namespace Poco { - - -class TextEncoding; - - -class Foundation_API TextConverter - /// A TextConverter converts strings from one encoding - /// into another. -{ -public: - TextConverter(const TextEncoding& inEncoding, const TextEncoding& outEncoding, int defaultChar = '?'); - /// Creates the TextConverter. The encoding objects must not be deleted while the - /// TextConverter is in use. - - ~TextConverter(); - /// Destroys the TextConverter. - - int convert(const std::string& source, std::string& destination); - /// Converts the source string from inEncoding to outEncoding - /// and appends the result to destination. - /// If a character cannot be represented in outEncoding, defaultChar - /// is used instead. - /// Returns the number of encoding errors (invalid byte sequences - /// in source). - - int convert(const void* source, int length, std::string& destination); - /// Converts the source buffer from inEncoding to outEncoding - /// and appends the result to destination. - /// If a character cannot be represented in outEncoding, defaultChar - /// is used instead. - /// Returns the number of encoding errors (invalid byte sequences - /// in source). - -private: - TextConverter(); - TextConverter(const TextConverter&); - TextConverter& operator = (const TextConverter&); - - const TextEncoding& _inEncoding; - const TextEncoding& _outEncoding; - int _defaultChar; -}; - - -} // namespace Poco - - -#endif // Foundation_TextConverter_INCLUDED +// +// TextConverter.h +// +// $Id: //poco/1.2/Foundation/include/Poco/TextConverter.h#1 $ +// +// Library: Foundation +// Package: Text +// Module: TextConverter +// +// Definition of the TextConverter class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_TextConverter_INCLUDED +#define Foundation_TextConverter_INCLUDED + + +#include "Poco/Foundation.h" + + +namespace Poco { + + +class TextEncoding; + + +class Foundation_API TextConverter + /// A TextConverter converts strings from one encoding + /// into another. +{ +public: + TextConverter(const TextEncoding& inEncoding, const TextEncoding& outEncoding, int defaultChar = '?'); + /// Creates the TextConverter. The encoding objects must not be deleted while the + /// TextConverter is in use. + + ~TextConverter(); + /// Destroys the TextConverter. + + int convert(const std::string& source, std::string& destination); + /// Converts the source string from inEncoding to outEncoding + /// and appends the result to destination. + /// If a character cannot be represented in outEncoding, defaultChar + /// is used instead. + /// Returns the number of encoding errors (invalid byte sequences + /// in source). + + int convert(const void* source, int length, std::string& destination); + /// Converts the source buffer from inEncoding to outEncoding + /// and appends the result to destination. + /// If a character cannot be represented in outEncoding, defaultChar + /// is used instead. + /// Returns the number of encoding errors (invalid byte sequences + /// in source). + +private: + TextConverter(); + TextConverter(const TextConverter&); + TextConverter& operator = (const TextConverter&); + + const TextEncoding& _inEncoding; + const TextEncoding& _outEncoding; + int _defaultChar; +}; + + +} // namespace Poco + + +#endif // Foundation_TextConverter_INCLUDED diff --git a/Foundation/include/Poco/TextEncoding.h b/Foundation/include/Poco/TextEncoding.h index ef26be456..8a4e86dbb 100644 --- a/Foundation/include/Poco/TextEncoding.h +++ b/Foundation/include/Poco/TextEncoding.h @@ -1,106 +1,106 @@ -// -// TextEncoding.h -// -// $Id: //poco/1.2/Foundation/include/Poco/TextEncoding.h#1 $ -// -// Library: Foundation -// Package: Text -// Module: TextEncoding -// -// Definition of the abstract TextEncoding class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_TextEncoding_INCLUDED -#define Foundation_TextEncoding_INCLUDED - - -#include "Poco/Foundation.h" - - -namespace Poco { - - -class Foundation_API TextEncoding - /// An abstract base class for implementing text encodings - /// like UTF-8 or ISO 8859-1. - /// - /// Subclasses must override the characterMap() and convert() - /// methods. -{ -public: - enum - { - MAX_SEQUENCE_LENGTH = 6 /// The maximum character byte sequence length supported. - }; - - typedef int CharacterMap[256]; - /// The map[b] member gives information about byte sequences - /// whose first byte is b. - /// If map[b] is c where c is >= 0, then b by itself encodes the Unicode scalar value c. - /// If map[b] is -1, then the byte sequence is malformed. - /// If map[b] is -n, where n >= 2, then b is the first byte of an n-byte - /// sequence that encodes a single Unicode scalar value. Byte sequences up - /// to 6 bytes in length are supported. - - virtual ~TextEncoding(); - /// Destroys the encoding. - - virtual const CharacterMap& characterMap() const = 0; - /// Returns the CharacterMap for the encoding. - /// The CharacterMap should be kept in a static member. As - /// characterMap() can be called frequently, it should be - /// implemented in such a way that it just returns a static - /// map. If the map is built at runtime, this should be - /// done in the constructor. - - virtual int convert(const unsigned char* bytes) const; - /// The convert function is used to convert multibyte sequences; - /// bytes will point to a byte sequence of n bytes where - /// getCharacterMap()[*bytes] == -n. - /// - /// The convert function must return the Unicode scalar value - /// represented by this byte sequence or -1 if the byte sequence is malformed. - /// The default implementation returns (int) bytes[0]. - - virtual int convert(int ch, unsigned char* bytes, int length) const; - /// Transform the Unicode character ch into the encoding's - /// byte sequence. The method returns the number of bytes - /// used. The method must not use more than length characters. - /// Bytes and length can also be null - in this case only the number - /// of bytes required to represent ch is returned. - /// If the character cannot be converted, 0 is returned and - /// the byte sequence remains unchanged. - /// The default implementation simply returns 0. -}; - - -} // namespace Poco - - -#endif // Foundation_TextEncoding_INCLUDED +// +// TextEncoding.h +// +// $Id: //poco/1.2/Foundation/include/Poco/TextEncoding.h#1 $ +// +// Library: Foundation +// Package: Text +// Module: TextEncoding +// +// Definition of the abstract TextEncoding class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_TextEncoding_INCLUDED +#define Foundation_TextEncoding_INCLUDED + + +#include "Poco/Foundation.h" + + +namespace Poco { + + +class Foundation_API TextEncoding + /// An abstract base class for implementing text encodings + /// like UTF-8 or ISO 8859-1. + /// + /// Subclasses must override the characterMap() and convert() + /// methods. +{ +public: + enum + { + MAX_SEQUENCE_LENGTH = 6 /// The maximum character byte sequence length supported. + }; + + typedef int CharacterMap[256]; + /// The map[b] member gives information about byte sequences + /// whose first byte is b. + /// If map[b] is c where c is >= 0, then b by itself encodes the Unicode scalar value c. + /// If map[b] is -1, then the byte sequence is malformed. + /// If map[b] is -n, where n >= 2, then b is the first byte of an n-byte + /// sequence that encodes a single Unicode scalar value. Byte sequences up + /// to 6 bytes in length are supported. + + virtual ~TextEncoding(); + /// Destroys the encoding. + + virtual const CharacterMap& characterMap() const = 0; + /// Returns the CharacterMap for the encoding. + /// The CharacterMap should be kept in a static member. As + /// characterMap() can be called frequently, it should be + /// implemented in such a way that it just returns a static + /// map. If the map is built at runtime, this should be + /// done in the constructor. + + virtual int convert(const unsigned char* bytes) const; + /// The convert function is used to convert multibyte sequences; + /// bytes will point to a byte sequence of n bytes where + /// getCharacterMap()[*bytes] == -n. + /// + /// The convert function must return the Unicode scalar value + /// represented by this byte sequence or -1 if the byte sequence is malformed. + /// The default implementation returns (int) bytes[0]. + + virtual int convert(int ch, unsigned char* bytes, int length) const; + /// Transform the Unicode character ch into the encoding's + /// byte sequence. The method returns the number of bytes + /// used. The method must not use more than length characters. + /// Bytes and length can also be null - in this case only the number + /// of bytes required to represent ch is returned. + /// If the character cannot be converted, 0 is returned and + /// the byte sequence remains unchanged. + /// The default implementation simply returns 0. +}; + + +} // namespace Poco + + +#endif // Foundation_TextEncoding_INCLUDED diff --git a/Foundation/include/Poco/TextIterator.h b/Foundation/include/Poco/TextIterator.h index 35b0df2f2..61796de08 100644 --- a/Foundation/include/Poco/TextIterator.h +++ b/Foundation/include/Poco/TextIterator.h @@ -1,151 +1,151 @@ -// -// TextIterator.h -// -// $Id: //poco/1.2/Foundation/include/Poco/TextIterator.h#1 $ -// -// Library: Foundation -// Package: Text -// Module: TextIterator -// -// Definition of the TextIterator class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_TextIterator_INCLUDED -#define Foundation_TextIterator_INCLUDED - - -#include "Poco/Foundation.h" - - -namespace Poco { - - -class TextEncoding; - - -class Foundation_API TextIterator - /// An unidirectional iterator for iterating over characters in a string. - /// The TextIterator uses a TextEncoding object to - /// work with multi-byte character encodings like UTF-8. - /// Characters are reported in Unicode. - /// - /// Example: Count the number of UTF-8 characters in a string. - /// - /// UTF8Encoding utf8Encoding; - /// std::string utf8String("...."); - /// TextIterator it(utf8String, utf8Encoding); - /// TextIterator end(utf8String); - /// int n = 0; - /// while (it != end) { ++n; ++it; } - /// - /// NOTE: When an UTF-16 encoding is used, surrogate pairs will be - /// reported as two separate characters, due to restrictions of - /// the TextEncoding class. -{ -public: - TextIterator(); - /// Creates an uninitialized TextIterator. - - TextIterator(const std::string& str, const TextEncoding& encoding); - /// Creates a TextIterator for the given string. - /// The encoding object must not be deleted as long as the iterator - /// is in use. - - TextIterator(const std::string::const_iterator& begin, const std::string::const_iterator& end, const TextEncoding& encoding); - /// Creates a TextIterator for the given range. - /// The encoding object must not be deleted as long as the iterator - /// is in use. - - TextIterator(const std::string& str); - /// Creates an end TextIterator for the given string. - - TextIterator(const std::string::const_iterator& end); - /// Creates an end TextIterator. - - ~TextIterator(); - /// Destroys the TextIterator. - - TextIterator(const TextIterator& it); - /// Copy constructor. - - TextIterator& operator = (const TextIterator& it); - /// Assignment operator. - - void swap(TextIterator& it); - /// Swaps the iterator with another one. - - int operator * () const; - /// Returns the Unicode value of the current character. - /// If there is no valid character at the current position, - /// -1 is returned. - - TextIterator& operator ++ (); - /// Prefix increment operator. - - TextIterator operator ++ (int); - /// Postfix increment operator. - - bool operator == (const TextIterator& it) const; - /// Compares two iterators for equality. - - bool operator != (const TextIterator& it) const; - /// Compares two iterators for inequality. - -private: - const TextEncoding* _pEncoding; - std::string::const_iterator _it; - std::string::const_iterator _end; -}; - - -// -// inlines -// -inline bool TextIterator::operator == (const TextIterator& it) const -{ - return _it == it._it; -} - - -inline bool TextIterator::operator != (const TextIterator& it) const -{ - return _it != it._it; -} - - -inline void swap(TextIterator& it1, TextIterator& it2) -{ - it1.swap(it2); -} - - -} // namespace Poco - - -#endif // Foundation_TextIterator_INCLUDED +// +// TextIterator.h +// +// $Id: //poco/1.2/Foundation/include/Poco/TextIterator.h#1 $ +// +// Library: Foundation +// Package: Text +// Module: TextIterator +// +// Definition of the TextIterator class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_TextIterator_INCLUDED +#define Foundation_TextIterator_INCLUDED + + +#include "Poco/Foundation.h" + + +namespace Poco { + + +class TextEncoding; + + +class Foundation_API TextIterator + /// An unidirectional iterator for iterating over characters in a string. + /// The TextIterator uses a TextEncoding object to + /// work with multi-byte character encodings like UTF-8. + /// Characters are reported in Unicode. + /// + /// Example: Count the number of UTF-8 characters in a string. + /// + /// UTF8Encoding utf8Encoding; + /// std::string utf8String("...."); + /// TextIterator it(utf8String, utf8Encoding); + /// TextIterator end(utf8String); + /// int n = 0; + /// while (it != end) { ++n; ++it; } + /// + /// NOTE: When an UTF-16 encoding is used, surrogate pairs will be + /// reported as two separate characters, due to restrictions of + /// the TextEncoding class. +{ +public: + TextIterator(); + /// Creates an uninitialized TextIterator. + + TextIterator(const std::string& str, const TextEncoding& encoding); + /// Creates a TextIterator for the given string. + /// The encoding object must not be deleted as long as the iterator + /// is in use. + + TextIterator(const std::string::const_iterator& begin, const std::string::const_iterator& end, const TextEncoding& encoding); + /// Creates a TextIterator for the given range. + /// The encoding object must not be deleted as long as the iterator + /// is in use. + + TextIterator(const std::string& str); + /// Creates an end TextIterator for the given string. + + TextIterator(const std::string::const_iterator& end); + /// Creates an end TextIterator. + + ~TextIterator(); + /// Destroys the TextIterator. + + TextIterator(const TextIterator& it); + /// Copy constructor. + + TextIterator& operator = (const TextIterator& it); + /// Assignment operator. + + void swap(TextIterator& it); + /// Swaps the iterator with another one. + + int operator * () const; + /// Returns the Unicode value of the current character. + /// If there is no valid character at the current position, + /// -1 is returned. + + TextIterator& operator ++ (); + /// Prefix increment operator. + + TextIterator operator ++ (int); + /// Postfix increment operator. + + bool operator == (const TextIterator& it) const; + /// Compares two iterators for equality. + + bool operator != (const TextIterator& it) const; + /// Compares two iterators for inequality. + +private: + const TextEncoding* _pEncoding; + std::string::const_iterator _it; + std::string::const_iterator _end; +}; + + +// +// inlines +// +inline bool TextIterator::operator == (const TextIterator& it) const +{ + return _it == it._it; +} + + +inline bool TextIterator::operator != (const TextIterator& it) const +{ + return _it != it._it; +} + + +inline void swap(TextIterator& it1, TextIterator& it2) +{ + it1.swap(it2); +} + + +} // namespace Poco + + +#endif // Foundation_TextIterator_INCLUDED diff --git a/Foundation/include/Poco/Thread.h b/Foundation/include/Poco/Thread.h index 6d37de02f..428480a61 100644 --- a/Foundation/include/Poco/Thread.h +++ b/Foundation/include/Poco/Thread.h @@ -1,196 +1,196 @@ -// -// Thread.h -// -// $Id: //poco/1.2/Foundation/include/Poco/Thread.h#1 $ -// -// Library: Foundation -// Package: Threading -// Module: Thread -// -// Definition of the Thread class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_Thread_INCLUDED -#define Foundation_Thread_INCLUDED - - -#include "Poco/Foundation.h" - - -#if defined(POCO_OS_FAMILY_WINDOWS) -#include "Poco/Thread_WIN32.h" -#else -#include "Poco/Thread_POSIX.h" -#endif - - -namespace Poco { - - -class Runnable; -class ThreadLocalStorage; - - -class Foundation_API Thread: private ThreadImpl - /// This class implements a platform-independent - /// wrapper to an operating system thread. - /// - /// Every Thread object gets a unique (within - /// its process) numeric thread ID. - /// Furthermore, a thread can be assigned a name. -{ -public: - enum Priority - /// Thread priorities. - { - PRIO_LOWEST = PRIO_LOWEST_IMPL, /// The lowest thread priority. - PRIO_LOW = PRIO_LOW_IMPL, /// A lower than normal thread priority. - PRIO_NORMAL = PRIO_NORMAL_IMPL, /// The normal thread priority. - PRIO_HIGH = PRIO_HIGH_IMPL, /// A higher than normal thread priority. - PRIO_HIGHEST = PRIO_HIGHEST_IMPL /// The highest thread priority. - }; - - Thread(); - /// Creates a thread. Call start() to start it. - - Thread(const std::string& name); - /// Creates a named thread. Call start() to start it. - - ~Thread(); - /// Destroys the thread. - - int id() const; - /// Returns the unique thread ID of the thread. - - const std::string& name() const; - /// Returns the name of the thread. - - void setPriority(Priority prio); - /// Sets the thread's priority. - /// - /// Some platform only allow changing a thread's priority - /// if the process has certain privileges. - - Priority getPriority() const; - /// Returns the thread's priority. - - void start(Runnable& target); - /// Starts the thread with the given target. - - void join(); - /// Waits until the thread completes execution. - /// If multiple threads try to join the same - /// thread, the result is undefined. - - bool isRunning() const; - /// Returns true if the thread is running. - - static void sleep(long milliseconds); - /// Suspends the current thread for the specified - /// amount of time. - - static void yield(); - /// Yields cpu to other threads. - - static Thread* current(); - /// Returns the Thread object for the currently active thread. - /// If the current thread is the main thread, 0 is returned. - -protected: - ThreadLocalStorage& tls(); - /// Returns a reference to the thread's local storage. - - void clearTLS(); - /// Clears the thread's local storage. - - std::string makeName(); - /// Creates a unique name for a thread. - - static int uniqueId(); - /// Creates and returns a unique id for a thread. - - void setName(const std::string& name); - /// Sets the name of the thread. - -private: - Thread(const Thread&); - Thread& operator = (const Thread&); - - int _id; - std::string _name; - ThreadLocalStorage* _pTLS; - - friend class ThreadLocalStorage; - friend class PooledThread; -}; - - -// -// inlines -// -inline int Thread::id() const -{ - return _id; -} - - -inline const std::string& Thread::name() const -{ - return _name; -} - - -inline bool Thread::isRunning() const -{ - return isRunningImpl(); -} - - -inline void Thread::sleep(long milliseconds) -{ - sleepImpl(milliseconds); -} - - -inline void Thread::yield() -{ - yieldImpl(); -} - - -inline Thread* Thread::current() -{ - return static_cast(currentImpl()); -} - - -} // namespace Poco - - -#endif // Foundation_Thread_INCLUDED +// +// Thread.h +// +// $Id: //poco/1.2/Foundation/include/Poco/Thread.h#1 $ +// +// Library: Foundation +// Package: Threading +// Module: Thread +// +// Definition of the Thread class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_Thread_INCLUDED +#define Foundation_Thread_INCLUDED + + +#include "Poco/Foundation.h" + + +#if defined(POCO_OS_FAMILY_WINDOWS) +#include "Poco/Thread_WIN32.h" +#else +#include "Poco/Thread_POSIX.h" +#endif + + +namespace Poco { + + +class Runnable; +class ThreadLocalStorage; + + +class Foundation_API Thread: private ThreadImpl + /// This class implements a platform-independent + /// wrapper to an operating system thread. + /// + /// Every Thread object gets a unique (within + /// its process) numeric thread ID. + /// Furthermore, a thread can be assigned a name. +{ +public: + enum Priority + /// Thread priorities. + { + PRIO_LOWEST = PRIO_LOWEST_IMPL, /// The lowest thread priority. + PRIO_LOW = PRIO_LOW_IMPL, /// A lower than normal thread priority. + PRIO_NORMAL = PRIO_NORMAL_IMPL, /// The normal thread priority. + PRIO_HIGH = PRIO_HIGH_IMPL, /// A higher than normal thread priority. + PRIO_HIGHEST = PRIO_HIGHEST_IMPL /// The highest thread priority. + }; + + Thread(); + /// Creates a thread. Call start() to start it. + + Thread(const std::string& name); + /// Creates a named thread. Call start() to start it. + + ~Thread(); + /// Destroys the thread. + + int id() const; + /// Returns the unique thread ID of the thread. + + const std::string& name() const; + /// Returns the name of the thread. + + void setPriority(Priority prio); + /// Sets the thread's priority. + /// + /// Some platform only allow changing a thread's priority + /// if the process has certain privileges. + + Priority getPriority() const; + /// Returns the thread's priority. + + void start(Runnable& target); + /// Starts the thread with the given target. + + void join(); + /// Waits until the thread completes execution. + /// If multiple threads try to join the same + /// thread, the result is undefined. + + bool isRunning() const; + /// Returns true if the thread is running. + + static void sleep(long milliseconds); + /// Suspends the current thread for the specified + /// amount of time. + + static void yield(); + /// Yields cpu to other threads. + + static Thread* current(); + /// Returns the Thread object for the currently active thread. + /// If the current thread is the main thread, 0 is returned. + +protected: + ThreadLocalStorage& tls(); + /// Returns a reference to the thread's local storage. + + void clearTLS(); + /// Clears the thread's local storage. + + std::string makeName(); + /// Creates a unique name for a thread. + + static int uniqueId(); + /// Creates and returns a unique id for a thread. + + void setName(const std::string& name); + /// Sets the name of the thread. + +private: + Thread(const Thread&); + Thread& operator = (const Thread&); + + int _id; + std::string _name; + ThreadLocalStorage* _pTLS; + + friend class ThreadLocalStorage; + friend class PooledThread; +}; + + +// +// inlines +// +inline int Thread::id() const +{ + return _id; +} + + +inline const std::string& Thread::name() const +{ + return _name; +} + + +inline bool Thread::isRunning() const +{ + return isRunningImpl(); +} + + +inline void Thread::sleep(long milliseconds) +{ + sleepImpl(milliseconds); +} + + +inline void Thread::yield() +{ + yieldImpl(); +} + + +inline Thread* Thread::current() +{ + return static_cast(currentImpl()); +} + + +} // namespace Poco + + +#endif // Foundation_Thread_INCLUDED diff --git a/Foundation/include/Poco/ThreadLocal.h b/Foundation/include/Poco/ThreadLocal.h index 30a98c5be..a0ee7c6ff 100644 --- a/Foundation/include/Poco/ThreadLocal.h +++ b/Foundation/include/Poco/ThreadLocal.h @@ -1,179 +1,179 @@ -// -// ThreadLocal.h -// -// $Id: //poco/1.2/Foundation/include/Poco/ThreadLocal.h#2 $ -// -// Library: Foundation -// Package: Threading -// Module: Thread -// -// Definition of the ThreadLocal template and related classes. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_ThreadLocal_INCLUDED -#define Foundation_ThreadLocal_INCLUDED - - -#include "Poco/Foundation.h" -#include - - -namespace Poco { - - -class Foundation_API TLSAbstractSlot - /// This is the base class for all objects - /// that the ThreadLocalStorage class manages. -{ -public: - TLSAbstractSlot(); - virtual ~TLSAbstractSlot(); -}; - - -template -class TLSSlot: public TLSAbstractSlot - /// The Slot template wraps another class - /// so that it can be stored in a ThreadLocalStorage - /// object. This class is used internally, and you - /// must not create instances of it yourself. -{ -public: - TLSSlot(): - _value() - { - } - - ~TLSSlot() - { - } - - C& value() - { - return _value; - } - -private: - TLSSlot(const TLSSlot&); - TLSSlot& operator = (const TLSSlot&); - - C _value; -}; - - -class Foundation_API ThreadLocalStorage - /// This class manages the local storage for each thread. - /// Never use this class directly, always use the - /// ThreadLocal template for managing thread local storage. -{ -public: - ThreadLocalStorage(); - /// Creates the TLS. - - ~ThreadLocalStorage(); - /// Deletes the TLS. - - TLSAbstractSlot*& get(const void* key); - /// Returns the slot for the given key. - - static ThreadLocalStorage& current(); - /// Returns the TLS object for the current thread - /// (which may also be the main thread). - - static void clear(); - /// Clears the current thread's TLS object. - /// Does nothing in the main thread. - -private: - typedef std::map TLSMap; - - TLSMap _map; - - friend class Thread; -}; - - -template -class ThreadLocal - /// This template is used to declare type safe thread - /// local variables. It can basically be used like - /// a smart pointer class with the special feature - /// that it references a different object - /// in every thread. The underlying object will - /// be created when it is referenced for the first - /// time. - /// See the NestedDiagnosticContext class for an - /// example how to use this template. - /// Every thread only has access to its own - /// thread local data. There is no way for a thread - /// to access another thread's local data. -{ - typedef TLSSlot Slot; - -public: - ThreadLocal() - { - } - - ~ThreadLocal() - { - } - - C* operator -> () - { - return &get(); - } - - C& operator * () - /// "Dereferences" the smart pointer and returns a reference - /// to the underlying data object. The reference can be used - /// to modify the object. - { - return get(); - } - - C& get() - /// Returns a reference to the underlying data object. - /// The reference can be used to modify the object. - { - TLSAbstractSlot*& p = ThreadLocalStorage::current().get(this); - if (!p) p = new Slot; - return static_cast(p)->value(); - } - -private: - ThreadLocal(const ThreadLocal&); - ThreadLocal& operator = (const ThreadLocal&); -}; - - -} // namespace Poco - - -#endif // Foundation_ThreadLocal_INCLUDED +// +// ThreadLocal.h +// +// $Id: //poco/1.2/Foundation/include/Poco/ThreadLocal.h#2 $ +// +// Library: Foundation +// Package: Threading +// Module: Thread +// +// Definition of the ThreadLocal template and related classes. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_ThreadLocal_INCLUDED +#define Foundation_ThreadLocal_INCLUDED + + +#include "Poco/Foundation.h" +#include + + +namespace Poco { + + +class Foundation_API TLSAbstractSlot + /// This is the base class for all objects + /// that the ThreadLocalStorage class manages. +{ +public: + TLSAbstractSlot(); + virtual ~TLSAbstractSlot(); +}; + + +template +class TLSSlot: public TLSAbstractSlot + /// The Slot template wraps another class + /// so that it can be stored in a ThreadLocalStorage + /// object. This class is used internally, and you + /// must not create instances of it yourself. +{ +public: + TLSSlot(): + _value() + { + } + + ~TLSSlot() + { + } + + C& value() + { + return _value; + } + +private: + TLSSlot(const TLSSlot&); + TLSSlot& operator = (const TLSSlot&); + + C _value; +}; + + +class Foundation_API ThreadLocalStorage + /// This class manages the local storage for each thread. + /// Never use this class directly, always use the + /// ThreadLocal template for managing thread local storage. +{ +public: + ThreadLocalStorage(); + /// Creates the TLS. + + ~ThreadLocalStorage(); + /// Deletes the TLS. + + TLSAbstractSlot*& get(const void* key); + /// Returns the slot for the given key. + + static ThreadLocalStorage& current(); + /// Returns the TLS object for the current thread + /// (which may also be the main thread). + + static void clear(); + /// Clears the current thread's TLS object. + /// Does nothing in the main thread. + +private: + typedef std::map TLSMap; + + TLSMap _map; + + friend class Thread; +}; + + +template +class ThreadLocal + /// This template is used to declare type safe thread + /// local variables. It can basically be used like + /// a smart pointer class with the special feature + /// that it references a different object + /// in every thread. The underlying object will + /// be created when it is referenced for the first + /// time. + /// See the NestedDiagnosticContext class for an + /// example how to use this template. + /// Every thread only has access to its own + /// thread local data. There is no way for a thread + /// to access another thread's local data. +{ + typedef TLSSlot Slot; + +public: + ThreadLocal() + { + } + + ~ThreadLocal() + { + } + + C* operator -> () + { + return &get(); + } + + C& operator * () + /// "Dereferences" the smart pointer and returns a reference + /// to the underlying data object. The reference can be used + /// to modify the object. + { + return get(); + } + + C& get() + /// Returns a reference to the underlying data object. + /// The reference can be used to modify the object. + { + TLSAbstractSlot*& p = ThreadLocalStorage::current().get(this); + if (!p) p = new Slot; + return static_cast(p)->value(); + } + +private: + ThreadLocal(const ThreadLocal&); + ThreadLocal& operator = (const ThreadLocal&); +}; + + +} // namespace Poco + + +#endif // Foundation_ThreadLocal_INCLUDED diff --git a/Foundation/include/Poco/ThreadPool.h b/Foundation/include/Poco/ThreadPool.h index b24f969c3..2d30d24d9 100644 --- a/Foundation/include/Poco/ThreadPool.h +++ b/Foundation/include/Poco/ThreadPool.h @@ -1,170 +1,170 @@ -// -// ThreadPool.h -// -// $Id: //poco/1.2/Foundation/include/Poco/ThreadPool.h#2 $ -// -// Library: Foundation -// Package: Threading -// Module: ThreadPool -// -// Definition of the ThreadPool class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_ThreadPool_INCLUDED -#define Foundation_ThreadPool_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/Thread.h" -#include "Poco/Mutex.h" -#include - - -namespace Poco { - - -class Runnable; -class PooledThread; - - -class Foundation_API ThreadPool - /// A thread pool always keeps a number of threads running, ready - /// to accept work. - /// Creating and starting a threads can impose a significant runtime - /// overhead to an application. A thread pool helps to improve - /// the performance of an application by reducing the number - /// of threads that have to be created (and destroyed again). - /// Threads in a thread pool are re-used once they become - /// available again. - /// The thread pool always keeps a minimum number of threads - /// running. If the demans for threads increases, additional - /// threads are created. Once the demand for threads sinks - /// again, no-longer used threads are stopped and removed - /// from the pool. -{ -public: - ThreadPool(int minCapacity = 2, int maxCapacity = 16, int idleTime = 60); - ThreadPool(const std::string& name, int minCapacity = 2, int maxCapacity = 16, int idleTime = 60); - /// Creates a thread pool with minCapacity threads. - /// If required, up to maxCapacity threads are created - /// a NoThreadAvailableException exception is thrown. - /// If a thread is running idle for more than idleTime seconds, - /// and more than minCapacity threads are running, the thread - /// is killed. - - ~ThreadPool(); - /// Currently running threads will remain active - /// until they complete. - - void addCapacity(int n); - /// Increases (or decreases, if n is negative) - /// the maximum number of threads. - - int capacity() const; - /// Returns the maximum capacity of threads. - - int used() const; - /// Returns the number of currently used threads. - - int allocated() const; - /// Returns the number of currently allocated threads. - - int available() const; - /// Returns the number available threads. - - void start(Runnable& target); - /// Obtains a thread and starts the target. - /// Throws a NoThreadAvailableException if no more - /// threads are available. - - void start(Runnable& target, const std::string& name); - /// Obtains a thread and starts the target. - /// Assigns the given name to the thread. - /// Throws a NoThreadAvailableException if no more - /// threads are available. - - void startWithPriority(Thread::Priority priority, Runnable& target); - /// Obtains a thread, adjusts the thread's priority, and starts the target. - /// Throws a NoThreadAvailableException if no more - /// threads are available. - - void startWithPriority(Thread::Priority priority, Runnable& target, const std::string& name); - /// Obtains a thread, adjusts the thread's priority, and starts the target. - /// Assigns the given name to the thread. - /// Throws a NoThreadAvailableException if no more - /// threads are available. - - void stopAll(); - /// Stops all running threads. - /// Will also delete all thread objects. - /// If used, this method should be the last action before - /// the thread pool is deleted. - - void joinAll(); - /// Waits for all threads to complete. - - void collect(); - /// Stops and removes no longer used threads from the - /// thread pool. Can be called at various times in an - /// application's life time to help the thread pool - /// manage its threads. Calling this method is optional, - /// as the thread pool is also implicitly managed in - /// calls to start(), addCapacity() and joinAll(). - - static ThreadPool& defaultPool(); - /// Returns a reference to the default - /// thread pool. - -protected: - PooledThread* getThread(); - PooledThread* createThread(); - - void housekeep(); - -private: - ThreadPool(const ThreadPool& pool); - ThreadPool& operator = (const ThreadPool& pool); - - typedef std::vector ThreadVec; - - std::string _name; - int _minCapacity; - int _maxCapacity; - int _idleTime; - int _serial; - int _age; - ThreadVec _threads; - mutable FastMutex _mutex; -}; - - -} // namespace Poco - - -#endif // Foundation_ThreadPool_INCLUDED +// +// ThreadPool.h +// +// $Id: //poco/1.2/Foundation/include/Poco/ThreadPool.h#2 $ +// +// Library: Foundation +// Package: Threading +// Module: ThreadPool +// +// Definition of the ThreadPool class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_ThreadPool_INCLUDED +#define Foundation_ThreadPool_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Thread.h" +#include "Poco/Mutex.h" +#include + + +namespace Poco { + + +class Runnable; +class PooledThread; + + +class Foundation_API ThreadPool + /// A thread pool always keeps a number of threads running, ready + /// to accept work. + /// Creating and starting a threads can impose a significant runtime + /// overhead to an application. A thread pool helps to improve + /// the performance of an application by reducing the number + /// of threads that have to be created (and destroyed again). + /// Threads in a thread pool are re-used once they become + /// available again. + /// The thread pool always keeps a minimum number of threads + /// running. If the demans for threads increases, additional + /// threads are created. Once the demand for threads sinks + /// again, no-longer used threads are stopped and removed + /// from the pool. +{ +public: + ThreadPool(int minCapacity = 2, int maxCapacity = 16, int idleTime = 60); + ThreadPool(const std::string& name, int minCapacity = 2, int maxCapacity = 16, int idleTime = 60); + /// Creates a thread pool with minCapacity threads. + /// If required, up to maxCapacity threads are created + /// a NoThreadAvailableException exception is thrown. + /// If a thread is running idle for more than idleTime seconds, + /// and more than minCapacity threads are running, the thread + /// is killed. + + ~ThreadPool(); + /// Currently running threads will remain active + /// until they complete. + + void addCapacity(int n); + /// Increases (or decreases, if n is negative) + /// the maximum number of threads. + + int capacity() const; + /// Returns the maximum capacity of threads. + + int used() const; + /// Returns the number of currently used threads. + + int allocated() const; + /// Returns the number of currently allocated threads. + + int available() const; + /// Returns the number available threads. + + void start(Runnable& target); + /// Obtains a thread and starts the target. + /// Throws a NoThreadAvailableException if no more + /// threads are available. + + void start(Runnable& target, const std::string& name); + /// Obtains a thread and starts the target. + /// Assigns the given name to the thread. + /// Throws a NoThreadAvailableException if no more + /// threads are available. + + void startWithPriority(Thread::Priority priority, Runnable& target); + /// Obtains a thread, adjusts the thread's priority, and starts the target. + /// Throws a NoThreadAvailableException if no more + /// threads are available. + + void startWithPriority(Thread::Priority priority, Runnable& target, const std::string& name); + /// Obtains a thread, adjusts the thread's priority, and starts the target. + /// Assigns the given name to the thread. + /// Throws a NoThreadAvailableException if no more + /// threads are available. + + void stopAll(); + /// Stops all running threads. + /// Will also delete all thread objects. + /// If used, this method should be the last action before + /// the thread pool is deleted. + + void joinAll(); + /// Waits for all threads to complete. + + void collect(); + /// Stops and removes no longer used threads from the + /// thread pool. Can be called at various times in an + /// application's life time to help the thread pool + /// manage its threads. Calling this method is optional, + /// as the thread pool is also implicitly managed in + /// calls to start(), addCapacity() and joinAll(). + + static ThreadPool& defaultPool(); + /// Returns a reference to the default + /// thread pool. + +protected: + PooledThread* getThread(); + PooledThread* createThread(); + + void housekeep(); + +private: + ThreadPool(const ThreadPool& pool); + ThreadPool& operator = (const ThreadPool& pool); + + typedef std::vector ThreadVec; + + std::string _name; + int _minCapacity; + int _maxCapacity; + int _idleTime; + int _serial; + int _age; + ThreadVec _threads; + mutable FastMutex _mutex; +}; + + +} // namespace Poco + + +#endif // Foundation_ThreadPool_INCLUDED diff --git a/Foundation/include/Poco/Thread_POSIX.h b/Foundation/include/Poco/Thread_POSIX.h index 43b31e202..01f07fa28 100644 --- a/Foundation/include/Poco/Thread_POSIX.h +++ b/Foundation/include/Poco/Thread_POSIX.h @@ -1,136 +1,136 @@ -// -// Thread_POSIX.h -// -// $Id: //poco/1.2/Foundation/include/Poco/Thread_POSIX.h#1 $ -// -// Library: Foundation -// Package: Threading -// Module: Thread -// -// Definition of the ThreadImpl class for POSIX Threads. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_Thread_POSIX_INCLUDED -#define Foundation_Thread_POSIX_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/Runnable.h" -#include "Poco/SignalHandler.h" -#include -#if !defined(POCO_NO_SYS_SELECT_H) -#include -#endif -#include - - -namespace Poco { - - -class Foundation_API ThreadImpl -{ -public: - enum Priority - { - PRIO_LOWEST_IMPL, - PRIO_LOW_IMPL, - PRIO_NORMAL_IMPL, - PRIO_HIGH_IMPL, - PRIO_HIGHEST_IMPL - }; - - ThreadImpl(); - ~ThreadImpl(); - - Runnable& targetImpl() const; - void setPriorityImpl(int prio); - int getPriorityImpl() const; - void startImpl(Runnable& target); - - void joinImpl(); - bool isRunningImpl() const; - static void sleepImpl(long milliseconds); - static void yieldImpl(); - static ThreadImpl* currentImpl(); - -protected: - static void* entry(void* pThread); - static int mapPrio(int prio); - -private: - Runnable* _pTarget; - pthread_t _thread; - int _prio; - - static pthread_key_t _currentKey; - static bool _haveCurrentKey; - -#if defined(POCO_OS_FAMILY_UNIX) - SignalHandler::JumpBufferVec _jumpBufferVec; - friend class SignalHandler; -#endif -}; - - -// -// inlines -// -inline int ThreadImpl::getPriorityImpl() const -{ - return _prio; -} - - -inline void ThreadImpl::sleepImpl(long milliseconds) -{ -#if defined(__VMS) || defined(__digital__) - // This is specific to DECThreads - struct timespec interval; - interval.tv_sec = milliseconds / 1000; - interval.tv_nsec = (milliseconds % 1000)*1000000; - pthread_delay_np(&interval); -#else - struct timeval tv; - tv.tv_sec = milliseconds / 1000; - tv.tv_usec = (milliseconds % 1000) * 1000; - select(0, NULL, NULL, NULL, &tv); -#endif -} - - -inline void ThreadImpl::yieldImpl() -{ - sched_yield(); -} - - -} // namespace Poco - - -#endif // Foundation_Thread_POSIX_INCLUDED +// +// Thread_POSIX.h +// +// $Id: //poco/1.2/Foundation/include/Poco/Thread_POSIX.h#1 $ +// +// Library: Foundation +// Package: Threading +// Module: Thread +// +// Definition of the ThreadImpl class for POSIX Threads. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_Thread_POSIX_INCLUDED +#define Foundation_Thread_POSIX_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Runnable.h" +#include "Poco/SignalHandler.h" +#include +#if !defined(POCO_NO_SYS_SELECT_H) +#include +#endif +#include + + +namespace Poco { + + +class Foundation_API ThreadImpl +{ +public: + enum Priority + { + PRIO_LOWEST_IMPL, + PRIO_LOW_IMPL, + PRIO_NORMAL_IMPL, + PRIO_HIGH_IMPL, + PRIO_HIGHEST_IMPL + }; + + ThreadImpl(); + ~ThreadImpl(); + + Runnable& targetImpl() const; + void setPriorityImpl(int prio); + int getPriorityImpl() const; + void startImpl(Runnable& target); + + void joinImpl(); + bool isRunningImpl() const; + static void sleepImpl(long milliseconds); + static void yieldImpl(); + static ThreadImpl* currentImpl(); + +protected: + static void* entry(void* pThread); + static int mapPrio(int prio); + +private: + Runnable* _pTarget; + pthread_t _thread; + int _prio; + + static pthread_key_t _currentKey; + static bool _haveCurrentKey; + +#if defined(POCO_OS_FAMILY_UNIX) + SignalHandler::JumpBufferVec _jumpBufferVec; + friend class SignalHandler; +#endif +}; + + +// +// inlines +// +inline int ThreadImpl::getPriorityImpl() const +{ + return _prio; +} + + +inline void ThreadImpl::sleepImpl(long milliseconds) +{ +#if defined(__VMS) || defined(__digital__) + // This is specific to DECThreads + struct timespec interval; + interval.tv_sec = milliseconds / 1000; + interval.tv_nsec = (milliseconds % 1000)*1000000; + pthread_delay_np(&interval); +#else + struct timeval tv; + tv.tv_sec = milliseconds / 1000; + tv.tv_usec = (milliseconds % 1000) * 1000; + select(0, NULL, NULL, NULL, &tv); +#endif +} + + +inline void ThreadImpl::yieldImpl() +{ + sched_yield(); +} + + +} // namespace Poco + + +#endif // Foundation_Thread_POSIX_INCLUDED diff --git a/Foundation/include/Poco/Thread_WIN32.h b/Foundation/include/Poco/Thread_WIN32.h index a2da30522..e2ab38ffe 100644 --- a/Foundation/include/Poco/Thread_WIN32.h +++ b/Foundation/include/Poco/Thread_WIN32.h @@ -1,116 +1,116 @@ -// -// Thread_WIN32.h -// -// $Id: //poco/1.2/Foundation/include/Poco/Thread_WIN32.h#1 $ -// -// Library: Foundation -// Package: Threading -// Module: Thread -// -// Definition of the ThreadImpl class for WIN32. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_Thread_WIN32_INCLUDED -#define Foundation_Thread_WIN32_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/Runnable.h" -#include - - -namespace Poco { - - -class Foundation_API ThreadImpl -{ -public: - enum Priority - { - PRIO_LOWEST_IMPL = THREAD_PRIORITY_LOWEST, - PRIO_LOW_IMPL = THREAD_PRIORITY_BELOW_NORMAL, - PRIO_NORMAL_IMPL = THREAD_PRIORITY_NORMAL, - PRIO_HIGH_IMPL = THREAD_PRIORITY_ABOVE_NORMAL, - PRIO_HIGHEST_IMPL = THREAD_PRIORITY_HIGHEST - }; - - ThreadImpl(); - ~ThreadImpl(); - - void setPriorityImpl(int prio); - int getPriorityImpl() const; - void startImpl(Runnable& target); - - void joinImpl(); - bool isRunningImpl() const; - static void sleepImpl(long milliseconds); - static void yieldImpl(); - static ThreadImpl* currentImpl(); - -protected: -#if defined(_DLL) - static DWORD WINAPI entry(LPVOID pThread); -#else - static unsigned __stdcall entry(void* pThread); -#endif - -private: - Runnable* _pTarget; - HANDLE _thread; - int _prio; - - static DWORD _currentKey; -}; - - -// -// inlines -// -inline int ThreadImpl::getPriorityImpl() const -{ - return _prio; -} - - -inline void ThreadImpl::sleepImpl(long milliseconds) -{ - Sleep(milliseconds); -} - - -inline void ThreadImpl::yieldImpl() -{ - Sleep(0); -} - - -} // namespace Poco - - -#endif // Foundation_Thread_WIN32_INCLUDED +// +// Thread_WIN32.h +// +// $Id: //poco/1.2/Foundation/include/Poco/Thread_WIN32.h#1 $ +// +// Library: Foundation +// Package: Threading +// Module: Thread +// +// Definition of the ThreadImpl class for WIN32. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_Thread_WIN32_INCLUDED +#define Foundation_Thread_WIN32_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Runnable.h" +#include + + +namespace Poco { + + +class Foundation_API ThreadImpl +{ +public: + enum Priority + { + PRIO_LOWEST_IMPL = THREAD_PRIORITY_LOWEST, + PRIO_LOW_IMPL = THREAD_PRIORITY_BELOW_NORMAL, + PRIO_NORMAL_IMPL = THREAD_PRIORITY_NORMAL, + PRIO_HIGH_IMPL = THREAD_PRIORITY_ABOVE_NORMAL, + PRIO_HIGHEST_IMPL = THREAD_PRIORITY_HIGHEST + }; + + ThreadImpl(); + ~ThreadImpl(); + + void setPriorityImpl(int prio); + int getPriorityImpl() const; + void startImpl(Runnable& target); + + void joinImpl(); + bool isRunningImpl() const; + static void sleepImpl(long milliseconds); + static void yieldImpl(); + static ThreadImpl* currentImpl(); + +protected: +#if defined(_DLL) + static DWORD WINAPI entry(LPVOID pThread); +#else + static unsigned __stdcall entry(void* pThread); +#endif + +private: + Runnable* _pTarget; + HANDLE _thread; + int _prio; + + static DWORD _currentKey; +}; + + +// +// inlines +// +inline int ThreadImpl::getPriorityImpl() const +{ + return _prio; +} + + +inline void ThreadImpl::sleepImpl(long milliseconds) +{ + Sleep(milliseconds); +} + + +inline void ThreadImpl::yieldImpl() +{ + Sleep(0); +} + + +} // namespace Poco + + +#endif // Foundation_Thread_WIN32_INCLUDED diff --git a/Foundation/include/Poco/Timer.h b/Foundation/include/Poco/Timer.h index d40f2eb2e..b0e559ddc 100644 --- a/Foundation/include/Poco/Timer.h +++ b/Foundation/include/Poco/Timer.h @@ -1,215 +1,215 @@ -// -// Timer.h -// -// $Id: //poco/1.2/Foundation/include/Poco/Timer.h#1 $ -// -// Library: Foundation -// Package: Threading -// Module: Timer -// -// Definition of the Timer and related classes. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_Timer_INCLUDED -#define Foundation_Timer_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/Runnable.h" -#include "Poco/Mutex.h" -#include "Poco/Event.h" - - -namespace Poco { - - -class AbstractTimerCallback; -class ThreadPool; - - -class Foundation_API Timer: protected Runnable - /// This class implements a thread-based timer. - /// A timer starts a thread that first waits for a given start interval. - /// Once that interval expires, the timer callback is called repeatedly - /// in the given periodic interval. If the interval is 0, the timer is only - /// called once. - /// The timer callback method can stop the timer by setting the - /// timer's periodic interval to 0. - /// - /// The timer callback runs in its own thread, so multithreading - /// issues (proper synchronization) have to be considered when writing - /// the callback method. - /// - /// The exact interval at which the callback is called depends on many - /// factors like operating system, CPU performance and system load and - /// may differ from the specified interval. - /// - /// The timer thread is taken from a thread pool, so - /// there is a limit to the number of available concurrent timers. -{ -public: - Timer(long startInterval = 0, long periodicInterval = 0); - /// Creates a new timer object. StartInterval and periodicInterval - /// are given in milliseconds. If a periodicInterval of zero is - /// specified, the callback will only be called once, after the - /// startInterval expires. - /// To start the timer, call the Start() method. - - virtual ~Timer(); - /// Stops and destroys the timer. - - void start(const AbstractTimerCallback& method); - /// Starts the timer. - /// Create the TimerCallback as follows: - /// TimerCallback callback(*this, &MyClass::onTimer); - /// timer.start(callback); - /// - /// The timer thread is taken from the global default thread pool. - - void start(const AbstractTimerCallback& method, ThreadPool& threadPool); - /// Starts the timer. - /// Create the TimerCallback as follows: - /// TimerCallback callback(*this, &MyClass::onTimer); - /// timer.start(callback); - - void stop(); - /// Stops the timer. If the callback method is currently running - /// it will be allowed to finish first. - /// WARNING: Never call this method from within the callback method, - /// as a deadlock would result. To stop the timer from within the - /// callback method, call restart(0). - - void restart(); - /// Restarts the periodic interval. If the callback method is already running, - /// nothing will happen. - - void restart(long milliseconds); - /// Sets a new periodic interval and restarts the timer. - /// An interval of 0 will stop the timer. - - long getStartInterval() const; - /// Returns the start interval. - - void setStartInterval(long milliseconds); - /// Sets the start interval. Will only be - /// effective before start() is called. - - long getPeriodicInterval() const; - /// Returns the periodic interval. - - void setPeriodicInterval(long milliseconds); - /// Sets the periodic interval. If the timer is already running - /// the new interval will be effective when the current interval - /// expires. - -protected: - void run(); - -private: - volatile long _startInterval; - volatile long _periodicInterval; - Event _wakeUp; - Event _done; - AbstractTimerCallback* _pCallback; - mutable FastMutex _mutex; -}; - - -class Foundation_API AbstractTimerCallback - /// This is the base class for all instantiations of - /// the TimerCallback template. -{ -public: - AbstractTimerCallback(); - AbstractTimerCallback(const AbstractTimerCallback& callback); - virtual ~AbstractTimerCallback(); - - AbstractTimerCallback& operator = (const AbstractTimerCallback& callback); - - virtual void invoke(Timer& timer) const = 0; - virtual AbstractTimerCallback* clone() const = 0; -}; - - -template -class TimerCallback: public AbstractTimerCallback - /// This template class implements an adapter that sits between - /// a Timer and an object's method invoked by the timer. - /// It is quite similar in concept to the RunnableAdapter, but provides - /// some Timer specific additional methods. - /// See the Timer class for information on how - /// to use this template class. -{ -public: - typedef void (C::*Callback)(Timer&); - - TimerCallback(C& object, Callback method): _pObject(&object), _method(method) - { - } - - TimerCallback(const TimerCallback& callback): _pObject(callback._pObject), _method(callback._method) - { - } - - ~TimerCallback() - { - } - - TimerCallback& operator = (const TimerCallback& callback) - { - if (&callback != this) - { - _pObject = callback._pObject; - _method = callback._method; - } - return *this; - } - - void invoke(Timer& timer) const - { - (_pObject->*_method)(timer); - } - - AbstractTimerCallback* clone() const - { - return new TimerCallback(*this); - } - -private: - TimerCallback(); - - C* _pObject; - Callback _method; -}; - - -} // namespace Poco - - -#endif // Foundation_Timer_INCLUDED +// +// Timer.h +// +// $Id: //poco/1.2/Foundation/include/Poco/Timer.h#1 $ +// +// Library: Foundation +// Package: Threading +// Module: Timer +// +// Definition of the Timer and related classes. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_Timer_INCLUDED +#define Foundation_Timer_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Runnable.h" +#include "Poco/Mutex.h" +#include "Poco/Event.h" + + +namespace Poco { + + +class AbstractTimerCallback; +class ThreadPool; + + +class Foundation_API Timer: protected Runnable + /// This class implements a thread-based timer. + /// A timer starts a thread that first waits for a given start interval. + /// Once that interval expires, the timer callback is called repeatedly + /// in the given periodic interval. If the interval is 0, the timer is only + /// called once. + /// The timer callback method can stop the timer by setting the + /// timer's periodic interval to 0. + /// + /// The timer callback runs in its own thread, so multithreading + /// issues (proper synchronization) have to be considered when writing + /// the callback method. + /// + /// The exact interval at which the callback is called depends on many + /// factors like operating system, CPU performance and system load and + /// may differ from the specified interval. + /// + /// The timer thread is taken from a thread pool, so + /// there is a limit to the number of available concurrent timers. +{ +public: + Timer(long startInterval = 0, long periodicInterval = 0); + /// Creates a new timer object. StartInterval and periodicInterval + /// are given in milliseconds. If a periodicInterval of zero is + /// specified, the callback will only be called once, after the + /// startInterval expires. + /// To start the timer, call the Start() method. + + virtual ~Timer(); + /// Stops and destroys the timer. + + void start(const AbstractTimerCallback& method); + /// Starts the timer. + /// Create the TimerCallback as follows: + /// TimerCallback callback(*this, &MyClass::onTimer); + /// timer.start(callback); + /// + /// The timer thread is taken from the global default thread pool. + + void start(const AbstractTimerCallback& method, ThreadPool& threadPool); + /// Starts the timer. + /// Create the TimerCallback as follows: + /// TimerCallback callback(*this, &MyClass::onTimer); + /// timer.start(callback); + + void stop(); + /// Stops the timer. If the callback method is currently running + /// it will be allowed to finish first. + /// WARNING: Never call this method from within the callback method, + /// as a deadlock would result. To stop the timer from within the + /// callback method, call restart(0). + + void restart(); + /// Restarts the periodic interval. If the callback method is already running, + /// nothing will happen. + + void restart(long milliseconds); + /// Sets a new periodic interval and restarts the timer. + /// An interval of 0 will stop the timer. + + long getStartInterval() const; + /// Returns the start interval. + + void setStartInterval(long milliseconds); + /// Sets the start interval. Will only be + /// effective before start() is called. + + long getPeriodicInterval() const; + /// Returns the periodic interval. + + void setPeriodicInterval(long milliseconds); + /// Sets the periodic interval. If the timer is already running + /// the new interval will be effective when the current interval + /// expires. + +protected: + void run(); + +private: + volatile long _startInterval; + volatile long _periodicInterval; + Event _wakeUp; + Event _done; + AbstractTimerCallback* _pCallback; + mutable FastMutex _mutex; +}; + + +class Foundation_API AbstractTimerCallback + /// This is the base class for all instantiations of + /// the TimerCallback template. +{ +public: + AbstractTimerCallback(); + AbstractTimerCallback(const AbstractTimerCallback& callback); + virtual ~AbstractTimerCallback(); + + AbstractTimerCallback& operator = (const AbstractTimerCallback& callback); + + virtual void invoke(Timer& timer) const = 0; + virtual AbstractTimerCallback* clone() const = 0; +}; + + +template +class TimerCallback: public AbstractTimerCallback + /// This template class implements an adapter that sits between + /// a Timer and an object's method invoked by the timer. + /// It is quite similar in concept to the RunnableAdapter, but provides + /// some Timer specific additional methods. + /// See the Timer class for information on how + /// to use this template class. +{ +public: + typedef void (C::*Callback)(Timer&); + + TimerCallback(C& object, Callback method): _pObject(&object), _method(method) + { + } + + TimerCallback(const TimerCallback& callback): _pObject(callback._pObject), _method(callback._method) + { + } + + ~TimerCallback() + { + } + + TimerCallback& operator = (const TimerCallback& callback) + { + if (&callback != this) + { + _pObject = callback._pObject; + _method = callback._method; + } + return *this; + } + + void invoke(Timer& timer) const + { + (_pObject->*_method)(timer); + } + + AbstractTimerCallback* clone() const + { + return new TimerCallback(*this); + } + +private: + TimerCallback(); + + C* _pObject; + Callback _method; +}; + + +} // namespace Poco + + +#endif // Foundation_Timer_INCLUDED diff --git a/Foundation/include/Poco/Timespan.h b/Foundation/include/Poco/Timespan.h index 69f628841..81e8df1fd 100644 --- a/Foundation/include/Poco/Timespan.h +++ b/Foundation/include/Poco/Timespan.h @@ -1,320 +1,320 @@ -// -// Timespan.h -// -// $Id: //poco/1.2/Foundation/include/Poco/Timespan.h#1 $ -// -// Library: Foundation -// Package: DateTime -// Module: Timespan -// -// Definition of the Timespan class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_Timespan_INCLUDED -#define Foundation_Timespan_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/Timestamp.h" - - -namespace Poco { - - -class Foundation_API Timespan - /// A class that represents time spans up to microsecond resolution. -{ -public: - typedef Timestamp::TimeDiff TimeDiff; - - Timespan(); - /// Creates a zero Timespan. - - Timespan(TimeDiff microseconds); - /// Creates a Timespan. - - Timespan(long seconds, long microseconds); - /// Creates a Timespan. Useful for creating - /// a Timespan from a struct timeval. - - Timespan(int days, int hours, int minutes, int seconds, int microseconds); - /// Creates a Timespan. - - Timespan(const Timespan& timespan); - /// Creates a Timespan from another one. - - ~Timespan(); - /// Destroys the Timespan. - - Timespan& operator = (const Timespan& timespan); - /// Assignment operator. - - Timespan& operator = (TimeDiff microseconds); - /// Assignment operator. - - Timespan& assign(int days, int hours, int minutes, int seconds, int microseconds); - /// Assigns a new span. - - Timespan& assign(long seconds, long microseconds); - /// Assigns a new span. Useful for assigning - /// from a struct timeval. - - void swap(Timespan& timespan); - /// Swaps the Timespan with another one. - - bool operator == (const Timespan& ts) const; - bool operator != (const Timespan& ts) const; - bool operator > (const Timespan& ts) const; - bool operator >= (const Timespan& ts) const; - bool operator < (const Timespan& ts) const; - bool operator <= (const Timespan& ts) const; - - bool operator == (TimeDiff microseconds) const; - bool operator != (TimeDiff microseconds) const; - bool operator > (TimeDiff microseconds) const; - bool operator >= (TimeDiff microseconds) const; - bool operator < (TimeDiff microseconds) const; - bool operator <= (TimeDiff microseconds) const; - - Timespan operator + (const Timespan& d) const; - Timespan operator - (const Timespan& d) const; - Timespan& operator += (const Timespan& d); - Timespan& operator -= (const Timespan& d); - - Timespan operator + (TimeDiff microseconds) const; - Timespan operator - (TimeDiff microseconds) const; - Timespan& operator += (TimeDiff microseconds); - Timespan& operator -= (TimeDiff microseconds); - - int days() const; - /// Returns the number of days. - - int hours() const; - /// Returns the number of hours (0 to 23). - - int totalHours() const; - /// Returns the total number of hours. - - int minutes() const; - /// Returns the number of minutes (0 to 59). - - int totalMinutes() const; - /// Returns the total number of minutes. - - int seconds() const; - /// Returns the number of seconds (0 to 59). - - int totalSeconds() const; - /// Returns the total number of seconds. - - int milliseconds() const; - /// Returns the number of milliseconds (0 to 999). - - TimeDiff totalMilliseconds() const; - /// Returns the total number of milliseconds. - - int microseconds() const; - /// Returns the fractions of a millisecond - /// in microseconds (0 to 999). - - int useconds() const; - /// Returns the fractions of a second - /// in microseconds (0 to 999). - - TimeDiff totalMicroseconds() const; - /// Returns the total number of microseconds. - - static const TimeDiff MILLISECONDS; /// The number of microseconds in a millisecond. - static const TimeDiff SECONDS; /// The number of microseconds in a second. - static const TimeDiff MINUTES; /// The number of microseconds in a minute. - static const TimeDiff HOURS; /// The number of microseconds in a hour. - static const TimeDiff DAYS; /// The number of microseconds in a day. - -private: - TimeDiff _span; -}; - - -// -// inlines -// -inline int Timespan::days() const -{ - return int(_span/DAYS); -} - - -inline int Timespan::hours() const -{ - return int((_span/HOURS) % 24); -} - - -inline int Timespan::totalHours() const -{ - return int(_span/HOURS); -} - - -inline int Timespan::minutes() const -{ - return int((_span/MINUTES) % 60); -} - - -inline int Timespan::totalMinutes() const -{ - return int(_span/MINUTES); -} - - -inline int Timespan::seconds() const -{ - return int((_span/SECONDS) % 60); -} - - -inline int Timespan::totalSeconds() const -{ - return int(_span/SECONDS); -} - - -inline int Timespan::milliseconds() const -{ - return int((_span/MILLISECONDS) % 1000); -} - - -inline Timespan::TimeDiff Timespan::totalMilliseconds() const -{ - return _span/MILLISECONDS; -} - - -inline int Timespan::microseconds() const -{ - return int(_span % 1000); -} - - -inline int Timespan::useconds() const -{ - return int(_span % 1000000); -} - - -inline Timespan::TimeDiff Timespan::totalMicroseconds() const -{ - return _span; -} - - -inline bool Timespan::operator == (const Timespan& ts) const -{ - return _span == ts._span; -} - - -inline bool Timespan::operator != (const Timespan& ts) const -{ - return _span != ts._span; -} - - -inline bool Timespan::operator > (const Timespan& ts) const -{ - return _span > ts._span; -} - - -inline bool Timespan::operator >= (const Timespan& ts) const -{ - return _span >= ts._span; -} - - -inline bool Timespan::operator < (const Timespan& ts) const -{ - return _span < ts._span; -} - - -inline bool Timespan::operator <= (const Timespan& ts) const -{ - return _span <= ts._span; -} - - -inline bool Timespan::operator == (TimeDiff microseconds) const -{ - return _span == microseconds; -} - - -inline bool Timespan::operator != (TimeDiff microseconds) const -{ - return _span != microseconds; -} - - -inline bool Timespan::operator > (TimeDiff microseconds) const -{ - return _span > microseconds; -} - - -inline bool Timespan::operator >= (TimeDiff microseconds) const -{ - return _span >= microseconds; -} - - -inline bool Timespan::operator < (TimeDiff microseconds) const -{ - return _span < microseconds; -} - - -inline bool Timespan::operator <= (TimeDiff microseconds) const -{ - return _span <= microseconds; -} - - -inline void swap(Timespan& s1, Timespan& s2) -{ - s1.swap(s2); -} - - -} // namespace Poco - - -#endif // Foundation_Timespan_INCLUDED +// +// Timespan.h +// +// $Id: //poco/1.2/Foundation/include/Poco/Timespan.h#1 $ +// +// Library: Foundation +// Package: DateTime +// Module: Timespan +// +// Definition of the Timespan class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_Timespan_INCLUDED +#define Foundation_Timespan_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Timestamp.h" + + +namespace Poco { + + +class Foundation_API Timespan + /// A class that represents time spans up to microsecond resolution. +{ +public: + typedef Timestamp::TimeDiff TimeDiff; + + Timespan(); + /// Creates a zero Timespan. + + Timespan(TimeDiff microseconds); + /// Creates a Timespan. + + Timespan(long seconds, long microseconds); + /// Creates a Timespan. Useful for creating + /// a Timespan from a struct timeval. + + Timespan(int days, int hours, int minutes, int seconds, int microseconds); + /// Creates a Timespan. + + Timespan(const Timespan& timespan); + /// Creates a Timespan from another one. + + ~Timespan(); + /// Destroys the Timespan. + + Timespan& operator = (const Timespan& timespan); + /// Assignment operator. + + Timespan& operator = (TimeDiff microseconds); + /// Assignment operator. + + Timespan& assign(int days, int hours, int minutes, int seconds, int microseconds); + /// Assigns a new span. + + Timespan& assign(long seconds, long microseconds); + /// Assigns a new span. Useful for assigning + /// from a struct timeval. + + void swap(Timespan& timespan); + /// Swaps the Timespan with another one. + + bool operator == (const Timespan& ts) const; + bool operator != (const Timespan& ts) const; + bool operator > (const Timespan& ts) const; + bool operator >= (const Timespan& ts) const; + bool operator < (const Timespan& ts) const; + bool operator <= (const Timespan& ts) const; + + bool operator == (TimeDiff microseconds) const; + bool operator != (TimeDiff microseconds) const; + bool operator > (TimeDiff microseconds) const; + bool operator >= (TimeDiff microseconds) const; + bool operator < (TimeDiff microseconds) const; + bool operator <= (TimeDiff microseconds) const; + + Timespan operator + (const Timespan& d) const; + Timespan operator - (const Timespan& d) const; + Timespan& operator += (const Timespan& d); + Timespan& operator -= (const Timespan& d); + + Timespan operator + (TimeDiff microseconds) const; + Timespan operator - (TimeDiff microseconds) const; + Timespan& operator += (TimeDiff microseconds); + Timespan& operator -= (TimeDiff microseconds); + + int days() const; + /// Returns the number of days. + + int hours() const; + /// Returns the number of hours (0 to 23). + + int totalHours() const; + /// Returns the total number of hours. + + int minutes() const; + /// Returns the number of minutes (0 to 59). + + int totalMinutes() const; + /// Returns the total number of minutes. + + int seconds() const; + /// Returns the number of seconds (0 to 59). + + int totalSeconds() const; + /// Returns the total number of seconds. + + int milliseconds() const; + /// Returns the number of milliseconds (0 to 999). + + TimeDiff totalMilliseconds() const; + /// Returns the total number of milliseconds. + + int microseconds() const; + /// Returns the fractions of a millisecond + /// in microseconds (0 to 999). + + int useconds() const; + /// Returns the fractions of a second + /// in microseconds (0 to 999). + + TimeDiff totalMicroseconds() const; + /// Returns the total number of microseconds. + + static const TimeDiff MILLISECONDS; /// The number of microseconds in a millisecond. + static const TimeDiff SECONDS; /// The number of microseconds in a second. + static const TimeDiff MINUTES; /// The number of microseconds in a minute. + static const TimeDiff HOURS; /// The number of microseconds in a hour. + static const TimeDiff DAYS; /// The number of microseconds in a day. + +private: + TimeDiff _span; +}; + + +// +// inlines +// +inline int Timespan::days() const +{ + return int(_span/DAYS); +} + + +inline int Timespan::hours() const +{ + return int((_span/HOURS) % 24); +} + + +inline int Timespan::totalHours() const +{ + return int(_span/HOURS); +} + + +inline int Timespan::minutes() const +{ + return int((_span/MINUTES) % 60); +} + + +inline int Timespan::totalMinutes() const +{ + return int(_span/MINUTES); +} + + +inline int Timespan::seconds() const +{ + return int((_span/SECONDS) % 60); +} + + +inline int Timespan::totalSeconds() const +{ + return int(_span/SECONDS); +} + + +inline int Timespan::milliseconds() const +{ + return int((_span/MILLISECONDS) % 1000); +} + + +inline Timespan::TimeDiff Timespan::totalMilliseconds() const +{ + return _span/MILLISECONDS; +} + + +inline int Timespan::microseconds() const +{ + return int(_span % 1000); +} + + +inline int Timespan::useconds() const +{ + return int(_span % 1000000); +} + + +inline Timespan::TimeDiff Timespan::totalMicroseconds() const +{ + return _span; +} + + +inline bool Timespan::operator == (const Timespan& ts) const +{ + return _span == ts._span; +} + + +inline bool Timespan::operator != (const Timespan& ts) const +{ + return _span != ts._span; +} + + +inline bool Timespan::operator > (const Timespan& ts) const +{ + return _span > ts._span; +} + + +inline bool Timespan::operator >= (const Timespan& ts) const +{ + return _span >= ts._span; +} + + +inline bool Timespan::operator < (const Timespan& ts) const +{ + return _span < ts._span; +} + + +inline bool Timespan::operator <= (const Timespan& ts) const +{ + return _span <= ts._span; +} + + +inline bool Timespan::operator == (TimeDiff microseconds) const +{ + return _span == microseconds; +} + + +inline bool Timespan::operator != (TimeDiff microseconds) const +{ + return _span != microseconds; +} + + +inline bool Timespan::operator > (TimeDiff microseconds) const +{ + return _span > microseconds; +} + + +inline bool Timespan::operator >= (TimeDiff microseconds) const +{ + return _span >= microseconds; +} + + +inline bool Timespan::operator < (TimeDiff microseconds) const +{ + return _span < microseconds; +} + + +inline bool Timespan::operator <= (TimeDiff microseconds) const +{ + return _span <= microseconds; +} + + +inline void swap(Timespan& s1, Timespan& s2) +{ + s1.swap(s2); +} + + +} // namespace Poco + + +#endif // Foundation_Timespan_INCLUDED diff --git a/Foundation/include/Poco/Timestamp.h b/Foundation/include/Poco/Timestamp.h index e3a6d68fc..abcd61c99 100644 --- a/Foundation/include/Poco/Timestamp.h +++ b/Foundation/include/Poco/Timestamp.h @@ -1,260 +1,260 @@ -// -// Timestamp.h -// -// $Id: //poco/1.2/Foundation/include/Poco/Timestamp.h#2 $ -// -// Library: Foundation -// Package: DateTime -// Module: Timestamp -// -// Definition of the Timestamp class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_Timestamp_INCLUDED -#define Foundation_Timestamp_INCLUDED - - -#include "Poco/Foundation.h" -#include - - -namespace Poco { - - -class Foundation_API Timestamp - /// A Timestamp stores a monotonic time value - /// with (theoretical) microseconds resolution. - /// Timestamps can be compared with each other - /// and simple arithmetics are supported. - /// Timestamps are UTC (Coordinated Universal Time) - /// based and thus independent of the timezone - /// in effect on the system. -{ -public: - typedef Int64 TimeVal; /// monotonic UTC time value in microsecond resolution - typedef Int64 UtcTimeVal; /// monotonic UTC time value in 100 nanosecond resolution - typedef Int64 TimeDiff; /// difference between two timestamps in microseconds - - Timestamp(); - /// Creates a timestamp with the current time. - - Timestamp(TimeVal tv); - /// Creates a timestamp from the given time value. - - Timestamp(const Timestamp& other); - /// Copy constructor. - - ~Timestamp(); - /// Destroys the timestamp - - Timestamp& operator = (const Timestamp& other); - Timestamp& operator = (TimeVal tv); - - void swap(Timestamp& timestamp); - /// Swaps the Timestamp with another one. - - void update(); - /// Updates the Timestamp with the current time. - - bool operator == (const Timestamp& ts) const; - bool operator != (const Timestamp& ts) const; - bool operator > (const Timestamp& ts) const; - bool operator >= (const Timestamp& ts) const; - bool operator < (const Timestamp& ts) const; - bool operator <= (const Timestamp& ts) const; - - Timestamp operator + (TimeDiff d) const; - Timestamp operator - (TimeDiff d) const; - TimeDiff operator - (const Timestamp& ts) const; - Timestamp& operator += (TimeDiff d); - Timestamp& operator -= (TimeDiff d); - - time_t epochTime() const; - /// Returns the timestamp expressed in time_t. - /// time_t base time is midnight, January 1, 1970. - /// Resolution is one second. - - UtcTimeVal utcTime() const; - /// Returns the timestamp expressed in UTC-based - /// time. UTC base time is midnight, October 15, 1582. - /// Resolution is 100 nanoseconds. - - TimeVal epochMicroseconds() const; - /// Returns the timestamp expressed in microseconds - /// since the Unix epoch, midnight, January 1, 1970. - - TimeDiff elapsed() const; - /// Returns the time elapsed since the time denoted by - /// the timestamp. Equivalent to Timestamp() - *this. - - bool isElapsed(TimeDiff interval) const; - /// Returns true iff the given interval has passed - /// since the time denoted by the timestamp. - - static Timestamp fromEpochTime(time_t t); - /// Creates a timestamp from a time_t. - - static Timestamp fromUtcTime(UtcTimeVal val); - /// Creates a timestamp from a UTC time value. - - static TimeVal resolution(); - /// Returns the resolution in units per second. - /// Since the timestamp has microsecond resolution, - /// the returned value is always 1000000. - -#if defined(_WIN32) - static Timestamp fromFileTimeNP(UInt32 fileTimeLow, UInt32 fileTimeHigh); - void toFileTimeNP(UInt32& fileTimeLow, UInt32& fileTimeHigh) const; -#endif - -private: - TimeVal _ts; -}; - - -// -// inlines -// -inline bool Timestamp::operator == (const Timestamp& ts) const -{ - return _ts == ts._ts; -} - - -inline bool Timestamp::operator != (const Timestamp& ts) const -{ - return _ts != ts._ts; -} - - -inline bool Timestamp::operator > (const Timestamp& ts) const -{ - return _ts > ts._ts; -} - - -inline bool Timestamp::operator >= (const Timestamp& ts) const -{ - return _ts >= ts._ts; -} - - -inline bool Timestamp::operator < (const Timestamp& ts) const -{ - return _ts < ts._ts; -} - - -inline bool Timestamp::operator <= (const Timestamp& ts) const -{ - return _ts <= ts._ts; -} - - -inline Timestamp Timestamp::operator + (Timestamp::TimeDiff d) const -{ - return Timestamp(_ts + d); -} - - -inline Timestamp Timestamp::operator - (Timestamp::TimeDiff d) const -{ - return Timestamp(_ts - d); -} - - -inline Timestamp::TimeDiff Timestamp::operator - (const Timestamp& ts) const -{ - return _ts - ts._ts; -} - - -inline Timestamp& Timestamp::operator += (Timestamp::TimeDiff d) -{ - _ts += d; - return *this; -} - - -inline Timestamp& Timestamp::operator -= (Timestamp::TimeDiff d) -{ - _ts -= d; - return *this; -} - - -inline time_t Timestamp::epochTime() const -{ - return time_t(_ts/resolution()); -} - - -inline Timestamp::UtcTimeVal Timestamp::utcTime() const -{ - return _ts*10 + (TimeDiff(0x01b21dd2) << 32) + 0x13814000; -} - - -inline Timestamp::TimeVal Timestamp::epochMicroseconds() const -{ - return _ts; -} - - -inline Timestamp::TimeDiff Timestamp::elapsed() const -{ - Timestamp now; - return now - *this; -} - - -inline bool Timestamp::isElapsed(Timestamp::TimeDiff interval) const -{ - Timestamp now; - Timestamp::TimeDiff diff = now - *this; - return diff >= interval; -} - - -inline Timestamp::TimeVal Timestamp::resolution() -{ - return 1000000; -} - - -inline void swap(Timestamp& s1, Timestamp& s2) -{ - s1.swap(s2); -} - - -} // namespace Poco - - -#endif // Foundation_Timestamp_INCLUDED +// +// Timestamp.h +// +// $Id: //poco/1.2/Foundation/include/Poco/Timestamp.h#2 $ +// +// Library: Foundation +// Package: DateTime +// Module: Timestamp +// +// Definition of the Timestamp class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_Timestamp_INCLUDED +#define Foundation_Timestamp_INCLUDED + + +#include "Poco/Foundation.h" +#include + + +namespace Poco { + + +class Foundation_API Timestamp + /// A Timestamp stores a monotonic time value + /// with (theoretical) microseconds resolution. + /// Timestamps can be compared with each other + /// and simple arithmetics are supported. + /// Timestamps are UTC (Coordinated Universal Time) + /// based and thus independent of the timezone + /// in effect on the system. +{ +public: + typedef Int64 TimeVal; /// monotonic UTC time value in microsecond resolution + typedef Int64 UtcTimeVal; /// monotonic UTC time value in 100 nanosecond resolution + typedef Int64 TimeDiff; /// difference between two timestamps in microseconds + + Timestamp(); + /// Creates a timestamp with the current time. + + Timestamp(TimeVal tv); + /// Creates a timestamp from the given time value. + + Timestamp(const Timestamp& other); + /// Copy constructor. + + ~Timestamp(); + /// Destroys the timestamp + + Timestamp& operator = (const Timestamp& other); + Timestamp& operator = (TimeVal tv); + + void swap(Timestamp& timestamp); + /// Swaps the Timestamp with another one. + + void update(); + /// Updates the Timestamp with the current time. + + bool operator == (const Timestamp& ts) const; + bool operator != (const Timestamp& ts) const; + bool operator > (const Timestamp& ts) const; + bool operator >= (const Timestamp& ts) const; + bool operator < (const Timestamp& ts) const; + bool operator <= (const Timestamp& ts) const; + + Timestamp operator + (TimeDiff d) const; + Timestamp operator - (TimeDiff d) const; + TimeDiff operator - (const Timestamp& ts) const; + Timestamp& operator += (TimeDiff d); + Timestamp& operator -= (TimeDiff d); + + time_t epochTime() const; + /// Returns the timestamp expressed in time_t. + /// time_t base time is midnight, January 1, 1970. + /// Resolution is one second. + + UtcTimeVal utcTime() const; + /// Returns the timestamp expressed in UTC-based + /// time. UTC base time is midnight, October 15, 1582. + /// Resolution is 100 nanoseconds. + + TimeVal epochMicroseconds() const; + /// Returns the timestamp expressed in microseconds + /// since the Unix epoch, midnight, January 1, 1970. + + TimeDiff elapsed() const; + /// Returns the time elapsed since the time denoted by + /// the timestamp. Equivalent to Timestamp() - *this. + + bool isElapsed(TimeDiff interval) const; + /// Returns true iff the given interval has passed + /// since the time denoted by the timestamp. + + static Timestamp fromEpochTime(time_t t); + /// Creates a timestamp from a time_t. + + static Timestamp fromUtcTime(UtcTimeVal val); + /// Creates a timestamp from a UTC time value. + + static TimeVal resolution(); + /// Returns the resolution in units per second. + /// Since the timestamp has microsecond resolution, + /// the returned value is always 1000000. + +#if defined(_WIN32) + static Timestamp fromFileTimeNP(UInt32 fileTimeLow, UInt32 fileTimeHigh); + void toFileTimeNP(UInt32& fileTimeLow, UInt32& fileTimeHigh) const; +#endif + +private: + TimeVal _ts; +}; + + +// +// inlines +// +inline bool Timestamp::operator == (const Timestamp& ts) const +{ + return _ts == ts._ts; +} + + +inline bool Timestamp::operator != (const Timestamp& ts) const +{ + return _ts != ts._ts; +} + + +inline bool Timestamp::operator > (const Timestamp& ts) const +{ + return _ts > ts._ts; +} + + +inline bool Timestamp::operator >= (const Timestamp& ts) const +{ + return _ts >= ts._ts; +} + + +inline bool Timestamp::operator < (const Timestamp& ts) const +{ + return _ts < ts._ts; +} + + +inline bool Timestamp::operator <= (const Timestamp& ts) const +{ + return _ts <= ts._ts; +} + + +inline Timestamp Timestamp::operator + (Timestamp::TimeDiff d) const +{ + return Timestamp(_ts + d); +} + + +inline Timestamp Timestamp::operator - (Timestamp::TimeDiff d) const +{ + return Timestamp(_ts - d); +} + + +inline Timestamp::TimeDiff Timestamp::operator - (const Timestamp& ts) const +{ + return _ts - ts._ts; +} + + +inline Timestamp& Timestamp::operator += (Timestamp::TimeDiff d) +{ + _ts += d; + return *this; +} + + +inline Timestamp& Timestamp::operator -= (Timestamp::TimeDiff d) +{ + _ts -= d; + return *this; +} + + +inline time_t Timestamp::epochTime() const +{ + return time_t(_ts/resolution()); +} + + +inline Timestamp::UtcTimeVal Timestamp::utcTime() const +{ + return _ts*10 + (TimeDiff(0x01b21dd2) << 32) + 0x13814000; +} + + +inline Timestamp::TimeVal Timestamp::epochMicroseconds() const +{ + return _ts; +} + + +inline Timestamp::TimeDiff Timestamp::elapsed() const +{ + Timestamp now; + return now - *this; +} + + +inline bool Timestamp::isElapsed(Timestamp::TimeDiff interval) const +{ + Timestamp now; + Timestamp::TimeDiff diff = now - *this; + return diff >= interval; +} + + +inline Timestamp::TimeVal Timestamp::resolution() +{ + return 1000000; +} + + +inline void swap(Timestamp& s1, Timestamp& s2) +{ + s1.swap(s2); +} + + +} // namespace Poco + + +#endif // Foundation_Timestamp_INCLUDED diff --git a/Foundation/include/Poco/Timezone.h b/Foundation/include/Poco/Timezone.h index 2ded0e4e2..7624b84e8 100644 --- a/Foundation/include/Poco/Timezone.h +++ b/Foundation/include/Poco/Timezone.h @@ -1,89 +1,89 @@ -// -// Timezone.h -// -// $Id: //poco/1.2/Foundation/include/Poco/Timezone.h#1 $ -// -// Library: Foundation -// Package: DateTime -// Module: Timezone -// -// Definition of the Timezone class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_Timezone_INCLUDED -#define Foundation_Timezone_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/Timestamp.h" - - -namespace Poco { - - -class Foundation_API Timezone - /// This class provides information about the current timezone. -{ -public: - static int utcOffset(); - /// Returns the offset of local time to UTC, in seconds. - /// local time = UTC + utcOffset(). - - static int dst(); - /// Returns the daylight saving time offset in seconds if - /// daylight saving time is in use. - /// local time = UTC + utcOffset() + dst(). - - static bool isDst(const Timestamp& timestamp); - /// Returns true if daylight saving time is in effect - /// for the given time. Depending on the operating system - /// platform this might only work reliably for certain - /// date ranges, as the C library's localtime() function - /// is used. - - static int tzd(); - /// Returns the time zone differential for the current timezone. - /// The timezone differential is computed as utcOffset() + dst() - /// and is expressed in seconds. - - static std::string name(); - /// Returns the timezone name currently in effect. - - static std::string standardName(); - /// Returns the timezone name if not daylight saving time is in effect. - - static std::string dstName(); - /// Returns the timezone name if daylight saving time is in effect. -}; - - -} // namespace Poco - - -#endif // Foundation_Timezone_INCLUDED +// +// Timezone.h +// +// $Id: //poco/1.2/Foundation/include/Poco/Timezone.h#1 $ +// +// Library: Foundation +// Package: DateTime +// Module: Timezone +// +// Definition of the Timezone class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_Timezone_INCLUDED +#define Foundation_Timezone_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Timestamp.h" + + +namespace Poco { + + +class Foundation_API Timezone + /// This class provides information about the current timezone. +{ +public: + static int utcOffset(); + /// Returns the offset of local time to UTC, in seconds. + /// local time = UTC + utcOffset(). + + static int dst(); + /// Returns the daylight saving time offset in seconds if + /// daylight saving time is in use. + /// local time = UTC + utcOffset() + dst(). + + static bool isDst(const Timestamp& timestamp); + /// Returns true if daylight saving time is in effect + /// for the given time. Depending on the operating system + /// platform this might only work reliably for certain + /// date ranges, as the C library's localtime() function + /// is used. + + static int tzd(); + /// Returns the time zone differential for the current timezone. + /// The timezone differential is computed as utcOffset() + dst() + /// and is expressed in seconds. + + static std::string name(); + /// Returns the timezone name currently in effect. + + static std::string standardName(); + /// Returns the timezone name if not daylight saving time is in effect. + + static std::string dstName(); + /// Returns the timezone name if daylight saving time is in effect. +}; + + +} // namespace Poco + + +#endif // Foundation_Timezone_INCLUDED diff --git a/Foundation/include/Poco/Token.h b/Foundation/include/Poco/Token.h index 1dfc02151..c1ef690db 100644 --- a/Foundation/include/Poco/Token.h +++ b/Foundation/include/Poco/Token.h @@ -1,183 +1,183 @@ -// -// Token.h -// -// $Id: //poco/1.2/Foundation/include/Poco/Token.h#1 $ -// -// Library: Foundation -// Package: Streams -// Module: StreamTokenizer -// -// Definition of the Token class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_Token_INCLUDED -#define Foundation_Token_INCLUDED - - -#include "Poco/Foundation.h" -#include - - -namespace Poco { - - -class Foundation_API Token - /// The base class for all token classes that can be - /// registered with the StreamTokenizer. -{ -public: - enum Class - { - IDENTIFIER_TOKEN, - KEYWORD_TOKEN, - SEPARATOR_TOKEN, - OPERATOR_TOKEN, - STRING_LITERAL_TOKEN, - CHAR_LITERAL_TOKEN, - INTEGER_LITERAL_TOKEN, - LONG_INTEGER_LITERAL_TOKEN, - FLOAT_LITERAL_TOKEN, - DOUBLE_LITERAL_TOKEN, - COMMENT_TOKEN, - SPECIAL_COMMENT_TOKEN, - PREPROCESSOR_TOKEN, - WHITESPACE_TOKEN, - EOF_TOKEN, - INVALID_TOKEN, - USER_TOKEN - }; - - Token(); - /// Creates the Token. - - virtual ~Token(); - /// Destroys the Token. - - virtual bool start(char c, std::istream& istr); - /// Checks if the given character (and, optionally, - /// the next character in the input stream) start - /// a valid token. Returns true if so, false - /// otherwise. - /// - /// The current read position in istr must not be - /// changed. In other words, only the peek() method - /// of istream may be used. - /// - /// If the character starts the token, it should - /// be set as the token's value. - - virtual void finish(std::istream& istr); - /// Builds the token by reading and appending - /// the remaining characters from istr. - - virtual Class tokenClass() const; - /// Returns the kind of the token. - - const std::string& tokenString() const; - /// Returns the token's raw string. - - virtual std::string asString() const; - /// Returns a string representation of the token. - - virtual int asInteger() const; - /// Returns an integer representation of the token. - - virtual double asFloat() const; - /// Returns a floating-point representation of the token. - - virtual char asChar() const; - /// Returns a char representation of the token. - - bool is(Class tokenClass) const; - /// Returns true iff the token has the given class. - -protected: - std::string _value; - -private: - Token(const Token&); - Token& operator = (const Token&); -}; - - -class Foundation_API InvalidToken: public Token - /// This token class is used for signalling that - /// an invalid character sequence has been encountered - /// in the input stream. -{ -public: - InvalidToken(); - ~InvalidToken(); - Class tokenClass() const; -}; - - -class Foundation_API EOFToken: public Token - /// This token class is used to signal the - /// end of the input stream. -{ -public: - EOFToken(); - ~EOFToken(); - Class tokenClass() const; -}; - - -class Foundation_API WhitespaceToken: public Token - /// This pseudo token class is used to eat - /// up whitespace in between real tokens. -{ -public: - WhitespaceToken(); - ~WhitespaceToken(); - Class tokenClass() const; - bool start(char c, std::istream& istr); - void finish(std::istream& istr); -}; - - -// -// inlines -// -inline const std::string& Token::tokenString() const -{ - return _value; -} - - -inline bool Token::is(Token::Class cls) const -{ - return tokenClass() == cls; -} - - -} // namespace Poco - - -#endif // Foundation_Token_INCLUDED +// +// Token.h +// +// $Id: //poco/1.2/Foundation/include/Poco/Token.h#1 $ +// +// Library: Foundation +// Package: Streams +// Module: StreamTokenizer +// +// Definition of the Token class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_Token_INCLUDED +#define Foundation_Token_INCLUDED + + +#include "Poco/Foundation.h" +#include + + +namespace Poco { + + +class Foundation_API Token + /// The base class for all token classes that can be + /// registered with the StreamTokenizer. +{ +public: + enum Class + { + IDENTIFIER_TOKEN, + KEYWORD_TOKEN, + SEPARATOR_TOKEN, + OPERATOR_TOKEN, + STRING_LITERAL_TOKEN, + CHAR_LITERAL_TOKEN, + INTEGER_LITERAL_TOKEN, + LONG_INTEGER_LITERAL_TOKEN, + FLOAT_LITERAL_TOKEN, + DOUBLE_LITERAL_TOKEN, + COMMENT_TOKEN, + SPECIAL_COMMENT_TOKEN, + PREPROCESSOR_TOKEN, + WHITESPACE_TOKEN, + EOF_TOKEN, + INVALID_TOKEN, + USER_TOKEN + }; + + Token(); + /// Creates the Token. + + virtual ~Token(); + /// Destroys the Token. + + virtual bool start(char c, std::istream& istr); + /// Checks if the given character (and, optionally, + /// the next character in the input stream) start + /// a valid token. Returns true if so, false + /// otherwise. + /// + /// The current read position in istr must not be + /// changed. In other words, only the peek() method + /// of istream may be used. + /// + /// If the character starts the token, it should + /// be set as the token's value. + + virtual void finish(std::istream& istr); + /// Builds the token by reading and appending + /// the remaining characters from istr. + + virtual Class tokenClass() const; + /// Returns the kind of the token. + + const std::string& tokenString() const; + /// Returns the token's raw string. + + virtual std::string asString() const; + /// Returns a string representation of the token. + + virtual int asInteger() const; + /// Returns an integer representation of the token. + + virtual double asFloat() const; + /// Returns a floating-point representation of the token. + + virtual char asChar() const; + /// Returns a char representation of the token. + + bool is(Class tokenClass) const; + /// Returns true iff the token has the given class. + +protected: + std::string _value; + +private: + Token(const Token&); + Token& operator = (const Token&); +}; + + +class Foundation_API InvalidToken: public Token + /// This token class is used for signalling that + /// an invalid character sequence has been encountered + /// in the input stream. +{ +public: + InvalidToken(); + ~InvalidToken(); + Class tokenClass() const; +}; + + +class Foundation_API EOFToken: public Token + /// This token class is used to signal the + /// end of the input stream. +{ +public: + EOFToken(); + ~EOFToken(); + Class tokenClass() const; +}; + + +class Foundation_API WhitespaceToken: public Token + /// This pseudo token class is used to eat + /// up whitespace in between real tokens. +{ +public: + WhitespaceToken(); + ~WhitespaceToken(); + Class tokenClass() const; + bool start(char c, std::istream& istr); + void finish(std::istream& istr); +}; + + +// +// inlines +// +inline const std::string& Token::tokenString() const +{ + return _value; +} + + +inline bool Token::is(Token::Class cls) const +{ + return tokenClass() == cls; +} + + +} // namespace Poco + + +#endif // Foundation_Token_INCLUDED diff --git a/Foundation/include/Poco/Types.h b/Foundation/include/Poco/Types.h index 86380619c..a60a3559e 100644 --- a/Foundation/include/Poco/Types.h +++ b/Foundation/include/Poco/Types.h @@ -1,214 +1,214 @@ -// -// Types.h -// -// $Id: //poco/1.2/Foundation/include/Poco/Types.h#1 $ -// -// Library: Foundation -// Package: Core -// Module: Types -// -// Definitions of fixed-size integer types for various platforms -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_Types_INCLUDED -#define Foundation_Types_INCLUDED - - -#include "Poco/Foundation.h" - - -namespace Poco { - - -#if defined(_MSC_VER) - // - // Windows/Visual C++ - // - typedef signed char Int8; - typedef unsigned char UInt8; - typedef signed short Int16; - typedef unsigned short UInt16; - typedef signed int Int32; - typedef unsigned int UInt32; - typedef signed __int64 Int64; - typedef unsigned __int64 UInt64; - #if defined(_WIN64) - #define POCO_PTR_IS_64_BIT 1 - typedef signed __int64 IntPtr; - typedef unsigned __int64 UIntPtr; - #else - typedef signed long IntPtr; - typedef unsigned long UIntPtr; - #endif - #define POCO_HAVE_INT64 1 -#elif defined(__GNUC__) - // - // Unix/GCC - // - typedef signed char Int8; - typedef unsigned char UInt8; - typedef signed short Int16; - typedef unsigned short UInt16; - typedef signed int Int32; - typedef unsigned int UInt32; - typedef signed long IntPtr; - typedef unsigned long UIntPtr; - #if defined(__LP64__) - #define POCO_PTR_IS_64_BIT 1 - #define POCO_LONG_IS_64_BIT 1 - typedef signed long Int64; - typedef unsigned long UInt64; - #else - typedef signed long long Int64; - typedef unsigned long long UInt64; - #endif - #define POCO_HAVE_INT64 1 -#elif defined(__DECCXX) - // - // Compaq C++ - // - typedef signed char Int8; - typedef unsigned char UInt8; - typedef signed short Int16; - typedef unsigned short UInt16; - typedef signed int Int32; - typedef unsigned int UInt32; - typedef signed __int64 Int64; - typedef unsigned __int64 UInt64; - #if defined(__VMS) - #if defined(__32BITS) - typedef signed long IntPtr; - typedef unsigned long UIntPtr; - #else - typedef Int64 IntPtr; - typedef UInt64 UIntPtr; - #define POCO_PTR_IS_64_BIT 1 - #endif - #else - typedef signed long IntPtr; - typedef unsigned long UIntPtr; - #define POCO_PTR_IS_64_BIT 1 - #define POCO_LONG_IS_64_BIT 1 - #endif - #define POCO_HAVE_INT64 1 -#elif defined(__HP_aCC) - // - // HP Ansi C++ - // - typedef signed char Int8; - typedef unsigned char UInt8; - typedef signed short Int16; - typedef unsigned short UInt16; - typedef signed int Int32; - typedef unsigned int UInt32; - typedef signed long IntPtr; - typedef unsigned long UIntPtr; - #if defined(__LP64__) - #define POCO_PTR_IS_64_BIT 1 - #define POCO_LONG_IS_64_BIT 1 - typedef signed long Int64; - typedef unsigned long UInt64; - #else - typedef signed long long Int64; - typedef unsigned long long UInt64; - #endif - #define POCO_HAVE_INT64 1 -#elif defined(__SUNPRO_CC) - // - // SUN Forte C++ - // - typedef signed char Int8; - typedef unsigned char UInt8; - typedef signed short Int16; - typedef unsigned short UInt16; - typedef signed int Int32; - typedef unsigned int UInt32; - typedef signed long IntPtr; - typedef unsigned long UIntPtr; - #if defined(__sparcv9) - #define POCO_PTR_IS_64_BIT 1 - #define POCO_LONG_IS_64_BIT 1 - typedef signed long Int64; - typedef unsigned long UInt64; - #else - typedef signed long long Int64; - typedef unsigned long long UInt64; - #endif - #define POCO_HAVE_INT64 1 -#elif defined(__IBMCPP__) - // - // IBM XL C++ - // - typedef signed char Int8; - typedef unsigned char UInt8; - typedef signed short Int16; - typedef unsigned short UInt16; - typedef signed int Int32; - typedef unsigned int UInt32; - typedef signed long IntPtr; - typedef unsigned long UIntPtr; - #if defined(__64BIT__) - #define POCO_PTR_IS_64_BIT 1 - #define POCO_LONG_IS_64_BIT 1 - typedef signed long Int64; - typedef unsigned long UInt64; - #else - typedef signed long long Int64; - typedef unsigned long long UInt64; - #endif - #define POCO_HAVE_INT64 1 -#elif defined(__sgi) - // - // MIPSpro C++ - // - typedef signed char Int8; - typedef unsigned char UInt8; - typedef signed short Int16; - typedef unsigned short UInt16; - typedef signed int Int32; - typedef unsigned int UInt32; - typedef signed long IntPtr; - typedef unsigned long UIntPtr; - #if _MIPS_SZLONG == 64 - #define POCO_PTR_IS_64_BIT 1 - #define POCO_LONG_IS_64_BIT 1 - typedef signed long Int64; - typedef unsigned long UInt64; - #else - typedef signed long long Int64; - typedef unsigned long long UInt64; - #endif - #define POCO_HAVE_INT64 1 -#endif - - -} // namespace Poco - - -#endif // Foundation_Types_INCLUDED +// +// Types.h +// +// $Id: //poco/1.2/Foundation/include/Poco/Types.h#1 $ +// +// Library: Foundation +// Package: Core +// Module: Types +// +// Definitions of fixed-size integer types for various platforms +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_Types_INCLUDED +#define Foundation_Types_INCLUDED + + +#include "Poco/Foundation.h" + + +namespace Poco { + + +#if defined(_MSC_VER) + // + // Windows/Visual C++ + // + typedef signed char Int8; + typedef unsigned char UInt8; + typedef signed short Int16; + typedef unsigned short UInt16; + typedef signed int Int32; + typedef unsigned int UInt32; + typedef signed __int64 Int64; + typedef unsigned __int64 UInt64; + #if defined(_WIN64) + #define POCO_PTR_IS_64_BIT 1 + typedef signed __int64 IntPtr; + typedef unsigned __int64 UIntPtr; + #else + typedef signed long IntPtr; + typedef unsigned long UIntPtr; + #endif + #define POCO_HAVE_INT64 1 +#elif defined(__GNUC__) + // + // Unix/GCC + // + typedef signed char Int8; + typedef unsigned char UInt8; + typedef signed short Int16; + typedef unsigned short UInt16; + typedef signed int Int32; + typedef unsigned int UInt32; + typedef signed long IntPtr; + typedef unsigned long UIntPtr; + #if defined(__LP64__) + #define POCO_PTR_IS_64_BIT 1 + #define POCO_LONG_IS_64_BIT 1 + typedef signed long Int64; + typedef unsigned long UInt64; + #else + typedef signed long long Int64; + typedef unsigned long long UInt64; + #endif + #define POCO_HAVE_INT64 1 +#elif defined(__DECCXX) + // + // Compaq C++ + // + typedef signed char Int8; + typedef unsigned char UInt8; + typedef signed short Int16; + typedef unsigned short UInt16; + typedef signed int Int32; + typedef unsigned int UInt32; + typedef signed __int64 Int64; + typedef unsigned __int64 UInt64; + #if defined(__VMS) + #if defined(__32BITS) + typedef signed long IntPtr; + typedef unsigned long UIntPtr; + #else + typedef Int64 IntPtr; + typedef UInt64 UIntPtr; + #define POCO_PTR_IS_64_BIT 1 + #endif + #else + typedef signed long IntPtr; + typedef unsigned long UIntPtr; + #define POCO_PTR_IS_64_BIT 1 + #define POCO_LONG_IS_64_BIT 1 + #endif + #define POCO_HAVE_INT64 1 +#elif defined(__HP_aCC) + // + // HP Ansi C++ + // + typedef signed char Int8; + typedef unsigned char UInt8; + typedef signed short Int16; + typedef unsigned short UInt16; + typedef signed int Int32; + typedef unsigned int UInt32; + typedef signed long IntPtr; + typedef unsigned long UIntPtr; + #if defined(__LP64__) + #define POCO_PTR_IS_64_BIT 1 + #define POCO_LONG_IS_64_BIT 1 + typedef signed long Int64; + typedef unsigned long UInt64; + #else + typedef signed long long Int64; + typedef unsigned long long UInt64; + #endif + #define POCO_HAVE_INT64 1 +#elif defined(__SUNPRO_CC) + // + // SUN Forte C++ + // + typedef signed char Int8; + typedef unsigned char UInt8; + typedef signed short Int16; + typedef unsigned short UInt16; + typedef signed int Int32; + typedef unsigned int UInt32; + typedef signed long IntPtr; + typedef unsigned long UIntPtr; + #if defined(__sparcv9) + #define POCO_PTR_IS_64_BIT 1 + #define POCO_LONG_IS_64_BIT 1 + typedef signed long Int64; + typedef unsigned long UInt64; + #else + typedef signed long long Int64; + typedef unsigned long long UInt64; + #endif + #define POCO_HAVE_INT64 1 +#elif defined(__IBMCPP__) + // + // IBM XL C++ + // + typedef signed char Int8; + typedef unsigned char UInt8; + typedef signed short Int16; + typedef unsigned short UInt16; + typedef signed int Int32; + typedef unsigned int UInt32; + typedef signed long IntPtr; + typedef unsigned long UIntPtr; + #if defined(__64BIT__) + #define POCO_PTR_IS_64_BIT 1 + #define POCO_LONG_IS_64_BIT 1 + typedef signed long Int64; + typedef unsigned long UInt64; + #else + typedef signed long long Int64; + typedef unsigned long long UInt64; + #endif + #define POCO_HAVE_INT64 1 +#elif defined(__sgi) + // + // MIPSpro C++ + // + typedef signed char Int8; + typedef unsigned char UInt8; + typedef signed short Int16; + typedef unsigned short UInt16; + typedef signed int Int32; + typedef unsigned int UInt32; + typedef signed long IntPtr; + typedef unsigned long UIntPtr; + #if _MIPS_SZLONG == 64 + #define POCO_PTR_IS_64_BIT 1 + #define POCO_LONG_IS_64_BIT 1 + typedef signed long Int64; + typedef unsigned long UInt64; + #else + typedef signed long long Int64; + typedef unsigned long long UInt64; + #endif + #define POCO_HAVE_INT64 1 +#endif + + +} // namespace Poco + + +#endif // Foundation_Types_INCLUDED diff --git a/Foundation/include/Poco/URI.h b/Foundation/include/Poco/URI.h index 1590e8355..5036ba468 100644 --- a/Foundation/include/Poco/URI.h +++ b/Foundation/include/Poco/URI.h @@ -1,365 +1,365 @@ -// -// URI.h -// -// $Id: //poco/1.2/Foundation/include/Poco/URI.h#1 $ -// -// Library: Foundation -// Package: URI -// Module: URI -// -// Definition of the URI class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_URI_INCLUDED -#define Foundation_URI_INCLUDED - - -#include "Poco/Foundation.h" -#include - - -namespace Poco { - - -class Foundation_API URI - /// A Uniform Resource Identifier, as specified in RFC 3986. - /// - /// The URI class provides methods for building URIs from their - /// parts, as well as for splitting URIs into their parts. - /// Furthermore, the class provides methods for resolving - /// relative URIs against base URIs. - /// - /// The class automatically performs a few normalizations on - /// all URIs and URI parts passed to it: - /// * scheme identifiers are converted to lower case. - /// * percent-encoded characters are decoded - /// * optionally, dot segments are removed from paths (see normalize()) -{ -public: - URI(); - /// Creates an empty URI. - - explicit URI(const std::string& uri); - /// Parses an URI from the given string. Throws a - /// SyntaxException if the uri is not valid. - - explicit URI(const char* uri); - /// Parses an URI from the given string. Throws a - /// SyntaxException if the uri is not valid. - - URI(const std::string& scheme, const std::string& pathEtc); - /// Creates an URI from its parts. - - URI(const std::string& scheme, const std::string& authority, const std::string& pathEtc); - /// Creates an URI from its parts. - - URI(const std::string& scheme, const std::string& authority, const std::string& path, const std::string& query); - /// Creates an URI from its parts. - - URI(const std::string& scheme, const std::string& authority, const std::string& path, const std::string& query, const std::string& fragment); - /// Creates an URI from its parts. - - URI(const URI& uri); - /// Copy constructor. Creates an URI from another one. - - URI(const URI& baseURI, const std::string& relativeURI); - /// Creates an URI from a base URI and a relative URI, according to - /// the algorithm in section 5.2 of RFC 3986. - - ~URI(); - /// Destroys the URI. - - URI& operator = (const URI& uri); - /// Assignment operator. - - URI& operator = (const std::string& uri); - /// Parses and assigns an URI from the given string. Throws a - /// SyntaxException if the uri is not valid. - - URI& operator = (const char* uri); - /// Parses and assigns an URI from the given string. Throws a - /// SyntaxException if the uri is not valid. - - void swap(URI& uri); - /// Swaps the URI with another one. - - void clear(); - /// Clears all parts of the URI. - - std::string toString() const; - /// Returns a string representation of the URI. - /// - /// Characters in the path, query and fragment parts will be - /// percent-encoded as necessary. - - const std::string& getScheme() const; - /// Returns the scheme part of the URI. - - void setScheme(const std::string& scheme); - /// Sets the scheme part of the URI. The given scheme - /// is converted to lower-case. - /// - /// A list of registered URI schemes can be found - /// at . - - const std::string& getUserInfo() const; - /// Returns the user-info part of the URI. - - void setUserInfo(const std::string& userInfo); - /// Sets the user-info part of the URI. - - const std::string& getHost() const; - /// Returns the host part of the URI. - - void setHost(const std::string& host); - /// Sets the host part of the URI. - - unsigned short getPort() const; - /// Returns the port number part of the URI. - /// - /// If no port number (0) has been specified, the - /// well-known port number (e.g., 80 for http) for - /// the given scheme is returned if it is known. - /// Otherwise, 0 is returned. - - void setPort(unsigned short port); - /// Sets the port number part of the URI. - - std::string getAuthority() const; - /// Returns the authority part (userInfo, host and port) - /// of the URI. - /// - /// If the port number is a well-known port - /// number for the given scheme (e.g., 80 for http), it - /// is not included in the authority. - - void setAuthority(const std::string& authority); - /// Parses the given authority part for the URI and sets - /// the user-info, host, port components accordingly. - - const std::string& getPath() const; - /// Returns the path part of the URI. - - void setPath(const std::string& path); - /// Sets the path part of the URI. - - std::string getQuery() const; - /// Returns the query part of the URI. - - void setQuery(const std::string& query); - /// Sets the query part of the URI. - - const std::string& getRawQuery() const; - /// Returns the unencoded query part of the URI. - - void setRawQuery(const std::string& query); - /// Sets the query part of the URI. - - const std::string& getFragment() const; - /// Returns the fragment part of the URI. - - void setFragment(const std::string& fragment); - /// Sets the fragment part of the URI. - - void setPathEtc(const std::string& pathEtc); - /// Sets the path, query and fragment parts of the URI. - - std::string getPathEtc() const; - /// Returns the path, query and fragment parts of the URI. - - std::string getPathAndQuery() const; - /// Returns the path and query parts of the URI. - - void resolve(const std::string& relativeURI); - /// Resolves the given relative URI against the base URI. - /// See section 5.2 of RFC 3986 for the algorithm used. - - void resolve(const URI& relativeURI); - /// Resolves the given relative URI against the base URI. - /// See section 5.2 of RFC 3986 for the algorithm used. - - bool isRelative() const; - /// Returns true if the URI is a relative reference, false otherwise. - /// - /// A relative reference does not contain a scheme identifier. - /// Relative references are usually resolved against an absolute - /// base reference. - - bool empty() const; - /// Returns true if the URI is empty, false otherwise. - - bool operator == (const URI& uri) const; - /// Returns true if both URIs are identical, false otherwise. - /// - /// Two URIs are identical if their scheme, authority, - /// path, query and fragment part are identical. - - bool operator == (const std::string& uri) const; - /// Parses the given URI and returns true if both URIs are identical, - /// false otherwise. - - bool operator != (const URI& uri) const; - /// Returns true if both URIs are identical, false otherwise. - - bool operator != (const std::string& uri) const; - /// Parses the given URI and returns true if both URIs are identical, - /// false otherwise. - - void normalize(); - /// Normalizes the URI by removing all but leading . and .. segments from the path. - /// - /// If the first path segment in a relative path contains a colon (:), - /// such as in a Windows path containing a drive letter, a dot segment (./) - /// is prepended in accordance with section 3.3 of RFC 3986. - - void getPathSegments(std::vector& segments); - /// Places the single path segments (delimited by slashes) into the - /// given vector. - - static void encode(const std::string& str, const std::string& reserved, std::string& encodedStr); - /// URI-encodes the given string by escaping reserved and non-ASCII - /// characters. The encoded string is appended to encodedStr. - - static void decode(const std::string& str, std::string& decodedStr); - /// URI-decodes the given string by replacing percent-encoded - /// characters with the actual character. The decoded string - /// is appended to decodedStr. - -protected: - bool equals(const URI& uri) const; - /// Returns true if both uri's are equivalent. - - bool isWellKnownPort() const; - /// Returns true if the URI's port number is a well-known one - /// (for example, 80, if the scheme is http). - - unsigned short getWellKnownPort() const; - /// Returns the well-known port number for the URI's scheme, - /// or 0 if the port number is not known. - - void parse(const std::string& uri); - /// Parses and assigns an URI from the given string. Throws a - /// SyntaxException if the uri is not valid. - - void parseAuthority(std::string::const_iterator& it, const std::string::const_iterator& end); - /// Parses and sets the user-info, host and port from the given data. - - void parseHostAndPort(std::string::const_iterator& it, const std::string::const_iterator& end); - /// Parses and sets the host and port from the given data. - - void parsePath(std::string::const_iterator& it, const std::string::const_iterator& end); - /// Parses and sets the path from the given data. - - void parsePathEtc(std::string::const_iterator& it, const std::string::const_iterator& end); - /// Parses and sets the path, query and fragment from the given data. - - void parseQuery(std::string::const_iterator& it, const std::string::const_iterator& end); - /// Parses and sets the query from the given data. - - void parseFragment(std::string::const_iterator& it, const std::string::const_iterator& end); - /// Parses and sets the fragment from the given data. - - void mergePath(const std::string& path); - /// Appends a path to the URI's path. - - void removeDotSegments(bool removeLeading = true); - /// Removes all dot segments from the path. - - static void getPathSegments(const std::string& path, std::vector& segments); - /// Places the single path segments (delimited by slashes) into the - /// given vector. - - void buildPath(const std::vector& segments, bool leadingSlash, bool trailingSlash); - /// Builds the path from the given segments. - - static const std::string RESERVED_PATH; - static const std::string RESERVED_QUERY; - static const std::string RESERVED_FRAGMENT; - static const std::string ILLEGAL; - -private: - std::string _scheme; - std::string _userInfo; - std::string _host; - unsigned short _port; - std::string _path; - std::string _query; - std::string _fragment; -}; - - -// -// inlines -// -inline const std::string& URI::getScheme() const -{ - return _scheme; -} - - -inline const std::string& URI::getUserInfo() const -{ - return _userInfo; -} - - -inline const std::string& URI::getHost() const -{ - return _host; -} - - -inline const std::string& URI::getPath() const -{ - return _path; -} - - -inline const std::string& URI::getRawQuery() const -{ - return _query; -} - - -inline const std::string& URI::getFragment() const -{ - return _fragment; -} - - -inline void swap(URI& u1, URI& u2) -{ - u1.swap(u2); -} - - -} // namespace Poco - - -#endif // Foundation_URI_INCLUDED +// +// URI.h +// +// $Id: //poco/1.2/Foundation/include/Poco/URI.h#1 $ +// +// Library: Foundation +// Package: URI +// Module: URI +// +// Definition of the URI class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_URI_INCLUDED +#define Foundation_URI_INCLUDED + + +#include "Poco/Foundation.h" +#include + + +namespace Poco { + + +class Foundation_API URI + /// A Uniform Resource Identifier, as specified in RFC 3986. + /// + /// The URI class provides methods for building URIs from their + /// parts, as well as for splitting URIs into their parts. + /// Furthermore, the class provides methods for resolving + /// relative URIs against base URIs. + /// + /// The class automatically performs a few normalizations on + /// all URIs and URI parts passed to it: + /// * scheme identifiers are converted to lower case. + /// * percent-encoded characters are decoded + /// * optionally, dot segments are removed from paths (see normalize()) +{ +public: + URI(); + /// Creates an empty URI. + + explicit URI(const std::string& uri); + /// Parses an URI from the given string. Throws a + /// SyntaxException if the uri is not valid. + + explicit URI(const char* uri); + /// Parses an URI from the given string. Throws a + /// SyntaxException if the uri is not valid. + + URI(const std::string& scheme, const std::string& pathEtc); + /// Creates an URI from its parts. + + URI(const std::string& scheme, const std::string& authority, const std::string& pathEtc); + /// Creates an URI from its parts. + + URI(const std::string& scheme, const std::string& authority, const std::string& path, const std::string& query); + /// Creates an URI from its parts. + + URI(const std::string& scheme, const std::string& authority, const std::string& path, const std::string& query, const std::string& fragment); + /// Creates an URI from its parts. + + URI(const URI& uri); + /// Copy constructor. Creates an URI from another one. + + URI(const URI& baseURI, const std::string& relativeURI); + /// Creates an URI from a base URI and a relative URI, according to + /// the algorithm in section 5.2 of RFC 3986. + + ~URI(); + /// Destroys the URI. + + URI& operator = (const URI& uri); + /// Assignment operator. + + URI& operator = (const std::string& uri); + /// Parses and assigns an URI from the given string. Throws a + /// SyntaxException if the uri is not valid. + + URI& operator = (const char* uri); + /// Parses and assigns an URI from the given string. Throws a + /// SyntaxException if the uri is not valid. + + void swap(URI& uri); + /// Swaps the URI with another one. + + void clear(); + /// Clears all parts of the URI. + + std::string toString() const; + /// Returns a string representation of the URI. + /// + /// Characters in the path, query and fragment parts will be + /// percent-encoded as necessary. + + const std::string& getScheme() const; + /// Returns the scheme part of the URI. + + void setScheme(const std::string& scheme); + /// Sets the scheme part of the URI. The given scheme + /// is converted to lower-case. + /// + /// A list of registered URI schemes can be found + /// at . + + const std::string& getUserInfo() const; + /// Returns the user-info part of the URI. + + void setUserInfo(const std::string& userInfo); + /// Sets the user-info part of the URI. + + const std::string& getHost() const; + /// Returns the host part of the URI. + + void setHost(const std::string& host); + /// Sets the host part of the URI. + + unsigned short getPort() const; + /// Returns the port number part of the URI. + /// + /// If no port number (0) has been specified, the + /// well-known port number (e.g., 80 for http) for + /// the given scheme is returned if it is known. + /// Otherwise, 0 is returned. + + void setPort(unsigned short port); + /// Sets the port number part of the URI. + + std::string getAuthority() const; + /// Returns the authority part (userInfo, host and port) + /// of the URI. + /// + /// If the port number is a well-known port + /// number for the given scheme (e.g., 80 for http), it + /// is not included in the authority. + + void setAuthority(const std::string& authority); + /// Parses the given authority part for the URI and sets + /// the user-info, host, port components accordingly. + + const std::string& getPath() const; + /// Returns the path part of the URI. + + void setPath(const std::string& path); + /// Sets the path part of the URI. + + std::string getQuery() const; + /// Returns the query part of the URI. + + void setQuery(const std::string& query); + /// Sets the query part of the URI. + + const std::string& getRawQuery() const; + /// Returns the unencoded query part of the URI. + + void setRawQuery(const std::string& query); + /// Sets the query part of the URI. + + const std::string& getFragment() const; + /// Returns the fragment part of the URI. + + void setFragment(const std::string& fragment); + /// Sets the fragment part of the URI. + + void setPathEtc(const std::string& pathEtc); + /// Sets the path, query and fragment parts of the URI. + + std::string getPathEtc() const; + /// Returns the path, query and fragment parts of the URI. + + std::string getPathAndQuery() const; + /// Returns the path and query parts of the URI. + + void resolve(const std::string& relativeURI); + /// Resolves the given relative URI against the base URI. + /// See section 5.2 of RFC 3986 for the algorithm used. + + void resolve(const URI& relativeURI); + /// Resolves the given relative URI against the base URI. + /// See section 5.2 of RFC 3986 for the algorithm used. + + bool isRelative() const; + /// Returns true if the URI is a relative reference, false otherwise. + /// + /// A relative reference does not contain a scheme identifier. + /// Relative references are usually resolved against an absolute + /// base reference. + + bool empty() const; + /// Returns true if the URI is empty, false otherwise. + + bool operator == (const URI& uri) const; + /// Returns true if both URIs are identical, false otherwise. + /// + /// Two URIs are identical if their scheme, authority, + /// path, query and fragment part are identical. + + bool operator == (const std::string& uri) const; + /// Parses the given URI and returns true if both URIs are identical, + /// false otherwise. + + bool operator != (const URI& uri) const; + /// Returns true if both URIs are identical, false otherwise. + + bool operator != (const std::string& uri) const; + /// Parses the given URI and returns true if both URIs are identical, + /// false otherwise. + + void normalize(); + /// Normalizes the URI by removing all but leading . and .. segments from the path. + /// + /// If the first path segment in a relative path contains a colon (:), + /// such as in a Windows path containing a drive letter, a dot segment (./) + /// is prepended in accordance with section 3.3 of RFC 3986. + + void getPathSegments(std::vector& segments); + /// Places the single path segments (delimited by slashes) into the + /// given vector. + + static void encode(const std::string& str, const std::string& reserved, std::string& encodedStr); + /// URI-encodes the given string by escaping reserved and non-ASCII + /// characters. The encoded string is appended to encodedStr. + + static void decode(const std::string& str, std::string& decodedStr); + /// URI-decodes the given string by replacing percent-encoded + /// characters with the actual character. The decoded string + /// is appended to decodedStr. + +protected: + bool equals(const URI& uri) const; + /// Returns true if both uri's are equivalent. + + bool isWellKnownPort() const; + /// Returns true if the URI's port number is a well-known one + /// (for example, 80, if the scheme is http). + + unsigned short getWellKnownPort() const; + /// Returns the well-known port number for the URI's scheme, + /// or 0 if the port number is not known. + + void parse(const std::string& uri); + /// Parses and assigns an URI from the given string. Throws a + /// SyntaxException if the uri is not valid. + + void parseAuthority(std::string::const_iterator& it, const std::string::const_iterator& end); + /// Parses and sets the user-info, host and port from the given data. + + void parseHostAndPort(std::string::const_iterator& it, const std::string::const_iterator& end); + /// Parses and sets the host and port from the given data. + + void parsePath(std::string::const_iterator& it, const std::string::const_iterator& end); + /// Parses and sets the path from the given data. + + void parsePathEtc(std::string::const_iterator& it, const std::string::const_iterator& end); + /// Parses and sets the path, query and fragment from the given data. + + void parseQuery(std::string::const_iterator& it, const std::string::const_iterator& end); + /// Parses and sets the query from the given data. + + void parseFragment(std::string::const_iterator& it, const std::string::const_iterator& end); + /// Parses and sets the fragment from the given data. + + void mergePath(const std::string& path); + /// Appends a path to the URI's path. + + void removeDotSegments(bool removeLeading = true); + /// Removes all dot segments from the path. + + static void getPathSegments(const std::string& path, std::vector& segments); + /// Places the single path segments (delimited by slashes) into the + /// given vector. + + void buildPath(const std::vector& segments, bool leadingSlash, bool trailingSlash); + /// Builds the path from the given segments. + + static const std::string RESERVED_PATH; + static const std::string RESERVED_QUERY; + static const std::string RESERVED_FRAGMENT; + static const std::string ILLEGAL; + +private: + std::string _scheme; + std::string _userInfo; + std::string _host; + unsigned short _port; + std::string _path; + std::string _query; + std::string _fragment; +}; + + +// +// inlines +// +inline const std::string& URI::getScheme() const +{ + return _scheme; +} + + +inline const std::string& URI::getUserInfo() const +{ + return _userInfo; +} + + +inline const std::string& URI::getHost() const +{ + return _host; +} + + +inline const std::string& URI::getPath() const +{ + return _path; +} + + +inline const std::string& URI::getRawQuery() const +{ + return _query; +} + + +inline const std::string& URI::getFragment() const +{ + return _fragment; +} + + +inline void swap(URI& u1, URI& u2) +{ + u1.swap(u2); +} + + +} // namespace Poco + + +#endif // Foundation_URI_INCLUDED diff --git a/Foundation/include/Poco/URIStreamFactory.h b/Foundation/include/Poco/URIStreamFactory.h index 8085069f9..c31075b53 100644 --- a/Foundation/include/Poco/URIStreamFactory.h +++ b/Foundation/include/Poco/URIStreamFactory.h @@ -1,85 +1,85 @@ -// -// URIStreamFactory.h -// -// $Id: //poco/1.2/Foundation/include/Poco/URIStreamFactory.h#1 $ -// -// Library: Foundation -// Package: URI -// Module: URIStreamFactory -// -// Definition of the URIStreamFactory class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_URIStreamFactory_INCLUDED -#define Foundation_URIStreamFactory_INCLUDED - - -#include "Poco/Foundation.h" -#include - - -namespace Poco { - - -class URI; - - -class Foundation_API URIStreamFactory - /// This class defines the interface that all - /// URI stream factories must implement. - /// - /// Subclasses must implement the open() method. -{ -public: - URIStreamFactory(); - /// Creates the URIStreamFactory. - - virtual std::istream* open(const URI& uri) = 0; - /// Tries to create and open an input stream for the - /// resource specified by the given URI. - /// - /// If the stream cannot be opened for whatever reason, - /// an appropriate IOException must be thrown. - -protected: - virtual ~URIStreamFactory(); - /// Destroys the URIStreamFactory. - -private: - URIStreamFactory(const URIStreamFactory&); - URIStreamFactory& operator = (const URIStreamFactory&); - - friend class URIStreamOpener; -}; - - -} // namespace Poco - - -#endif // Foundation_URIStreamFactory_INCLUDED +// +// URIStreamFactory.h +// +// $Id: //poco/1.2/Foundation/include/Poco/URIStreamFactory.h#1 $ +// +// Library: Foundation +// Package: URI +// Module: URIStreamFactory +// +// Definition of the URIStreamFactory class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_URIStreamFactory_INCLUDED +#define Foundation_URIStreamFactory_INCLUDED + + +#include "Poco/Foundation.h" +#include + + +namespace Poco { + + +class URI; + + +class Foundation_API URIStreamFactory + /// This class defines the interface that all + /// URI stream factories must implement. + /// + /// Subclasses must implement the open() method. +{ +public: + URIStreamFactory(); + /// Creates the URIStreamFactory. + + virtual std::istream* open(const URI& uri) = 0; + /// Tries to create and open an input stream for the + /// resource specified by the given URI. + /// + /// If the stream cannot be opened for whatever reason, + /// an appropriate IOException must be thrown. + +protected: + virtual ~URIStreamFactory(); + /// Destroys the URIStreamFactory. + +private: + URIStreamFactory(const URIStreamFactory&); + URIStreamFactory& operator = (const URIStreamFactory&); + + friend class URIStreamOpener; +}; + + +} // namespace Poco + + +#endif // Foundation_URIStreamFactory_INCLUDED diff --git a/Foundation/include/Poco/URIStreamOpener.h b/Foundation/include/Poco/URIStreamOpener.h index fd8f26c2d..27563abfa 100644 --- a/Foundation/include/Poco/URIStreamOpener.h +++ b/Foundation/include/Poco/URIStreamOpener.h @@ -1,151 +1,151 @@ -// -// URIStreamOpener.h -// -// $Id: //poco/1.2/Foundation/include/Poco/URIStreamOpener.h#1 $ -// -// Library: Foundation -// Package: URI -// Module: URIStreamOpener -// -// Definition of the URIStreamOpener class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_URIStreamOpener_INCLUDED -#define Foundation_URIStreamOpener_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/Mutex.h" -#include -#include - - -namespace Poco { - - -class URI; -class URIStreamFactory; -class Path; - - -class Foundation_API URIStreamOpener - /// The URIStreamOpener class is used to create and open input streams - /// for resourced identified by Uniform Resource Identifiers. - /// - /// For every URI scheme used, a URIStreamFactory must be registered. - /// A FileStreamFactory is automatically registered for file URIs. -{ -public: - URIStreamOpener(); - /// Creates the URIStreamOpener and registers a FileStreamFactory - /// for file URIs. - - ~URIStreamOpener(); - /// Destroys the URIStreamOpener and deletes all registered - /// URI stream factories. - - std::istream* open(const URI& uri) const; - /// Tries to create and open an input stream for the resource specified - /// by the given uniform resource identifier. - /// - /// If no URIStreamFactory has been registered for the URI's - /// scheme, a UnknownURIScheme exception is thrown. - /// If the stream cannot be opened for any reason, an - /// IOException is thrown. - /// - /// The given URI must be a valid one. This excludes file system paths. - /// - /// Whoever calls the method is responsible for deleting - /// the returned stream. - - std::istream* open(const std::string& pathOrURI) const; - /// Tries to create and open an input stream for the resource specified - /// by the given path or uniform resource identifier. - /// - /// If the stream cannot be opened for any reason, an - /// Exception is thrown. - /// - /// The method first tries to interpret the given pathOrURI as an URI. - /// If this fails, the pathOrURI is treated as local filesystem path. - /// If this also fails, an exception is thrown. - /// - /// Whoever calls the method is responsible for deleting - /// the returned stream. - - std::istream* open(const std::string& basePathOrURI, const std::string& pathOrURI) const; - /// Tries to create and open an input stream for the resource specified - /// by the given path or uniform resource identifier. - /// - /// pathOrURI is resolved against basePathOrURI (see URI::resolve() and - /// Path::resolve() for more information). - /// - /// If the stream cannot be opened for any reason, an - /// Exception is thrown. - /// - /// Whoever calls the method is responsible for deleting - /// the returned stream. - - void registerStreamFactory(const std::string& scheme, URIStreamFactory* pFactory); - /// Registers a URIStreamFactory for the given scheme. If another factory - /// has already been registered for the scheme, an ExistsException is thrown. - /// - /// The URIStreamOpener takes ownership of the factory and deletes it when it is - /// no longer needed (in other words, when the URIStreamOpener is deleted). - - void unregisterStreamFactory(const std::string& scheme); - /// Unregisters and deletes the URIStreamFactory for the given scheme. - /// - /// Throws a NotFoundException if no URIStreamFactory has been registered - /// for the given scheme. - - bool supportsScheme(const std::string& scheme); - /// Returns true iff a URIStreamFactory for the given scheme - /// has been registered. - - static URIStreamOpener& defaultOpener(); - /// Returns a reference to the default URIStreamOpener. - -protected: - std::istream* openFile(const Path& path) const; - -private: - URIStreamOpener(const URIStreamOpener&); - URIStreamOpener& operator = (const URIStreamOpener&); - - typedef std::map FactoryMap; - - FactoryMap _map; - mutable FastMutex _mutex; -}; - - -} // namespace Poco - - -#endif // Foundation_URIStreamOpener_INCLUDED +// +// URIStreamOpener.h +// +// $Id: //poco/1.2/Foundation/include/Poco/URIStreamOpener.h#1 $ +// +// Library: Foundation +// Package: URI +// Module: URIStreamOpener +// +// Definition of the URIStreamOpener class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_URIStreamOpener_INCLUDED +#define Foundation_URIStreamOpener_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/Mutex.h" +#include +#include + + +namespace Poco { + + +class URI; +class URIStreamFactory; +class Path; + + +class Foundation_API URIStreamOpener + /// The URIStreamOpener class is used to create and open input streams + /// for resourced identified by Uniform Resource Identifiers. + /// + /// For every URI scheme used, a URIStreamFactory must be registered. + /// A FileStreamFactory is automatically registered for file URIs. +{ +public: + URIStreamOpener(); + /// Creates the URIStreamOpener and registers a FileStreamFactory + /// for file URIs. + + ~URIStreamOpener(); + /// Destroys the URIStreamOpener and deletes all registered + /// URI stream factories. + + std::istream* open(const URI& uri) const; + /// Tries to create and open an input stream for the resource specified + /// by the given uniform resource identifier. + /// + /// If no URIStreamFactory has been registered for the URI's + /// scheme, a UnknownURIScheme exception is thrown. + /// If the stream cannot be opened for any reason, an + /// IOException is thrown. + /// + /// The given URI must be a valid one. This excludes file system paths. + /// + /// Whoever calls the method is responsible for deleting + /// the returned stream. + + std::istream* open(const std::string& pathOrURI) const; + /// Tries to create and open an input stream for the resource specified + /// by the given path or uniform resource identifier. + /// + /// If the stream cannot be opened for any reason, an + /// Exception is thrown. + /// + /// The method first tries to interpret the given pathOrURI as an URI. + /// If this fails, the pathOrURI is treated as local filesystem path. + /// If this also fails, an exception is thrown. + /// + /// Whoever calls the method is responsible for deleting + /// the returned stream. + + std::istream* open(const std::string& basePathOrURI, const std::string& pathOrURI) const; + /// Tries to create and open an input stream for the resource specified + /// by the given path or uniform resource identifier. + /// + /// pathOrURI is resolved against basePathOrURI (see URI::resolve() and + /// Path::resolve() for more information). + /// + /// If the stream cannot be opened for any reason, an + /// Exception is thrown. + /// + /// Whoever calls the method is responsible for deleting + /// the returned stream. + + void registerStreamFactory(const std::string& scheme, URIStreamFactory* pFactory); + /// Registers a URIStreamFactory for the given scheme. If another factory + /// has already been registered for the scheme, an ExistsException is thrown. + /// + /// The URIStreamOpener takes ownership of the factory and deletes it when it is + /// no longer needed (in other words, when the URIStreamOpener is deleted). + + void unregisterStreamFactory(const std::string& scheme); + /// Unregisters and deletes the URIStreamFactory for the given scheme. + /// + /// Throws a NotFoundException if no URIStreamFactory has been registered + /// for the given scheme. + + bool supportsScheme(const std::string& scheme); + /// Returns true iff a URIStreamFactory for the given scheme + /// has been registered. + + static URIStreamOpener& defaultOpener(); + /// Returns a reference to the default URIStreamOpener. + +protected: + std::istream* openFile(const Path& path) const; + +private: + URIStreamOpener(const URIStreamOpener&); + URIStreamOpener& operator = (const URIStreamOpener&); + + typedef std::map FactoryMap; + + FactoryMap _map; + mutable FastMutex _mutex; +}; + + +} // namespace Poco + + +#endif // Foundation_URIStreamOpener_INCLUDED diff --git a/Foundation/include/Poco/UTF16Encoding.h b/Foundation/include/Poco/UTF16Encoding.h index 0a84c4a2d..5b5645abd 100644 --- a/Foundation/include/Poco/UTF16Encoding.h +++ b/Foundation/include/Poco/UTF16Encoding.h @@ -1,102 +1,102 @@ -// -// UTF16Encoding.h -// -// $Id: //poco/1.2/Foundation/include/Poco/UTF16Encoding.h#1 $ -// -// Library: Foundation -// Package: Text -// Module: UTF16Encoding -// -// Definition of the UTF16Encoding class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_UTF16Encoding_INCLUDED -#define Foundation_UTF16Encoding_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/TextEncoding.h" - - -namespace Poco { - - -class Foundation_API UTF16Encoding: public TextEncoding - /// UTF-16 text encoding, as defined in RFC 2781. - /// - /// When converting from UTF-16 to Unicode, surrogates are - /// reported as they are - in other words, surrogate pairs - /// are not combined into one Unicode character. - /// When converting from Unicode to UTF-16, however, characters - /// outside the 16-bit range are converted into a low and - /// high surrogate. -{ -public: - enum ByteOrderType - { - BIG_ENDIAN_BYTE_ORDER, - LITTLE_ENDIAN_BYTE_ORDER, - NATIVE_BYTE_ORDER - }; - - UTF16Encoding(ByteOrderType byteOrder = NATIVE_BYTE_ORDER); - /// Creates and initializes the encoding for the given byte order. - - UTF16Encoding(int byteOrderMark); - /// Creates and initializes the encoding for the byte-order - /// indicated by the given byte-order mark, which is the Unicode - /// character 0xFEFF. - - ~UTF16Encoding(); - - ByteOrderType getByteOrder() const; - /// Returns the byte-order currently in use. - - void setByteOrder(ByteOrderType byteOrder); - /// Sets the byte order. - - void setByteOrder(int byteOrderMark); - /// Sets the byte order according to the given - /// byte order mark, which is the Unicode - /// character 0xFEFF. - - const CharacterMap& characterMap() const; - int convert(const unsigned char* bytes) const; - int convert(int ch, unsigned char* bytes, int length) const; - -private: - bool _flipBytes; - static const CharacterMap _charMap; -}; - - -} // namespace Poco - - -#endif // Foundation_UTF16Encoding_INCLUDED +// +// UTF16Encoding.h +// +// $Id: //poco/1.2/Foundation/include/Poco/UTF16Encoding.h#1 $ +// +// Library: Foundation +// Package: Text +// Module: UTF16Encoding +// +// Definition of the UTF16Encoding class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_UTF16Encoding_INCLUDED +#define Foundation_UTF16Encoding_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/TextEncoding.h" + + +namespace Poco { + + +class Foundation_API UTF16Encoding: public TextEncoding + /// UTF-16 text encoding, as defined in RFC 2781. + /// + /// When converting from UTF-16 to Unicode, surrogates are + /// reported as they are - in other words, surrogate pairs + /// are not combined into one Unicode character. + /// When converting from Unicode to UTF-16, however, characters + /// outside the 16-bit range are converted into a low and + /// high surrogate. +{ +public: + enum ByteOrderType + { + BIG_ENDIAN_BYTE_ORDER, + LITTLE_ENDIAN_BYTE_ORDER, + NATIVE_BYTE_ORDER + }; + + UTF16Encoding(ByteOrderType byteOrder = NATIVE_BYTE_ORDER); + /// Creates and initializes the encoding for the given byte order. + + UTF16Encoding(int byteOrderMark); + /// Creates and initializes the encoding for the byte-order + /// indicated by the given byte-order mark, which is the Unicode + /// character 0xFEFF. + + ~UTF16Encoding(); + + ByteOrderType getByteOrder() const; + /// Returns the byte-order currently in use. + + void setByteOrder(ByteOrderType byteOrder); + /// Sets the byte order. + + void setByteOrder(int byteOrderMark); + /// Sets the byte order according to the given + /// byte order mark, which is the Unicode + /// character 0xFEFF. + + const CharacterMap& characterMap() const; + int convert(const unsigned char* bytes) const; + int convert(int ch, unsigned char* bytes, int length) const; + +private: + bool _flipBytes; + static const CharacterMap _charMap; +}; + + +} // namespace Poco + + +#endif // Foundation_UTF16Encoding_INCLUDED diff --git a/Foundation/include/Poco/UTF8Encoding.h b/Foundation/include/Poco/UTF8Encoding.h index ce516271f..9a6587f5f 100644 --- a/Foundation/include/Poco/UTF8Encoding.h +++ b/Foundation/include/Poco/UTF8Encoding.h @@ -1,68 +1,68 @@ -// -// UTF8Encoding.h -// -// $Id: //poco/1.2/Foundation/include/Poco/UTF8Encoding.h#1 $ -// -// Library: Foundation -// Package: Text -// Module: UTF8Encoding -// -// Definition of the UTF8Encoding class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_UTF8Encoding_INCLUDED -#define Foundation_UTF8Encoding_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/TextEncoding.h" - - -namespace Poco { - - -class Foundation_API UTF8Encoding: public TextEncoding - /// UTF-8 text encoding, as defined in RFC 2279. -{ -public: - UTF8Encoding(); - ~UTF8Encoding(); - const CharacterMap& characterMap() const; - int convert(const unsigned char* bytes) const; - int convert(int ch, unsigned char* bytes, int length) const; - -private: - static const CharacterMap _charMap; -}; - - -} // namespace Poco - - -#endif // Foundation_UTF8Encoding_INCLUDED +// +// UTF8Encoding.h +// +// $Id: //poco/1.2/Foundation/include/Poco/UTF8Encoding.h#1 $ +// +// Library: Foundation +// Package: Text +// Module: UTF8Encoding +// +// Definition of the UTF8Encoding class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_UTF8Encoding_INCLUDED +#define Foundation_UTF8Encoding_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/TextEncoding.h" + + +namespace Poco { + + +class Foundation_API UTF8Encoding: public TextEncoding + /// UTF-8 text encoding, as defined in RFC 2279. +{ +public: + UTF8Encoding(); + ~UTF8Encoding(); + const CharacterMap& characterMap() const; + int convert(const unsigned char* bytes) const; + int convert(int ch, unsigned char* bytes, int length) const; + +private: + static const CharacterMap _charMap; +}; + + +} // namespace Poco + + +#endif // Foundation_UTF8Encoding_INCLUDED diff --git a/Foundation/include/Poco/UUID.h b/Foundation/include/Poco/UUID.h index 29595ae1b..edb1102ca 100644 --- a/Foundation/include/Poco/UUID.h +++ b/Foundation/include/Poco/UUID.h @@ -1,233 +1,233 @@ -// -// UUID.h -// -// $Id: //poco/1.2/Foundation/include/Poco/UUID.h#1 $ -// -// Library: Foundation -// Package: UUID -// Module: UUID -// -// Definition of the UUID class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_UUID_INCLUDED -#define Foundation_UUID_INCLUDED - - -#include "Poco/Foundation.h" - - -namespace Poco { - - -class Foundation_API UUID - /// A UUID is an identifier that is unique across both space and time, - /// with respect to the space of all UUIDs. Since a UUID is a fixed - /// size and contains a time field, it is possible for values to - /// rollover (around A.D. 3400, depending on the specific algorithm - /// used). A UUID can be used for multiple purposes, from tagging - /// objects with an extremely short lifetime, to reliably identifying - /// very persistent objects across a network. - /// This class implements a Universal Unique Identifier, - /// as specified in Appendix A of the DCE 1.1 Remote Procedure - /// Call Specification (http://www.opengroup.org/onlinepubs/9629399/), - /// RFC 2518 (WebDAV), section 6.4.1 and the UUIDs and GUIDs internet - /// draft by Leach/Salz from February, 1998 - /// (http://ftp.ics.uci.edu/pub/ietf/webdav/uuid-guid/draft-leach-uuids-guids-01.txt) - /// and also - /// http://www.ietf.org/internet-drafts/draft-mealling-uuid-urn-03.txt -{ -public: - enum Version - { - UUID_TIME_BASED = 0x01, - UUID_DCE_UID = 0x02, - UUID_NAME_BASED = 0x03, - UUID_RANDOM = 0x04 - }; - - UUID(); - /// Creates a nil (all zero) UUID. - - UUID(const UUID& uuid); - /// Copy constructor. - - explicit UUID(const std::string& uuid); - /// Parses the UUID from a string. - - explicit UUID(const char* uuid); - /// Parses the UUID from a string. - - ~UUID(); - /// Destroys the UUID. - - UUID& operator = (const UUID& uuid); - /// Assignment operator. - - void swap(UUID& uuid); - /// Swaps the UUID with another one. - - void parse(const std::string& uuid); - /// Parses the UUID from its string representation. - - std::string toString() const; - /// Returns a string representation of the UUID consisting - /// of groups of hexadecimal digits separated by hyphens. - - void copyFrom(const char* buffer); - /// Copies the UUID (16 bytes) from a buffer or byte array. - /// The UUID fields are expected to be - /// stored in network byte order. - /// The buffer need not be aligned. - - void copyTo(char* buffer) const; - /// Copies the UUID to the buffer. The fields - /// are in network byte order. - /// The buffer need not be aligned. - /// There must have room for at least 16 bytes. - - Version version() const; - /// Returns the version of the UUID. - - int variant() const; - /// Returns the variant number of the UUID: - /// - 0 reserved for NCS backward compatibility - /// - 2 the Leach-Salz variant (used by this class) - /// - 6 reserved, Microsoft Corporation backward compatibility - /// - 7 reserved for future definition - - bool operator == (const UUID& uuid) const; - bool operator != (const UUID& uuid) const; - bool operator < (const UUID& uuid) const; - bool operator <= (const UUID& uuid) const; - bool operator > (const UUID& uuid) const; - bool operator >= (const UUID& uuid) const; - - bool isNil() const; - /// Returns true iff the UUID is nil (in other words, - /// consists of all zeros). - - static const UUID& nil(); - /// Returns a nil UUID. - - static const UUID& dns(); - /// Returns the namespace identifier for the DNS namespace. - - static const UUID& uri(); - /// Returns the namespace identifier for the URI (former URL) namespace. - - static const UUID& oid(); - /// Returns the namespace identifier for the OID namespace. - - static const UUID& x500(); - /// Returns the namespace identifier for the X500 namespace. - -protected: - UUID(UInt32 timeLow, UInt32 timeMid, UInt32 timeHiAndVersion, UInt16 clockSeq, UInt8 node[]); - UUID(const char* bytes, Version version); - int compare(const UUID& uuid) const; - static void appendHex(std::string& str, UInt8 n); - static void appendHex(std::string& str, UInt16 n); - static void appendHex(std::string& str, UInt32 n); - static int nibble(char hex); - void fromNetwork(); - void toNetwork(); - -private: - UInt32 _timeLow; - UInt16 _timeMid; - UInt16 _timeHiAndVersion; - UInt16 _clockSeq; - UInt8 _node[6]; - - friend class UUIDGenerator; -}; - - -// -// inlines -// -inline bool UUID::operator == (const UUID& uuid) const -{ - return compare(uuid) == 0; -} - - -inline bool UUID::operator != (const UUID& uuid) const -{ - return compare(uuid) != 0; -} - - -inline bool UUID::operator < (const UUID& uuid) const -{ - return compare(uuid) < 0; -} - - -inline bool UUID::operator <= (const UUID& uuid) const -{ - return compare(uuid) <= 0; -} - - -inline bool UUID::operator > (const UUID& uuid) const -{ - return compare(uuid) > 0; -} - - -inline bool UUID::operator >= (const UUID& uuid) const -{ - return compare(uuid) >= 0; -} - - -inline UUID::Version UUID::version() const -{ - return Version(_timeHiAndVersion >> 12); -} - - -inline bool UUID::isNil() const -{ - return compare(nil()) == 0; -} - - -inline void swap(UUID& u1, UUID& u2) -{ - u1.swap(u2); -} - - -} // namespace Poco - - -#endif // Foundation_UUID_INCLUDED +// +// UUID.h +// +// $Id: //poco/1.2/Foundation/include/Poco/UUID.h#1 $ +// +// Library: Foundation +// Package: UUID +// Module: UUID +// +// Definition of the UUID class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_UUID_INCLUDED +#define Foundation_UUID_INCLUDED + + +#include "Poco/Foundation.h" + + +namespace Poco { + + +class Foundation_API UUID + /// A UUID is an identifier that is unique across both space and time, + /// with respect to the space of all UUIDs. Since a UUID is a fixed + /// size and contains a time field, it is possible for values to + /// rollover (around A.D. 3400, depending on the specific algorithm + /// used). A UUID can be used for multiple purposes, from tagging + /// objects with an extremely short lifetime, to reliably identifying + /// very persistent objects across a network. + /// This class implements a Universal Unique Identifier, + /// as specified in Appendix A of the DCE 1.1 Remote Procedure + /// Call Specification (http://www.opengroup.org/onlinepubs/9629399/), + /// RFC 2518 (WebDAV), section 6.4.1 and the UUIDs and GUIDs internet + /// draft by Leach/Salz from February, 1998 + /// (http://ftp.ics.uci.edu/pub/ietf/webdav/uuid-guid/draft-leach-uuids-guids-01.txt) + /// and also + /// http://www.ietf.org/internet-drafts/draft-mealling-uuid-urn-03.txt +{ +public: + enum Version + { + UUID_TIME_BASED = 0x01, + UUID_DCE_UID = 0x02, + UUID_NAME_BASED = 0x03, + UUID_RANDOM = 0x04 + }; + + UUID(); + /// Creates a nil (all zero) UUID. + + UUID(const UUID& uuid); + /// Copy constructor. + + explicit UUID(const std::string& uuid); + /// Parses the UUID from a string. + + explicit UUID(const char* uuid); + /// Parses the UUID from a string. + + ~UUID(); + /// Destroys the UUID. + + UUID& operator = (const UUID& uuid); + /// Assignment operator. + + void swap(UUID& uuid); + /// Swaps the UUID with another one. + + void parse(const std::string& uuid); + /// Parses the UUID from its string representation. + + std::string toString() const; + /// Returns a string representation of the UUID consisting + /// of groups of hexadecimal digits separated by hyphens. + + void copyFrom(const char* buffer); + /// Copies the UUID (16 bytes) from a buffer or byte array. + /// The UUID fields are expected to be + /// stored in network byte order. + /// The buffer need not be aligned. + + void copyTo(char* buffer) const; + /// Copies the UUID to the buffer. The fields + /// are in network byte order. + /// The buffer need not be aligned. + /// There must have room for at least 16 bytes. + + Version version() const; + /// Returns the version of the UUID. + + int variant() const; + /// Returns the variant number of the UUID: + /// - 0 reserved for NCS backward compatibility + /// - 2 the Leach-Salz variant (used by this class) + /// - 6 reserved, Microsoft Corporation backward compatibility + /// - 7 reserved for future definition + + bool operator == (const UUID& uuid) const; + bool operator != (const UUID& uuid) const; + bool operator < (const UUID& uuid) const; + bool operator <= (const UUID& uuid) const; + bool operator > (const UUID& uuid) const; + bool operator >= (const UUID& uuid) const; + + bool isNil() const; + /// Returns true iff the UUID is nil (in other words, + /// consists of all zeros). + + static const UUID& nil(); + /// Returns a nil UUID. + + static const UUID& dns(); + /// Returns the namespace identifier for the DNS namespace. + + static const UUID& uri(); + /// Returns the namespace identifier for the URI (former URL) namespace. + + static const UUID& oid(); + /// Returns the namespace identifier for the OID namespace. + + static const UUID& x500(); + /// Returns the namespace identifier for the X500 namespace. + +protected: + UUID(UInt32 timeLow, UInt32 timeMid, UInt32 timeHiAndVersion, UInt16 clockSeq, UInt8 node[]); + UUID(const char* bytes, Version version); + int compare(const UUID& uuid) const; + static void appendHex(std::string& str, UInt8 n); + static void appendHex(std::string& str, UInt16 n); + static void appendHex(std::string& str, UInt32 n); + static int nibble(char hex); + void fromNetwork(); + void toNetwork(); + +private: + UInt32 _timeLow; + UInt16 _timeMid; + UInt16 _timeHiAndVersion; + UInt16 _clockSeq; + UInt8 _node[6]; + + friend class UUIDGenerator; +}; + + +// +// inlines +// +inline bool UUID::operator == (const UUID& uuid) const +{ + return compare(uuid) == 0; +} + + +inline bool UUID::operator != (const UUID& uuid) const +{ + return compare(uuid) != 0; +} + + +inline bool UUID::operator < (const UUID& uuid) const +{ + return compare(uuid) < 0; +} + + +inline bool UUID::operator <= (const UUID& uuid) const +{ + return compare(uuid) <= 0; +} + + +inline bool UUID::operator > (const UUID& uuid) const +{ + return compare(uuid) > 0; +} + + +inline bool UUID::operator >= (const UUID& uuid) const +{ + return compare(uuid) >= 0; +} + + +inline UUID::Version UUID::version() const +{ + return Version(_timeHiAndVersion >> 12); +} + + +inline bool UUID::isNil() const +{ + return compare(nil()) == 0; +} + + +inline void swap(UUID& u1, UUID& u2) +{ + u1.swap(u2); +} + + +} // namespace Poco + + +#endif // Foundation_UUID_INCLUDED diff --git a/Foundation/include/Poco/UUIDGenerator.h b/Foundation/include/Poco/UUIDGenerator.h index 4120fc4e0..eaffbf41f 100644 --- a/Foundation/include/Poco/UUIDGenerator.h +++ b/Foundation/include/Poco/UUIDGenerator.h @@ -1,118 +1,118 @@ -// -// UUIDGenerator.h -// -// $Id: //poco/1.2/Foundation/include/Poco/UUIDGenerator.h#1 $ -// -// Library: Foundation -// Package: UUID -// Module: UUID -// -// Definition of the UUIDGenerator class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_UUIDGenerator_INCLUDED -#define Foundation_UUIDGenerator_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/UUID.h" -#include "Poco/Mutex.h" -#include "Poco/Random.h" -#include "Poco/Timestamp.h" - - -namespace Poco { - - -class DigestEngine; - - -class Foundation_API UUIDGenerator - /// This class implements a generator for Universal Unique Identifiers, - /// as specified in Appendix A of the DCE 1.1 Remote Procedure - /// Call Specification (http://www.opengroup.org/onlinepubs/9629399/), - /// RFC 2518 (WebDAV), section 6.4.1 and the UUIDs and GUIDs internet - /// draft by Leach/Salz from February, 1998 - /// (http://ftp.ics.uci.edu/pub/ietf/webdav/uuid-guid/draft-leach-uuids-guids-01.txt) -{ -public: - UUIDGenerator(); - /// Creates the UUIDGenerator. - - ~UUIDGenerator(); - /// Destroys the UUIDGenerator. - - UUID create(); - /// Creates a new time-based UUID, using the MAC address of - /// one of the system's ethernet adapters. - /// - /// Throws a SystemException if no MAC address can be - /// obtained. - - UUID createFromName(const UUID& nsid, const std::string& name); - /// Creates a name-based UUID. - - UUID createFromName(const UUID& nsid, const std::string& name, DigestEngine& de); - /// Creates a name-based UUID, using the given digest engine. - - UUID createRandom(); - /// Creates a random UUID. - - UUID createOne(); - /// Tries to create and return a time-based UUID (see createSecure()), and, - /// if that does not work due to the unavailability of a MAC address, - /// creates and returns a random UUID. - /// - /// The UUID::version() method can be used to determine the actual kind of - /// the UUID generated. - - static UUIDGenerator& defaultGenerator(); - /// Returns a reference to the default UUIDGenerator. - -protected: - Timestamp::UtcTimeVal timeStamp(); - void getNode(); - -private: - FastMutex _mutex; - Random _random; - Timestamp _lastTime; - int _ticks; - UInt8 _node[6]; - bool _haveNode; - - UUIDGenerator(const UUIDGenerator&); - UUIDGenerator& operator = (const UUIDGenerator&); -}; - - -} // namespace Poco - - -#endif // Foundation_UUIDGenerator_INCLUDED +// +// UUIDGenerator.h +// +// $Id: //poco/1.2/Foundation/include/Poco/UUIDGenerator.h#1 $ +// +// Library: Foundation +// Package: UUID +// Module: UUID +// +// Definition of the UUIDGenerator class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_UUIDGenerator_INCLUDED +#define Foundation_UUIDGenerator_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/UUID.h" +#include "Poco/Mutex.h" +#include "Poco/Random.h" +#include "Poco/Timestamp.h" + + +namespace Poco { + + +class DigestEngine; + + +class Foundation_API UUIDGenerator + /// This class implements a generator for Universal Unique Identifiers, + /// as specified in Appendix A of the DCE 1.1 Remote Procedure + /// Call Specification (http://www.opengroup.org/onlinepubs/9629399/), + /// RFC 2518 (WebDAV), section 6.4.1 and the UUIDs and GUIDs internet + /// draft by Leach/Salz from February, 1998 + /// (http://ftp.ics.uci.edu/pub/ietf/webdav/uuid-guid/draft-leach-uuids-guids-01.txt) +{ +public: + UUIDGenerator(); + /// Creates the UUIDGenerator. + + ~UUIDGenerator(); + /// Destroys the UUIDGenerator. + + UUID create(); + /// Creates a new time-based UUID, using the MAC address of + /// one of the system's ethernet adapters. + /// + /// Throws a SystemException if no MAC address can be + /// obtained. + + UUID createFromName(const UUID& nsid, const std::string& name); + /// Creates a name-based UUID. + + UUID createFromName(const UUID& nsid, const std::string& name, DigestEngine& de); + /// Creates a name-based UUID, using the given digest engine. + + UUID createRandom(); + /// Creates a random UUID. + + UUID createOne(); + /// Tries to create and return a time-based UUID (see createSecure()), and, + /// if that does not work due to the unavailability of a MAC address, + /// creates and returns a random UUID. + /// + /// The UUID::version() method can be used to determine the actual kind of + /// the UUID generated. + + static UUIDGenerator& defaultGenerator(); + /// Returns a reference to the default UUIDGenerator. + +protected: + Timestamp::UtcTimeVal timeStamp(); + void getNode(); + +private: + FastMutex _mutex; + Random _random; + Timestamp _lastTime; + int _ticks; + UInt8 _node[6]; + bool _haveNode; + + UUIDGenerator(const UUIDGenerator&); + UUIDGenerator& operator = (const UUIDGenerator&); +}; + + +} // namespace Poco + + +#endif // Foundation_UUIDGenerator_INCLUDED diff --git a/Foundation/include/Poco/UnbufferedStreamBuf.h b/Foundation/include/Poco/UnbufferedStreamBuf.h index 276dcfd3d..64f62d5e4 100644 --- a/Foundation/include/Poco/UnbufferedStreamBuf.h +++ b/Foundation/include/Poco/UnbufferedStreamBuf.h @@ -1,191 +1,191 @@ -// -// UnufferedStreamBuf.h -// -// $Id: //poco/1.2/Foundation/include/Poco/UnbufferedStreamBuf.h#1 $ -// -// Library: Foundation -// Package: Streams -// Module: StreamBuf -// -// Definition of template BasicUnbufferedStreamBuf and class UnbufferedStreamBuf. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_UnbufferedStreamBuf_INCLUDED -#define Foundation_UnbufferedStreamBuf_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/StreamUtil.h" -#include -#include -#include - - -namespace Poco { - - -template -class BasicUnbufferedStreamBuf: public std::basic_streambuf - /// This is an implementation of an unbuffered streambuf - /// that greatly simplifies the implementation of - /// custom streambufs of various kinds. - /// Derived classes only have to override the methods - /// readFromDevice() or writeToDevice(). -{ -protected: - typedef std::basic_streambuf Base; - typedef std::basic_ios IOS; - typedef ch char_type; - typedef tr char_traits; - typedef typename Base::int_type int_type; - typedef typename Base::pos_type pos_type; - typedef typename Base::off_type off_type; - typedef typename IOS::openmode openmode; - -public: - BasicUnbufferedStreamBuf(): - _pb(char_traits::eof()), - _ispb(false) - { - this->setg(0, 0, 0); - this->setp(0, 0); - } - - ~BasicUnbufferedStreamBuf() - { - } - - virtual int_type overflow(int_type c) - { - if (c != char_traits::eof()) - return writeToDevice(char_traits::to_char_type(c)); - else - return c; - } - - virtual int_type underflow() - { - if (_ispb) - { - return _pb; - } - else - { - int_type c = readFromDevice(); - if (c != char_traits::eof()) - { - _ispb = true; - _pb = c; - } - return c; - } - } - - virtual int_type uflow() - { - if (_ispb) - { - _ispb = false; - return _pb; - } - else - { - int_type c = readFromDevice(); - if (c != char_traits::eof()) - { - _pb = c; - } - return c; - } - } - - virtual int_type pbackfail(int_type c) - { - if (_ispb) - { - return char_traits::eof(); - } - else - { - _ispb = true; - _pb = c; - return c; - } - } - - virtual std::streamsize xsgetn(char_type* p, std::streamsize count) - /// Some platforms (for example, Compaq C++) have buggy implementations of - /// xsgetn that handle null buffers incorrectly. - /// Anyway, it does not hurt to provide an optimized implementation - /// of xsgetn for this streambuf implementation. - { - std::streamsize copied = 0; - while (count > 0) - { - int_type c = uflow(); - if (c == char_traits::eof()) break; - *p++ = char_traits::to_char_type(c); - ++copied; - --count; - } - return copied; - } - -protected: - static int_type charToInt(char_type c) - { - return char_traits::to_int_type(c); - } - -private: - virtual int_type readFromDevice() - { - return char_traits::eof(); - } - - virtual int_type writeToDevice(char_type c) - { - return char_traits::eof(); - } - - int_type _pb; - bool _ispb; -}; - - -// -// We provide an instantiation for char -// -typedef BasicUnbufferedStreamBuf > UnbufferedStreamBuf; - - -} // namespace Poco - - -#endif // Foundation_UnbufferedStreamBuf_INCLUDED +// +// UnufferedStreamBuf.h +// +// $Id: //poco/1.2/Foundation/include/Poco/UnbufferedStreamBuf.h#1 $ +// +// Library: Foundation +// Package: Streams +// Module: StreamBuf +// +// Definition of template BasicUnbufferedStreamBuf and class UnbufferedStreamBuf. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_UnbufferedStreamBuf_INCLUDED +#define Foundation_UnbufferedStreamBuf_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/StreamUtil.h" +#include +#include +#include + + +namespace Poco { + + +template +class BasicUnbufferedStreamBuf: public std::basic_streambuf + /// This is an implementation of an unbuffered streambuf + /// that greatly simplifies the implementation of + /// custom streambufs of various kinds. + /// Derived classes only have to override the methods + /// readFromDevice() or writeToDevice(). +{ +protected: + typedef std::basic_streambuf Base; + typedef std::basic_ios IOS; + typedef ch char_type; + typedef tr char_traits; + typedef typename Base::int_type int_type; + typedef typename Base::pos_type pos_type; + typedef typename Base::off_type off_type; + typedef typename IOS::openmode openmode; + +public: + BasicUnbufferedStreamBuf(): + _pb(char_traits::eof()), + _ispb(false) + { + this->setg(0, 0, 0); + this->setp(0, 0); + } + + ~BasicUnbufferedStreamBuf() + { + } + + virtual int_type overflow(int_type c) + { + if (c != char_traits::eof()) + return writeToDevice(char_traits::to_char_type(c)); + else + return c; + } + + virtual int_type underflow() + { + if (_ispb) + { + return _pb; + } + else + { + int_type c = readFromDevice(); + if (c != char_traits::eof()) + { + _ispb = true; + _pb = c; + } + return c; + } + } + + virtual int_type uflow() + { + if (_ispb) + { + _ispb = false; + return _pb; + } + else + { + int_type c = readFromDevice(); + if (c != char_traits::eof()) + { + _pb = c; + } + return c; + } + } + + virtual int_type pbackfail(int_type c) + { + if (_ispb) + { + return char_traits::eof(); + } + else + { + _ispb = true; + _pb = c; + return c; + } + } + + virtual std::streamsize xsgetn(char_type* p, std::streamsize count) + /// Some platforms (for example, Compaq C++) have buggy implementations of + /// xsgetn that handle null buffers incorrectly. + /// Anyway, it does not hurt to provide an optimized implementation + /// of xsgetn for this streambuf implementation. + { + std::streamsize copied = 0; + while (count > 0) + { + int_type c = uflow(); + if (c == char_traits::eof()) break; + *p++ = char_traits::to_char_type(c); + ++copied; + --count; + } + return copied; + } + +protected: + static int_type charToInt(char_type c) + { + return char_traits::to_int_type(c); + } + +private: + virtual int_type readFromDevice() + { + return char_traits::eof(); + } + + virtual int_type writeToDevice(char_type c) + { + return char_traits::eof(); + } + + int_type _pb; + bool _ispb; +}; + + +// +// We provide an instantiation for char +// +typedef BasicUnbufferedStreamBuf > UnbufferedStreamBuf; + + +} // namespace Poco + + +#endif // Foundation_UnbufferedStreamBuf_INCLUDED diff --git a/Foundation/include/Poco/UnicodeConverter.h b/Foundation/include/Poco/UnicodeConverter.h index 71110d645..72280f389 100644 --- a/Foundation/include/Poco/UnicodeConverter.h +++ b/Foundation/include/Poco/UnicodeConverter.h @@ -1,81 +1,81 @@ -// -// UnicodeConverter.h -// -// $Id: //poco/1.2/Foundation/include/Poco/UnicodeConverter.h#1 $ -// -// Library: Foundation -// Package: Text -// Module: UnicodeConverter -// -// Definition of the UnicodeConverter class. -// -// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_UnicodeConverter_INCLUDED -#define Foundation_UnicodeConverter_INCLUDED - - -#include "Poco/Foundation.h" - - -namespace Poco { - - -class Foundation_API UnicodeConverter - /// A convenience class that converts strings from - /// UTF-8 encoded std::strings to UTF-16 encoded std::wstrings - /// and vice-versa. - /// - /// This class is mainly used for working with the Unicode Windows APIs - /// and probably won't be of much use anywhere else. -{ -public: - static void toUTF16(const std::string& utf8String, std::wstring& utf16String); - /// Converts the given UTF-8 encoded string into an UTF-16 encoded wstring. - - static void toUTF16(const char* utf8String, int length, std::wstring& utf16String); - /// Converts the given UTF-8 encoded character sequence into an UTF-16 encoded string. - - static void toUTF16(const char* utf8String, std::wstring& utf16String); - /// Converts the given zero-terminated UTF-8 encoded character sequence into an UTF-16 encoded wstring. - - static void toUTF8(const std::wstring& utf16String, std::string& utf8String); - /// Converts the given UTF-16 encoded wstring into an UTF-8 encoded string. - - static void toUTF8(const wchar_t* utf16String, int length, std::string& utf8String); - /// Converts the given zero-terminated UTF-16 encoded wide character sequence into an UTF-8 encoded wstring. - - static void toUTF8(const wchar_t* utf16String, std::string& utf8String); - /// Converts the given UTF-16 encoded zero terminated character sequence into an UTF-8 encoded string. -}; - - -} // namespace Poco - - -#endif // Foundation_UnicodeConverter_INCLUDED +// +// UnicodeConverter.h +// +// $Id: //poco/1.2/Foundation/include/Poco/UnicodeConverter.h#1 $ +// +// Library: Foundation +// Package: Text +// Module: UnicodeConverter +// +// Definition of the UnicodeConverter class. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_UnicodeConverter_INCLUDED +#define Foundation_UnicodeConverter_INCLUDED + + +#include "Poco/Foundation.h" + + +namespace Poco { + + +class Foundation_API UnicodeConverter + /// A convenience class that converts strings from + /// UTF-8 encoded std::strings to UTF-16 encoded std::wstrings + /// and vice-versa. + /// + /// This class is mainly used for working with the Unicode Windows APIs + /// and probably won't be of much use anywhere else. +{ +public: + static void toUTF16(const std::string& utf8String, std::wstring& utf16String); + /// Converts the given UTF-8 encoded string into an UTF-16 encoded wstring. + + static void toUTF16(const char* utf8String, int length, std::wstring& utf16String); + /// Converts the given UTF-8 encoded character sequence into an UTF-16 encoded string. + + static void toUTF16(const char* utf8String, std::wstring& utf16String); + /// Converts the given zero-terminated UTF-8 encoded character sequence into an UTF-16 encoded wstring. + + static void toUTF8(const std::wstring& utf16String, std::string& utf8String); + /// Converts the given UTF-16 encoded wstring into an UTF-8 encoded string. + + static void toUTF8(const wchar_t* utf16String, int length, std::string& utf8String); + /// Converts the given zero-terminated UTF-16 encoded wide character sequence into an UTF-8 encoded wstring. + + static void toUTF8(const wchar_t* utf16String, std::string& utf8String); + /// Converts the given UTF-16 encoded zero terminated character sequence into an UTF-8 encoded string. +}; + + +} // namespace Poco + + +#endif // Foundation_UnicodeConverter_INCLUDED diff --git a/Foundation/include/Poco/ValidArgs.h b/Foundation/include/Poco/ValidArgs.h index 833a9811e..915d09a56 100644 --- a/Foundation/include/Poco/ValidArgs.h +++ b/Foundation/include/Poco/ValidArgs.h @@ -1,96 +1,96 @@ -// -// ValidArgs.h -// -// $Id: //poco/1.2/Foundation/include/Poco/ValidArgs.h#2 $ -// -// Library: Foundation -// Package: Cache -// Module: ValidArgs -// -// Definition of the ValidArgs class. -// -// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_ValidArgs_INCLUDED -#define Foundation_ValidArgs_INCLUDED - - -#include "Poco/Foundation.h" - - -namespace Poco { - - -template -class ValidArgs -{ -public: - ValidArgs(const TKey& key): - _key(key), - _isValid(true) - { - } - - ValidArgs(const ValidArgs& args): - _key(args._key), - _isValid(args._isValid) - { - } - - ~ValidArgs() - { - } - - const TKey& key() const - { - return _key; - } - - bool isValid() const - { - return _isValid; - } - - void invalidate() - { - _isValid = false; - } - -protected: - const TKey& _key; - bool _isValid; - -private: - ValidArgs& operator = (const ValidArgs& args); -}; - - -} // namespace Poco - - -#endif +// +// ValidArgs.h +// +// $Id: //poco/1.2/Foundation/include/Poco/ValidArgs.h#2 $ +// +// Library: Foundation +// Package: Cache +// Module: ValidArgs +// +// Definition of the ValidArgs class. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_ValidArgs_INCLUDED +#define Foundation_ValidArgs_INCLUDED + + +#include "Poco/Foundation.h" + + +namespace Poco { + + +template +class ValidArgs +{ +public: + ValidArgs(const TKey& key): + _key(key), + _isValid(true) + { + } + + ValidArgs(const ValidArgs& args): + _key(args._key), + _isValid(args._isValid) + { + } + + ~ValidArgs() + { + } + + const TKey& key() const + { + return _key; + } + + bool isValid() const + { + return _isValid; + } + + void invalidate() + { + _isValid = false; + } + +protected: + const TKey& _key; + bool _isValid; + +private: + ValidArgs& operator = (const ValidArgs& args); +}; + + +} // namespace Poco + + +#endif diff --git a/Foundation/include/Poco/Void.h b/Foundation/include/Poco/Void.h index 7a01a0eaa..9e638b00c 100644 --- a/Foundation/include/Poco/Void.h +++ b/Foundation/include/Poco/Void.h @@ -1,90 +1,90 @@ -// -// Void.h -// -// $Id: //poco/1.2/Foundation/include/Poco/Void.h#1 $ -// -// Library: Foundation -// Package: Core -// Module: Void -// -// Definition of the Void class. -// -// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. -// 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. -// -// 3. Redistributions in any form must be accompanied by information on -// how to obtain complete source code for this software and any -// accompanying software that uses this software. The source code -// must either be included in the distribution or be available for no -// more than the cost of distribution plus a nominal fee, and must be -// freely redistributable under reasonable conditions. For an -// executable file, complete source code means the source code for all -// modules it contains. It does not include source code for modules or -// files that typically accompany the major components of the operating -// system on which the executable file runs. -// -// 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 Foundation_Void_INCLUDED -#define Foundation_Void_INCLUDED - - -#include "Poco/Foundation.h" - - -namespace Poco { - - -class Foundation_API Void - /// A dummy class with value-type semantics, - /// mostly useful as a template argument. - /// - /// This class is typically used together with ActiveMethod, - /// if no argument or return value is needed. -{ -public: - Void(); - /// Creates the Void. - - Void(const Void& v); - /// Creates the Void from another Void. - /// - /// The philosophical aspects of this operation - /// remain undiscussed for now. - - ~Void(); - /// Destroys the Void. - - Void& operator = (const Void& v); - /// Assigns another void. -}; - - -} // namespace Poco - - -#endif // Foundation_Void_INCLUDED +// +// Void.h +// +// $Id: //poco/1.2/Foundation/include/Poco/Void.h#1 $ +// +// Library: Foundation +// Package: Core +// Module: Void +// +// Definition of the Void class. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// 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. +// +// 3. Redistributions in any form must be accompanied by information on +// how to obtain complete source code for this software and any +// accompanying software that uses this software. The source code +// must either be included in the distribution or be available for no +// more than the cost of distribution plus a nominal fee, and must be +// freely redistributable under reasonable conditions. For an +// executable file, complete source code means the source code for all +// modules it contains. It does not include source code for modules or +// files that typically accompany the major components of the operating +// system on which the executable file runs. +// +// 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 Foundation_Void_INCLUDED +#define Foundation_Void_INCLUDED + + +#include "Poco/Foundation.h" + + +namespace Poco { + + +class Foundation_API Void + /// A dummy class with value-type semantics, + /// mostly useful as a template argument. + /// + /// This class is typically used together with ActiveMethod, + /// if no argument or return value is needed. +{ +public: + Void(); + /// Creates the Void. + + Void(const Void& v); + /// Creates the Void from another Void. + /// + /// The philosophical aspects of this operation + /// remain undiscussed for now. + + ~Void(); + /// Destroys the Void. + + Void& operator = (const Void& v); + /// Assigns another void. +}; + + +} // namespace Poco + + +#endif // Foundation_Void_INCLUDED diff --git a/Foundation/include/Poco/Windows1252Encoding.h b/Foundation/include/Poco/Windows1252Encoding.h index f3c4e48c9..9632f75bf 100644 --- a/Foundation/include/Poco/Windows1252Encoding.h +++ b/Foundation/include/Poco/Windows1252Encoding.h @@ -1,68 +1,68 @@ -// -// Windows1252Encoding.h -// -// $Id: //poco/1.2/Foundation/include/Poco/Windows1252Encoding.h#1 $ -// -// Library: Foundation -// Package: Text -// Module: Windows1252Encoding -// -// Definition of the Windows1252Encoding class. -// -// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Foundation_Windows1252Encoding_INCLUDED -#define Foundation_Windows1252Encoding_INCLUDED - - -#include "Poco/Foundation.h" -#include "Poco/TextEncoding.h" - - -namespace Poco { - - -class Foundation_API Windows1252Encoding: public TextEncoding - /// Windows Codepage 1252 text encoding. -{ -public: - Windows1252Encoding(); - ~Windows1252Encoding(); - const CharacterMap& characterMap() const; - int convert(const unsigned char* bytes) const; - int convert(int ch, unsigned char* bytes, int length) const; - -private: - static const CharacterMap _charMap; -}; - - -} // namespace Poco - - -#endif // Foundation_Windows1252Encoding_INCLUDED +// +// Windows1252Encoding.h +// +// $Id: //poco/1.2/Foundation/include/Poco/Windows1252Encoding.h#1 $ +// +// Library: Foundation +// Package: Text +// Module: Windows1252Encoding +// +// Definition of the Windows1252Encoding class. +// +// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Foundation_Windows1252Encoding_INCLUDED +#define Foundation_Windows1252Encoding_INCLUDED + + +#include "Poco/Foundation.h" +#include "Poco/TextEncoding.h" + + +namespace Poco { + + +class Foundation_API Windows1252Encoding: public TextEncoding + /// Windows Codepage 1252 text encoding. +{ +public: + Windows1252Encoding(); + ~Windows1252Encoding(); + const CharacterMap& characterMap() const; + int convert(const unsigned char* bytes) const; + int convert(int ch, unsigned char* bytes, int length) const; + +private: + static const CharacterMap _charMap; +}; + + +} // namespace Poco + + +#endif // Foundation_Windows1252Encoding_INCLUDED diff --git a/Foundation/include/Poco/zconf.h b/Foundation/include/Poco/zconf.h index 2b2d092f1..60630212c 100644 --- a/Foundation/include/Poco/zconf.h +++ b/Foundation/include/Poco/zconf.h @@ -1,332 +1,332 @@ -/* zconf.h -- configuration of the zlib compression library - * Copyright (C) 1995-2005 Jean-loup Gailly. - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -/* @(#) $Id: //poco/1.2/Foundation/include/Poco/zconf.h#1 $ */ - -#ifndef ZCONF_H -#define ZCONF_H - -/* - * If you *really* need a unique prefix for all types and library functions, - * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it. - */ -#ifdef Z_PREFIX -# define deflateInit_ z_deflateInit_ -# define deflate z_deflate -# define deflateEnd z_deflateEnd -# define inflateInit_ z_inflateInit_ -# define inflate z_inflate -# define inflateEnd z_inflateEnd -# define deflateInit2_ z_deflateInit2_ -# define deflateSetDictionary z_deflateSetDictionary -# define deflateCopy z_deflateCopy -# define deflateReset z_deflateReset -# define deflateParams z_deflateParams -# define deflateBound z_deflateBound -# define deflatePrime z_deflatePrime -# define inflateInit2_ z_inflateInit2_ -# define inflateSetDictionary z_inflateSetDictionary -# define inflateSync z_inflateSync -# define inflateSyncPoint z_inflateSyncPoint -# define inflateCopy z_inflateCopy -# define inflateReset z_inflateReset -# define inflateBack z_inflateBack -# define inflateBackEnd z_inflateBackEnd -# define compress z_compress -# define compress2 z_compress2 -# define compressBound z_compressBound -# define uncompress z_uncompress -# define adler32 z_adler32 -# define crc32 z_crc32 -# define get_crc_table z_get_crc_table -# define zError z_zError - -# define alloc_func z_alloc_func -# define free_func z_free_func -# define in_func z_in_func -# define out_func z_out_func -# define Byte z_Byte -# define uInt z_uInt -# define uLong z_uLong -# define Bytef z_Bytef -# define charf z_charf -# define intf z_intf -# define uIntf z_uIntf -# define uLongf z_uLongf -# define voidpf z_voidpf -# define voidp z_voidp -#endif - -#if defined(__MSDOS__) && !defined(MSDOS) -# define MSDOS -#endif -#if (defined(OS_2) || defined(__OS2__)) && !defined(OS2) -# define OS2 -#endif -#if defined(_WINDOWS) && !defined(WINDOWS) -# define WINDOWS -#endif -#if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__) -# ifndef WIN32 -# define WIN32 -# endif -#endif -#if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32) -# if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__) -# ifndef SYS16BIT -# define SYS16BIT -# endif -# endif -#endif - -/* - * Compile with -DMAXSEG_64K if the alloc function cannot allocate more - * than 64k bytes at a time (needed on systems with 16-bit int). - */ -#ifdef SYS16BIT -# define MAXSEG_64K -#endif -#ifdef MSDOS -# define UNALIGNED_OK -#endif - -#ifdef __STDC_VERSION__ -# ifndef STDC -# define STDC -# endif -# if __STDC_VERSION__ >= 199901L -# ifndef STDC99 -# define STDC99 -# endif -# endif -#endif -#if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus)) -# define STDC -#endif -#if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__)) -# define STDC -#endif -#if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32)) -# define STDC -#endif -#if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__)) -# define STDC -#endif - -#if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */ -# define STDC -#endif - -#ifndef STDC -# ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */ -# define const /* note: need a more gentle solution here */ -# endif -#endif - -/* Some Mac compilers merge all .h files incorrectly: */ -#if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__) -# define NO_DUMMY_DECL -#endif - -/* Maximum value for memLevel in deflateInit2 */ -#ifndef MAX_MEM_LEVEL -# ifdef MAXSEG_64K -# define MAX_MEM_LEVEL 8 -# else -# define MAX_MEM_LEVEL 9 -# endif -#endif - -/* Maximum value for windowBits in deflateInit2 and inflateInit2. - * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files - * created by gzip. (Files created by minigzip can still be extracted by - * gzip.) - */ -#ifndef MAX_WBITS -# define MAX_WBITS 15 /* 32K LZ77 window */ -#endif - -/* The memory requirements for deflate are (in bytes): - (1 << (windowBits+2)) + (1 << (memLevel+9)) - that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values) - plus a few kilobytes for small objects. For example, if you want to reduce - the default memory requirements from 256K to 128K, compile with - make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7" - Of course this will generally degrade compression (there's no free lunch). - - The memory requirements for inflate are (in bytes) 1 << windowBits - that is, 32K for windowBits=15 (default value) plus a few kilobytes - for small objects. -*/ - - /* Type declarations */ - -#ifndef OF /* function prototypes */ -# ifdef STDC -# define OF(args) args -# else -# define OF(args) () -# endif -#endif - -/* The following definitions for FAR are needed only for MSDOS mixed - * model programming (small or medium model with some far allocations). - * This was tested only with MSC; for other MSDOS compilers you may have - * to define NO_MEMCPY in zutil.h. If you don't need the mixed model, - * just define FAR to be empty. - */ -#ifdef SYS16BIT -# if defined(M_I86SM) || defined(M_I86MM) - /* MSC small or medium model */ -# define SMALL_MEDIUM -# ifdef _MSC_VER -# define FAR _far -# else -# define FAR far -# endif -# endif -# if (defined(__SMALL__) || defined(__MEDIUM__)) - /* Turbo C small or medium model */ -# define SMALL_MEDIUM -# ifdef __BORLANDC__ -# define FAR _far -# else -# define FAR far -# endif -# endif -#endif - -#if defined(WINDOWS) || defined(WIN32) - /* If building or using zlib as a DLL, define ZLIB_DLL. - * This is not mandatory, but it offers a little performance increase. - */ -# ifdef ZLIB_DLL -# if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500)) -# ifdef ZLIB_INTERNAL -# define ZEXTERN extern __declspec(dllexport) -# else -# define ZEXTERN extern __declspec(dllimport) -# endif -# endif -# endif /* ZLIB_DLL */ - /* If building or using zlib with the WINAPI/WINAPIV calling convention, - * define ZLIB_WINAPI. - * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI. - */ -# ifdef ZLIB_WINAPI -# ifdef FAR -# undef FAR -# endif -# include - /* No need for _export, use ZLIB.DEF instead. */ - /* For complete Windows compatibility, use WINAPI, not __stdcall. */ -# define ZEXPORT WINAPI -# ifdef WIN32 -# define ZEXPORTVA WINAPIV -# else -# define ZEXPORTVA FAR CDECL -# endif -# endif -#endif - -#if defined (__BEOS__) -# ifdef ZLIB_DLL -# ifdef ZLIB_INTERNAL -# define ZEXPORT __declspec(dllexport) -# define ZEXPORTVA __declspec(dllexport) -# else -# define ZEXPORT __declspec(dllimport) -# define ZEXPORTVA __declspec(dllimport) -# endif -# endif -#endif - -#ifndef ZEXTERN -# define ZEXTERN extern -#endif -#ifndef ZEXPORT -# define ZEXPORT -#endif -#ifndef ZEXPORTVA -# define ZEXPORTVA -#endif - -#ifndef FAR -# define FAR -#endif - -#if !defined(__MACTYPES__) -typedef unsigned char Byte; /* 8 bits */ -#endif -typedef unsigned int uInt; /* 16 bits or more */ -typedef unsigned long uLong; /* 32 bits or more */ - -#ifdef SMALL_MEDIUM - /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */ -# define Bytef Byte FAR -#else - typedef Byte FAR Bytef; -#endif -typedef char FAR charf; -typedef int FAR intf; -typedef uInt FAR uIntf; -typedef uLong FAR uLongf; - -#ifdef STDC - typedef void const *voidpc; - typedef void FAR *voidpf; - typedef void *voidp; -#else - typedef Byte const *voidpc; - typedef Byte FAR *voidpf; - typedef Byte *voidp; -#endif - -#if 0 /* HAVE_UNISTD_H -- this line is updated by ./configure */ -# include /* for off_t */ -# include /* for SEEK_* and off_t */ -# ifdef VMS -# include /* for off_t */ -# endif -# define z_off_t off_t -#endif -#ifndef SEEK_SET -# define SEEK_SET 0 /* Seek from beginning of file. */ -# define SEEK_CUR 1 /* Seek from current position. */ -# define SEEK_END 2 /* Set file pointer to EOF plus "offset" */ -#endif -#ifndef z_off_t -# define z_off_t long -#endif - -#if defined(__OS400__) -# define NO_vsnprintf -#endif - -#if defined(__MVS__) -# define NO_vsnprintf -# ifdef FAR -# undef FAR -# endif -#endif - -/* MVS linker does not support external names larger than 8 bytes */ -#if defined(__MVS__) -# pragma map(deflateInit_,"DEIN") -# pragma map(deflateInit2_,"DEIN2") -# pragma map(deflateEnd,"DEEND") -# pragma map(deflateBound,"DEBND") -# pragma map(inflateInit_,"ININ") -# pragma map(inflateInit2_,"ININ2") -# pragma map(inflateEnd,"INEND") -# pragma map(inflateSync,"INSY") -# pragma map(inflateSetDictionary,"INSEDI") -# pragma map(compressBound,"CMBND") -# pragma map(inflate_table,"INTABL") -# pragma map(inflate_fast,"INFA") -# pragma map(inflate_copyright,"INCOPY") -#endif - -#endif /* ZCONF_H */ +/* zconf.h -- configuration of the zlib compression library + * Copyright (C) 1995-2005 Jean-loup Gailly. + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* @(#) $Id: //poco/1.2/Foundation/include/Poco/zconf.h#1 $ */ + +#ifndef ZCONF_H +#define ZCONF_H + +/* + * If you *really* need a unique prefix for all types and library functions, + * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it. + */ +#ifdef Z_PREFIX +# define deflateInit_ z_deflateInit_ +# define deflate z_deflate +# define deflateEnd z_deflateEnd +# define inflateInit_ z_inflateInit_ +# define inflate z_inflate +# define inflateEnd z_inflateEnd +# define deflateInit2_ z_deflateInit2_ +# define deflateSetDictionary z_deflateSetDictionary +# define deflateCopy z_deflateCopy +# define deflateReset z_deflateReset +# define deflateParams z_deflateParams +# define deflateBound z_deflateBound +# define deflatePrime z_deflatePrime +# define inflateInit2_ z_inflateInit2_ +# define inflateSetDictionary z_inflateSetDictionary +# define inflateSync z_inflateSync +# define inflateSyncPoint z_inflateSyncPoint +# define inflateCopy z_inflateCopy +# define inflateReset z_inflateReset +# define inflateBack z_inflateBack +# define inflateBackEnd z_inflateBackEnd +# define compress z_compress +# define compress2 z_compress2 +# define compressBound z_compressBound +# define uncompress z_uncompress +# define adler32 z_adler32 +# define crc32 z_crc32 +# define get_crc_table z_get_crc_table +# define zError z_zError + +# define alloc_func z_alloc_func +# define free_func z_free_func +# define in_func z_in_func +# define out_func z_out_func +# define Byte z_Byte +# define uInt z_uInt +# define uLong z_uLong +# define Bytef z_Bytef +# define charf z_charf +# define intf z_intf +# define uIntf z_uIntf +# define uLongf z_uLongf +# define voidpf z_voidpf +# define voidp z_voidp +#endif + +#if defined(__MSDOS__) && !defined(MSDOS) +# define MSDOS +#endif +#if (defined(OS_2) || defined(__OS2__)) && !defined(OS2) +# define OS2 +#endif +#if defined(_WINDOWS) && !defined(WINDOWS) +# define WINDOWS +#endif +#if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__) +# ifndef WIN32 +# define WIN32 +# endif +#endif +#if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32) +# if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__) +# ifndef SYS16BIT +# define SYS16BIT +# endif +# endif +#endif + +/* + * Compile with -DMAXSEG_64K if the alloc function cannot allocate more + * than 64k bytes at a time (needed on systems with 16-bit int). + */ +#ifdef SYS16BIT +# define MAXSEG_64K +#endif +#ifdef MSDOS +# define UNALIGNED_OK +#endif + +#ifdef __STDC_VERSION__ +# ifndef STDC +# define STDC +# endif +# if __STDC_VERSION__ >= 199901L +# ifndef STDC99 +# define STDC99 +# endif +# endif +#endif +#if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus)) +# define STDC +#endif +#if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__)) +# define STDC +#endif +#if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32)) +# define STDC +#endif +#if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__)) +# define STDC +#endif + +#if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */ +# define STDC +#endif + +#ifndef STDC +# ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */ +# define const /* note: need a more gentle solution here */ +# endif +#endif + +/* Some Mac compilers merge all .h files incorrectly: */ +#if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__) +# define NO_DUMMY_DECL +#endif + +/* Maximum value for memLevel in deflateInit2 */ +#ifndef MAX_MEM_LEVEL +# ifdef MAXSEG_64K +# define MAX_MEM_LEVEL 8 +# else +# define MAX_MEM_LEVEL 9 +# endif +#endif + +/* Maximum value for windowBits in deflateInit2 and inflateInit2. + * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files + * created by gzip. (Files created by minigzip can still be extracted by + * gzip.) + */ +#ifndef MAX_WBITS +# define MAX_WBITS 15 /* 32K LZ77 window */ +#endif + +/* The memory requirements for deflate are (in bytes): + (1 << (windowBits+2)) + (1 << (memLevel+9)) + that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values) + plus a few kilobytes for small objects. For example, if you want to reduce + the default memory requirements from 256K to 128K, compile with + make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7" + Of course this will generally degrade compression (there's no free lunch). + + The memory requirements for inflate are (in bytes) 1 << windowBits + that is, 32K for windowBits=15 (default value) plus a few kilobytes + for small objects. +*/ + + /* Type declarations */ + +#ifndef OF /* function prototypes */ +# ifdef STDC +# define OF(args) args +# else +# define OF(args) () +# endif +#endif + +/* The following definitions for FAR are needed only for MSDOS mixed + * model programming (small or medium model with some far allocations). + * This was tested only with MSC; for other MSDOS compilers you may have + * to define NO_MEMCPY in zutil.h. If you don't need the mixed model, + * just define FAR to be empty. + */ +#ifdef SYS16BIT +# if defined(M_I86SM) || defined(M_I86MM) + /* MSC small or medium model */ +# define SMALL_MEDIUM +# ifdef _MSC_VER +# define FAR _far +# else +# define FAR far +# endif +# endif +# if (defined(__SMALL__) || defined(__MEDIUM__)) + /* Turbo C small or medium model */ +# define SMALL_MEDIUM +# ifdef __BORLANDC__ +# define FAR _far +# else +# define FAR far +# endif +# endif +#endif + +#if defined(WINDOWS) || defined(WIN32) + /* If building or using zlib as a DLL, define ZLIB_DLL. + * This is not mandatory, but it offers a little performance increase. + */ +# ifdef ZLIB_DLL +# if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500)) +# ifdef ZLIB_INTERNAL +# define ZEXTERN extern __declspec(dllexport) +# else +# define ZEXTERN extern __declspec(dllimport) +# endif +# endif +# endif /* ZLIB_DLL */ + /* If building or using zlib with the WINAPI/WINAPIV calling convention, + * define ZLIB_WINAPI. + * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI. + */ +# ifdef ZLIB_WINAPI +# ifdef FAR +# undef FAR +# endif +# include + /* No need for _export, use ZLIB.DEF instead. */ + /* For complete Windows compatibility, use WINAPI, not __stdcall. */ +# define ZEXPORT WINAPI +# ifdef WIN32 +# define ZEXPORTVA WINAPIV +# else +# define ZEXPORTVA FAR CDECL +# endif +# endif +#endif + +#if defined (__BEOS__) +# ifdef ZLIB_DLL +# ifdef ZLIB_INTERNAL +# define ZEXPORT __declspec(dllexport) +# define ZEXPORTVA __declspec(dllexport) +# else +# define ZEXPORT __declspec(dllimport) +# define ZEXPORTVA __declspec(dllimport) +# endif +# endif +#endif + +#ifndef ZEXTERN +# define ZEXTERN extern +#endif +#ifndef ZEXPORT +# define ZEXPORT +#endif +#ifndef ZEXPORTVA +# define ZEXPORTVA +#endif + +#ifndef FAR +# define FAR +#endif + +#if !defined(__MACTYPES__) +typedef unsigned char Byte; /* 8 bits */ +#endif +typedef unsigned int uInt; /* 16 bits or more */ +typedef unsigned long uLong; /* 32 bits or more */ + +#ifdef SMALL_MEDIUM + /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */ +# define Bytef Byte FAR +#else + typedef Byte FAR Bytef; +#endif +typedef char FAR charf; +typedef int FAR intf; +typedef uInt FAR uIntf; +typedef uLong FAR uLongf; + +#ifdef STDC + typedef void const *voidpc; + typedef void FAR *voidpf; + typedef void *voidp; +#else + typedef Byte const *voidpc; + typedef Byte FAR *voidpf; + typedef Byte *voidp; +#endif + +#if 0 /* HAVE_UNISTD_H -- this line is updated by ./configure */ +# include /* for off_t */ +# include /* for SEEK_* and off_t */ +# ifdef VMS +# include /* for off_t */ +# endif +# define z_off_t off_t +#endif +#ifndef SEEK_SET +# define SEEK_SET 0 /* Seek from beginning of file. */ +# define SEEK_CUR 1 /* Seek from current position. */ +# define SEEK_END 2 /* Set file pointer to EOF plus "offset" */ +#endif +#ifndef z_off_t +# define z_off_t long +#endif + +#if defined(__OS400__) +# define NO_vsnprintf +#endif + +#if defined(__MVS__) +# define NO_vsnprintf +# ifdef FAR +# undef FAR +# endif +#endif + +/* MVS linker does not support external names larger than 8 bytes */ +#if defined(__MVS__) +# pragma map(deflateInit_,"DEIN") +# pragma map(deflateInit2_,"DEIN2") +# pragma map(deflateEnd,"DEEND") +# pragma map(deflateBound,"DEBND") +# pragma map(inflateInit_,"ININ") +# pragma map(inflateInit2_,"ININ2") +# pragma map(inflateEnd,"INEND") +# pragma map(inflateSync,"INSY") +# pragma map(inflateSetDictionary,"INSEDI") +# pragma map(compressBound,"CMBND") +# pragma map(inflate_table,"INTABL") +# pragma map(inflate_fast,"INFA") +# pragma map(inflate_copyright,"INCOPY") +#endif + +#endif /* ZCONF_H */ diff --git a/Foundation/include/Poco/zlib.h b/Foundation/include/Poco/zlib.h index 62d0e4675..022817927 100644 --- a/Foundation/include/Poco/zlib.h +++ b/Foundation/include/Poco/zlib.h @@ -1,1357 +1,1357 @@ -/* zlib.h -- interface of the 'zlib' general purpose compression library - version 1.2.3, July 18th, 2005 - - Copyright (C) 1995-2005 Jean-loup Gailly and Mark Adler - - 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. - - Jean-loup Gailly Mark Adler - jloup@gzip.org madler@alumni.caltech.edu - - - The data format used by the zlib library is described by RFCs (Request for - Comments) 1950 to 1952 in the files http://www.ietf.org/rfc/rfc1950.txt - (zlib format), rfc1951.txt (deflate format) and rfc1952.txt (gzip format). -*/ - -#ifndef ZLIB_H -#define ZLIB_H - -#include "zconf.h" - -#ifdef __cplusplus -extern "C" { -#endif - -#define ZLIB_VERSION "1.2.3" -#define ZLIB_VERNUM 0x1230 - -/* - The 'zlib' compression library provides in-memory compression and - decompression functions, including integrity checks of the uncompressed - data. This version of the library supports only one compression method - (deflation) but other algorithms will be added later and will have the same - stream interface. - - Compression can be done in a single step if the buffers are large - enough (for example if an input file is mmap'ed), or can be done by - repeated calls of the compression function. In the latter case, the - application must provide more input and/or consume the output - (providing more output space) before each call. - - The compressed data format used by default by the in-memory functions is - the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped - around a deflate stream, which is itself documented in RFC 1951. - - The library also supports reading and writing files in gzip (.gz) format - with an interface similar to that of stdio using the functions that start - with "gz". The gzip format is different from the zlib format. gzip is a - gzip wrapper, documented in RFC 1952, wrapped around a deflate stream. - - This library can optionally read and write gzip streams in memory as well. - - The zlib format was designed to be compact and fast for use in memory - and on communications channels. The gzip format was designed for single- - file compression on file systems, has a larger header than zlib to maintain - directory information, and uses a different, slower check method than zlib. - - The library does not install any signal handler. The decoder checks - the consistency of the compressed data, so the library should never - crash even in case of corrupted input. -*/ - -typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size)); -typedef void (*free_func) OF((voidpf opaque, voidpf address)); - -struct internal_state; - -typedef struct z_stream_s { - Bytef *next_in; /* next input byte */ - uInt avail_in; /* number of bytes available at next_in */ - uLong total_in; /* total nb of input bytes read so far */ - - Bytef *next_out; /* next output byte should be put there */ - uInt avail_out; /* remaining free space at next_out */ - uLong total_out; /* total nb of bytes output so far */ - - char *msg; /* last error message, NULL if no error */ - struct internal_state FAR *state; /* not visible by applications */ - - alloc_func zalloc; /* used to allocate the internal state */ - free_func zfree; /* used to free the internal state */ - voidpf opaque; /* private data object passed to zalloc and zfree */ - - int data_type; /* best guess about the data type: binary or text */ - uLong adler; /* adler32 value of the uncompressed data */ - uLong reserved; /* reserved for future use */ -} z_stream; - -typedef z_stream FAR *z_streamp; - -/* - gzip header information passed to and from zlib routines. See RFC 1952 - for more details on the meanings of these fields. -*/ -typedef struct gz_header_s { - int text; /* true if compressed data believed to be text */ - uLong time; /* modification time */ - int xflags; /* extra flags (not used when writing a gzip file) */ - int os; /* operating system */ - Bytef *extra; /* pointer to extra field or Z_NULL if none */ - uInt extra_len; /* extra field length (valid if extra != Z_NULL) */ - uInt extra_max; /* space at extra (only when reading header) */ - Bytef *name; /* pointer to zero-terminated file name or Z_NULL */ - uInt name_max; /* space at name (only when reading header) */ - Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */ - uInt comm_max; /* space at comment (only when reading header) */ - int hcrc; /* true if there was or will be a header crc */ - int done; /* true when done reading gzip header (not used - when writing a gzip file) */ -} gz_header; - -typedef gz_header FAR *gz_headerp; - -/* - The application must update next_in and avail_in when avail_in has - dropped to zero. It must update next_out and avail_out when avail_out - has dropped to zero. The application must initialize zalloc, zfree and - opaque before calling the init function. All other fields are set by the - compression library and must not be updated by the application. - - The opaque value provided by the application will be passed as the first - parameter for calls of zalloc and zfree. This can be useful for custom - memory management. The compression library attaches no meaning to the - opaque value. - - zalloc must return Z_NULL if there is not enough memory for the object. - If zlib is used in a multi-threaded application, zalloc and zfree must be - thread safe. - - On 16-bit systems, the functions zalloc and zfree must be able to allocate - exactly 65536 bytes, but will not be required to allocate more than this - if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS, - pointers returned by zalloc for objects of exactly 65536 bytes *must* - have their offset normalized to zero. The default allocation function - provided by this library ensures this (see zutil.c). To reduce memory - requirements and avoid any allocation of 64K objects, at the expense of - compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h). - - The fields total_in and total_out can be used for statistics or - progress reports. After compression, total_in holds the total size of - the uncompressed data and may be saved for use in the decompressor - (particularly if the decompressor wants to decompress everything in - a single step). -*/ - - /* constants */ - -#define Z_NO_FLUSH 0 -#define Z_PARTIAL_FLUSH 1 /* will be removed, use Z_SYNC_FLUSH instead */ -#define Z_SYNC_FLUSH 2 -#define Z_FULL_FLUSH 3 -#define Z_FINISH 4 -#define Z_BLOCK 5 -/* Allowed flush values; see deflate() and inflate() below for details */ - -#define Z_OK 0 -#define Z_STREAM_END 1 -#define Z_NEED_DICT 2 -#define Z_ERRNO (-1) -#define Z_STREAM_ERROR (-2) -#define Z_DATA_ERROR (-3) -#define Z_MEM_ERROR (-4) -#define Z_BUF_ERROR (-5) -#define Z_VERSION_ERROR (-6) -/* Return codes for the compression/decompression functions. Negative - * values are errors, positive values are used for special but normal events. - */ - -#define Z_NO_COMPRESSION 0 -#define Z_BEST_SPEED 1 -#define Z_BEST_COMPRESSION 9 -#define Z_DEFAULT_COMPRESSION (-1) -/* compression levels */ - -#define Z_FILTERED 1 -#define Z_HUFFMAN_ONLY 2 -#define Z_RLE 3 -#define Z_FIXED 4 -#define Z_DEFAULT_STRATEGY 0 -/* compression strategy; see deflateInit2() below for details */ - -#define Z_BINARY 0 -#define Z_TEXT 1 -#define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */ -#define Z_UNKNOWN 2 -/* Possible values of the data_type field (though see inflate()) */ - -#define Z_DEFLATED 8 -/* The deflate compression method (the only one supported in this version) */ - -#define Z_NULL 0 /* for initializing zalloc, zfree, opaque */ - -#define zlib_version zlibVersion() -/* for compatibility with versions < 1.0.2 */ - - /* basic functions */ - -ZEXTERN const char * ZEXPORT zlibVersion OF((void)); -/* The application can compare zlibVersion and ZLIB_VERSION for consistency. - If the first character differs, the library code actually used is - not compatible with the zlib.h header file used by the application. - This check is automatically made by deflateInit and inflateInit. - */ - -/* -ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level)); - - Initializes the internal stream state for compression. The fields - zalloc, zfree and opaque must be initialized before by the caller. - If zalloc and zfree are set to Z_NULL, deflateInit updates them to - use default allocation functions. - - The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9: - 1 gives best speed, 9 gives best compression, 0 gives no compression at - all (the input data is simply copied a block at a time). - Z_DEFAULT_COMPRESSION requests a default compromise between speed and - compression (currently equivalent to level 6). - - deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not - enough memory, Z_STREAM_ERROR if level is not a valid compression level, - Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible - with the version assumed by the caller (ZLIB_VERSION). - msg is set to null if there is no error message. deflateInit does not - perform any compression: this will be done by deflate(). -*/ - - -ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush)); -/* - deflate compresses as much data as possible, and stops when the input - buffer becomes empty or the output buffer becomes full. It may introduce some - output latency (reading input without producing any output) except when - forced to flush. - - The detailed semantics are as follows. deflate performs one or both of the - following actions: - - - Compress more input starting at next_in and update next_in and avail_in - accordingly. If not all input can be processed (because there is not - enough room in the output buffer), next_in and avail_in are updated and - processing will resume at this point for the next call of deflate(). - - - Provide more output starting at next_out and update next_out and avail_out - accordingly. This action is forced if the parameter flush is non zero. - Forcing flush frequently degrades the compression ratio, so this parameter - should be set only when necessary (in interactive applications). - Some output may be provided even if flush is not set. - - Before the call of deflate(), the application should ensure that at least - one of the actions is possible, by providing more input and/or consuming - more output, and updating avail_in or avail_out accordingly; avail_out - should never be zero before the call. The application can consume the - compressed output when it wants, for example when the output buffer is full - (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK - and with zero avail_out, it must be called again after making room in the - output buffer because there might be more output pending. - - Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to - decide how much data to accumualte before producing output, in order to - maximize compression. - - If the parameter flush is set to Z_SYNC_FLUSH, all pending output is - flushed to the output buffer and the output is aligned on a byte boundary, so - that the decompressor can get all input data available so far. (In particular - avail_in is zero after the call if enough output space has been provided - before the call.) Flushing may degrade compression for some compression - algorithms and so it should be used only when necessary. - - If flush is set to Z_FULL_FLUSH, all output is flushed as with - Z_SYNC_FLUSH, and the compression state is reset so that decompression can - restart from this point if previous compressed data has been damaged or if - random access is desired. Using Z_FULL_FLUSH too often can seriously degrade - compression. - - If deflate returns with avail_out == 0, this function must be called again - with the same value of the flush parameter and more output space (updated - avail_out), until the flush is complete (deflate returns with non-zero - avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that - avail_out is greater than six to avoid repeated flush markers due to - avail_out == 0 on return. - - If the parameter flush is set to Z_FINISH, pending input is processed, - pending output is flushed and deflate returns with Z_STREAM_END if there - was enough output space; if deflate returns with Z_OK, this function must be - called again with Z_FINISH and more output space (updated avail_out) but no - more input data, until it returns with Z_STREAM_END or an error. After - deflate has returned Z_STREAM_END, the only possible operations on the - stream are deflateReset or deflateEnd. - - Z_FINISH can be used immediately after deflateInit if all the compression - is to be done in a single step. In this case, avail_out must be at least - the value returned by deflateBound (see below). If deflate does not return - Z_STREAM_END, then it must be called again as described above. - - deflate() sets strm->adler to the adler32 checksum of all input read - so far (that is, total_in bytes). - - deflate() may update strm->data_type if it can make a good guess about - the input data type (Z_BINARY or Z_TEXT). In doubt, the data is considered - binary. This field is only for information purposes and does not affect - the compression algorithm in any manner. - - deflate() returns Z_OK if some progress has been made (more input - processed or more output produced), Z_STREAM_END if all input has been - consumed and all output has been produced (only when flush is set to - Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example - if next_in or next_out was NULL), Z_BUF_ERROR if no progress is possible - (for example avail_in or avail_out was zero). Note that Z_BUF_ERROR is not - fatal, and deflate() can be called again with more input and more output - space to continue compressing. -*/ - - -ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm)); -/* - All dynamically allocated data structures for this stream are freed. - This function discards any unprocessed input and does not flush any - pending output. - - deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the - stream state was inconsistent, Z_DATA_ERROR if the stream was freed - prematurely (some input or output was discarded). In the error case, - msg may be set but then points to a static string (which must not be - deallocated). -*/ - - -/* -ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm)); - - Initializes the internal stream state for decompression. The fields - next_in, avail_in, zalloc, zfree and opaque must be initialized before by - the caller. If next_in is not Z_NULL and avail_in is large enough (the exact - value depends on the compression method), inflateInit determines the - compression method from the zlib header and allocates all data structures - accordingly; otherwise the allocation will be deferred to the first call of - inflate. If zalloc and zfree are set to Z_NULL, inflateInit updates them to - use default allocation functions. - - inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough - memory, Z_VERSION_ERROR if the zlib library version is incompatible with the - version assumed by the caller. msg is set to null if there is no error - message. inflateInit does not perform any decompression apart from reading - the zlib header if present: this will be done by inflate(). (So next_in and - avail_in may be modified, but next_out and avail_out are unchanged.) -*/ - - -ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush)); -/* - inflate decompresses as much data as possible, and stops when the input - buffer becomes empty or the output buffer becomes full. It may introduce - some output latency (reading input without producing any output) except when - forced to flush. - - The detailed semantics are as follows. inflate performs one or both of the - following actions: - - - Decompress more input starting at next_in and update next_in and avail_in - accordingly. If not all input can be processed (because there is not - enough room in the output buffer), next_in is updated and processing - will resume at this point for the next call of inflate(). - - - Provide more output starting at next_out and update next_out and avail_out - accordingly. inflate() provides as much output as possible, until there - is no more input data or no more space in the output buffer (see below - about the flush parameter). - - Before the call of inflate(), the application should ensure that at least - one of the actions is possible, by providing more input and/or consuming - more output, and updating the next_* and avail_* values accordingly. - The application can consume the uncompressed output when it wants, for - example when the output buffer is full (avail_out == 0), or after each - call of inflate(). If inflate returns Z_OK and with zero avail_out, it - must be called again after making room in the output buffer because there - might be more output pending. - - The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH, - Z_FINISH, or Z_BLOCK. Z_SYNC_FLUSH requests that inflate() flush as much - output as possible to the output buffer. Z_BLOCK requests that inflate() stop - if and when it gets to the next deflate block boundary. When decoding the - zlib or gzip format, this will cause inflate() to return immediately after - the header and before the first block. When doing a raw inflate, inflate() - will go ahead and process the first block, and will return when it gets to - the end of that block, or when it runs out of data. - - The Z_BLOCK option assists in appending to or combining deflate streams. - Also to assist in this, on return inflate() will set strm->data_type to the - number of unused bits in the last byte taken from strm->next_in, plus 64 - if inflate() is currently decoding the last block in the deflate stream, - plus 128 if inflate() returned immediately after decoding an end-of-block - code or decoding the complete header up to just before the first byte of the - deflate stream. The end-of-block will not be indicated until all of the - uncompressed data from that block has been written to strm->next_out. The - number of unused bits may in general be greater than seven, except when - bit 7 of data_type is set, in which case the number of unused bits will be - less than eight. - - inflate() should normally be called until it returns Z_STREAM_END or an - error. However if all decompression is to be performed in a single step - (a single call of inflate), the parameter flush should be set to - Z_FINISH. In this case all pending input is processed and all pending - output is flushed; avail_out must be large enough to hold all the - uncompressed data. (The size of the uncompressed data may have been saved - by the compressor for this purpose.) The next operation on this stream must - be inflateEnd to deallocate the decompression state. The use of Z_FINISH - is never required, but can be used to inform inflate that a faster approach - may be used for the single inflate() call. - - In this implementation, inflate() always flushes as much output as - possible to the output buffer, and always uses the faster approach on the - first call. So the only effect of the flush parameter in this implementation - is on the return value of inflate(), as noted below, or when it returns early - because Z_BLOCK is used. - - If a preset dictionary is needed after this call (see inflateSetDictionary - below), inflate sets strm->adler to the adler32 checksum of the dictionary - chosen by the compressor and returns Z_NEED_DICT; otherwise it sets - strm->adler to the adler32 checksum of all output produced so far (that is, - total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described - below. At the end of the stream, inflate() checks that its computed adler32 - checksum is equal to that saved by the compressor and returns Z_STREAM_END - only if the checksum is correct. - - inflate() will decompress and check either zlib-wrapped or gzip-wrapped - deflate data. The header type is detected automatically. Any information - contained in the gzip header is not retained, so applications that need that - information should instead use raw inflate, see inflateInit2() below, or - inflateBack() and perform their own processing of the gzip header and - trailer. - - inflate() returns Z_OK if some progress has been made (more input processed - or more output produced), Z_STREAM_END if the end of the compressed data has - been reached and all uncompressed output has been produced, Z_NEED_DICT if a - preset dictionary is needed at this point, Z_DATA_ERROR if the input data was - corrupted (input stream not conforming to the zlib format or incorrect check - value), Z_STREAM_ERROR if the stream structure was inconsistent (for example - if next_in or next_out was NULL), Z_MEM_ERROR if there was not enough memory, - Z_BUF_ERROR if no progress is possible or if there was not enough room in the - output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and - inflate() can be called again with more input and more output space to - continue decompressing. If Z_DATA_ERROR is returned, the application may then - call inflateSync() to look for a good compression block if a partial recovery - of the data is desired. -*/ - - -ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm)); -/* - All dynamically allocated data structures for this stream are freed. - This function discards any unprocessed input and does not flush any - pending output. - - inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state - was inconsistent. In the error case, msg may be set but then points to a - static string (which must not be deallocated). -*/ - - /* Advanced functions */ - -/* - The following functions are needed only in some special applications. -*/ - -/* -ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm, - int level, - int method, - int windowBits, - int memLevel, - int strategy)); - - This is another version of deflateInit with more compression options. The - fields next_in, zalloc, zfree and opaque must be initialized before by - the caller. - - The method parameter is the compression method. It must be Z_DEFLATED in - this version of the library. - - The windowBits parameter is the base two logarithm of the window size - (the size of the history buffer). It should be in the range 8..15 for this - version of the library. Larger values of this parameter result in better - compression at the expense of memory usage. The default value is 15 if - deflateInit is used instead. - - windowBits can also be -8..-15 for raw deflate. In this case, -windowBits - determines the window size. deflate() will then generate raw deflate data - with no zlib header or trailer, and will not compute an adler32 check value. - - windowBits can also be greater than 15 for optional gzip encoding. Add - 16 to windowBits to write a simple gzip header and trailer around the - compressed data instead of a zlib wrapper. The gzip header will have no - file name, no extra data, no comment, no modification time (set to zero), - no header crc, and the operating system will be set to 255 (unknown). If a - gzip stream is being written, strm->adler is a crc32 instead of an adler32. - - The memLevel parameter specifies how much memory should be allocated - for the internal compression state. memLevel=1 uses minimum memory but - is slow and reduces compression ratio; memLevel=9 uses maximum memory - for optimal speed. The default value is 8. See zconf.h for total memory - usage as a function of windowBits and memLevel. - - The strategy parameter is used to tune the compression algorithm. Use the - value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a - filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no - string match), or Z_RLE to limit match distances to one (run-length - encoding). Filtered data consists mostly of small values with a somewhat - random distribution. In this case, the compression algorithm is tuned to - compress them better. The effect of Z_FILTERED is to force more Huffman - coding and less string matching; it is somewhat intermediate between - Z_DEFAULT and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as fast as - Z_HUFFMAN_ONLY, but give better compression for PNG image data. The strategy - parameter only affects the compression ratio but not the correctness of the - compressed output even if it is not set appropriately. Z_FIXED prevents the - use of dynamic Huffman codes, allowing for a simpler decoder for special - applications. - - deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough - memory, Z_STREAM_ERROR if a parameter is invalid (such as an invalid - method). msg is set to null if there is no error message. deflateInit2 does - not perform any compression: this will be done by deflate(). -*/ - -ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm, - const Bytef *dictionary, - uInt dictLength)); -/* - Initializes the compression dictionary from the given byte sequence - without producing any compressed output. This function must be called - immediately after deflateInit, deflateInit2 or deflateReset, before any - call of deflate. The compressor and decompressor must use exactly the same - dictionary (see inflateSetDictionary). - - The dictionary should consist of strings (byte sequences) that are likely - to be encountered later in the data to be compressed, with the most commonly - used strings preferably put towards the end of the dictionary. Using a - dictionary is most useful when the data to be compressed is short and can be - predicted with good accuracy; the data can then be compressed better than - with the default empty dictionary. - - Depending on the size of the compression data structures selected by - deflateInit or deflateInit2, a part of the dictionary may in effect be - discarded, for example if the dictionary is larger than the window size in - deflate or deflate2. Thus the strings most likely to be useful should be - put at the end of the dictionary, not at the front. In addition, the - current implementation of deflate will use at most the window size minus - 262 bytes of the provided dictionary. - - Upon return of this function, strm->adler is set to the adler32 value - of the dictionary; the decompressor may later use this value to determine - which dictionary has been used by the compressor. (The adler32 value - applies to the whole dictionary even if only a subset of the dictionary is - actually used by the compressor.) If a raw deflate was requested, then the - adler32 value is not computed and strm->adler is not set. - - deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a - parameter is invalid (such as NULL dictionary) or the stream state is - inconsistent (for example if deflate has already been called for this stream - or if the compression method is bsort). deflateSetDictionary does not - perform any compression: this will be done by deflate(). -*/ - -ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest, - z_streamp source)); -/* - Sets the destination stream as a complete copy of the source stream. - - This function can be useful when several compression strategies will be - tried, for example when there are several ways of pre-processing the input - data with a filter. The streams that will be discarded should then be freed - by calling deflateEnd. Note that deflateCopy duplicates the internal - compression state which can be quite large, so this strategy is slow and - can consume lots of memory. - - deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not - enough memory, Z_STREAM_ERROR if the source stream state was inconsistent - (such as zalloc being NULL). msg is left unchanged in both source and - destination. -*/ - -ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm)); -/* - This function is equivalent to deflateEnd followed by deflateInit, - but does not free and reallocate all the internal compression state. - The stream will keep the same compression level and any other attributes - that may have been set by deflateInit2. - - deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source - stream state was inconsistent (such as zalloc or state being NULL). -*/ - -ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm, - int level, - int strategy)); -/* - Dynamically update the compression level and compression strategy. The - interpretation of level and strategy is as in deflateInit2. This can be - used to switch between compression and straight copy of the input data, or - to switch to a different kind of input data requiring a different - strategy. If the compression level is changed, the input available so far - is compressed with the old level (and may be flushed); the new level will - take effect only at the next call of deflate(). - - Before the call of deflateParams, the stream state must be set as for - a call of deflate(), since the currently available input may have to - be compressed and flushed. In particular, strm->avail_out must be non-zero. - - deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source - stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR - if strm->avail_out was zero. -*/ - -ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm, - int good_length, - int max_lazy, - int nice_length, - int max_chain)); -/* - Fine tune deflate's internal compression parameters. This should only be - used by someone who understands the algorithm used by zlib's deflate for - searching for the best matching string, and even then only by the most - fanatic optimizer trying to squeeze out the last compressed bit for their - specific input data. Read the deflate.c source code for the meaning of the - max_lazy, good_length, nice_length, and max_chain parameters. - - deflateTune() can be called after deflateInit() or deflateInit2(), and - returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream. - */ - -ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm, - uLong sourceLen)); -/* - deflateBound() returns an upper bound on the compressed size after - deflation of sourceLen bytes. It must be called after deflateInit() - or deflateInit2(). This would be used to allocate an output buffer - for deflation in a single pass, and so would be called before deflate(). -*/ - -ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm, - int bits, - int value)); -/* - deflatePrime() inserts bits in the deflate output stream. The intent - is that this function is used to start off the deflate output with the - bits leftover from a previous deflate stream when appending to it. As such, - this function can only be used for raw deflate, and must be used before the - first deflate() call after a deflateInit2() or deflateReset(). bits must be - less than or equal to 16, and that many of the least significant bits of - value will be inserted in the output. - - deflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source - stream state was inconsistent. -*/ - -ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm, - gz_headerp head)); -/* - deflateSetHeader() provides gzip header information for when a gzip - stream is requested by deflateInit2(). deflateSetHeader() may be called - after deflateInit2() or deflateReset() and before the first call of - deflate(). The text, time, os, extra field, name, and comment information - in the provided gz_header structure are written to the gzip header (xflag is - ignored -- the extra flags are set according to the compression level). The - caller must assure that, if not Z_NULL, name and comment are terminated with - a zero byte, and that if extra is not Z_NULL, that extra_len bytes are - available there. If hcrc is true, a gzip header crc is included. Note that - the current versions of the command-line version of gzip (up through version - 1.3.x) do not support header crc's, and will report that it is a "multi-part - gzip file" and give up. - - If deflateSetHeader is not used, the default gzip header has text false, - the time set to zero, and os set to 255, with no extra, name, or comment - fields. The gzip header is returned to the default state by deflateReset(). - - deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source - stream state was inconsistent. -*/ - -/* -ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm, - int windowBits)); - - This is another version of inflateInit with an extra parameter. The - fields next_in, avail_in, zalloc, zfree and opaque must be initialized - before by the caller. - - The windowBits parameter is the base two logarithm of the maximum window - size (the size of the history buffer). It should be in the range 8..15 for - this version of the library. The default value is 15 if inflateInit is used - instead. windowBits must be greater than or equal to the windowBits value - provided to deflateInit2() while compressing, or it must be equal to 15 if - deflateInit2() was not used. If a compressed stream with a larger window - size is given as input, inflate() will return with the error code - Z_DATA_ERROR instead of trying to allocate a larger window. - - windowBits can also be -8..-15 for raw inflate. In this case, -windowBits - determines the window size. inflate() will then process raw deflate data, - not looking for a zlib or gzip header, not generating a check value, and not - looking for any check values for comparison at the end of the stream. This - is for use with other formats that use the deflate compressed data format - such as zip. Those formats provide their own check values. If a custom - format is developed using the raw deflate format for compressed data, it is - recommended that a check value such as an adler32 or a crc32 be applied to - the uncompressed data as is done in the zlib, gzip, and zip formats. For - most applications, the zlib format should be used as is. Note that comments - above on the use in deflateInit2() applies to the magnitude of windowBits. - - windowBits can also be greater than 15 for optional gzip decoding. Add - 32 to windowBits to enable zlib and gzip decoding with automatic header - detection, or add 16 to decode only the gzip format (the zlib format will - return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is - a crc32 instead of an adler32. - - inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough - memory, Z_STREAM_ERROR if a parameter is invalid (such as a null strm). msg - is set to null if there is no error message. inflateInit2 does not perform - any decompression apart from reading the zlib header if present: this will - be done by inflate(). (So next_in and avail_in may be modified, but next_out - and avail_out are unchanged.) -*/ - -ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm, - const Bytef *dictionary, - uInt dictLength)); -/* - Initializes the decompression dictionary from the given uncompressed byte - sequence. This function must be called immediately after a call of inflate, - if that call returned Z_NEED_DICT. The dictionary chosen by the compressor - can be determined from the adler32 value returned by that call of inflate. - The compressor and decompressor must use exactly the same dictionary (see - deflateSetDictionary). For raw inflate, this function can be called - immediately after inflateInit2() or inflateReset() and before any call of - inflate() to set the dictionary. The application must insure that the - dictionary that was used for compression is provided. - - inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a - parameter is invalid (such as NULL dictionary) or the stream state is - inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the - expected one (incorrect adler32 value). inflateSetDictionary does not - perform any decompression: this will be done by subsequent calls of - inflate(). -*/ - -ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm)); -/* - Skips invalid compressed data until a full flush point (see above the - description of deflate with Z_FULL_FLUSH) can be found, or until all - available input is skipped. No output is provided. - - inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR - if no more input was provided, Z_DATA_ERROR if no flush point has been found, - or Z_STREAM_ERROR if the stream structure was inconsistent. In the success - case, the application may save the current current value of total_in which - indicates where valid compressed data was found. In the error case, the - application may repeatedly call inflateSync, providing more input each time, - until success or end of the input data. -*/ - -ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest, - z_streamp source)); -/* - Sets the destination stream as a complete copy of the source stream. - - This function can be useful when randomly accessing a large stream. The - first pass through the stream can periodically record the inflate state, - allowing restarting inflate at those points when randomly accessing the - stream. - - inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not - enough memory, Z_STREAM_ERROR if the source stream state was inconsistent - (such as zalloc being NULL). msg is left unchanged in both source and - destination. -*/ - -ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm)); -/* - This function is equivalent to inflateEnd followed by inflateInit, - but does not free and reallocate all the internal decompression state. - The stream will keep attributes that may have been set by inflateInit2. - - inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source - stream state was inconsistent (such as zalloc or state being NULL). -*/ - -ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm, - int bits, - int value)); -/* - This function inserts bits in the inflate input stream. The intent is - that this function is used to start inflating at a bit position in the - middle of a byte. The provided bits will be used before any bytes are used - from next_in. This function should only be used with raw inflate, and - should be used before the first inflate() call after inflateInit2() or - inflateReset(). bits must be less than or equal to 16, and that many of the - least significant bits of value will be inserted in the input. - - inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source - stream state was inconsistent. -*/ - -ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm, - gz_headerp head)); -/* - inflateGetHeader() requests that gzip header information be stored in the - provided gz_header structure. inflateGetHeader() may be called after - inflateInit2() or inflateReset(), and before the first call of inflate(). - As inflate() processes the gzip stream, head->done is zero until the header - is completed, at which time head->done is set to one. If a zlib stream is - being decoded, then head->done is set to -1 to indicate that there will be - no gzip header information forthcoming. Note that Z_BLOCK can be used to - force inflate() to return immediately after header processing is complete - and before any actual data is decompressed. - - The text, time, xflags, and os fields are filled in with the gzip header - contents. hcrc is set to true if there is a header CRC. (The header CRC - was valid if done is set to one.) If extra is not Z_NULL, then extra_max - contains the maximum number of bytes to write to extra. Once done is true, - extra_len contains the actual extra field length, and extra contains the - extra field, or that field truncated if extra_max is less than extra_len. - If name is not Z_NULL, then up to name_max characters are written there, - terminated with a zero unless the length is greater than name_max. If - comment is not Z_NULL, then up to comm_max characters are written there, - terminated with a zero unless the length is greater than comm_max. When - any of extra, name, or comment are not Z_NULL and the respective field is - not present in the header, then that field is set to Z_NULL to signal its - absence. This allows the use of deflateSetHeader() with the returned - structure to duplicate the header. However if those fields are set to - allocated memory, then the application will need to save those pointers - elsewhere so that they can be eventually freed. - - If inflateGetHeader is not used, then the header information is simply - discarded. The header is always checked for validity, including the header - CRC if present. inflateReset() will reset the process to discard the header - information. The application would need to call inflateGetHeader() again to - retrieve the header from the next gzip stream. - - inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source - stream state was inconsistent. -*/ - -/* -ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits, - unsigned char FAR *window)); - - Initialize the internal stream state for decompression using inflateBack() - calls. The fields zalloc, zfree and opaque in strm must be initialized - before the call. If zalloc and zfree are Z_NULL, then the default library- - derived memory allocation routines are used. windowBits is the base two - logarithm of the window size, in the range 8..15. window is a caller - supplied buffer of that size. Except for special applications where it is - assured that deflate was used with small window sizes, windowBits must be 15 - and a 32K byte window must be supplied to be able to decompress general - deflate streams. - - See inflateBack() for the usage of these routines. - - inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of - the paramaters are invalid, Z_MEM_ERROR if the internal state could not - be allocated, or Z_VERSION_ERROR if the version of the library does not - match the version of the header file. -*/ - -typedef unsigned (*in_func) OF((void FAR *, unsigned char FAR * FAR *)); -typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned)); - -ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm, - in_func in, void FAR *in_desc, - out_func out, void FAR *out_desc)); -/* - inflateBack() does a raw inflate with a single call using a call-back - interface for input and output. This is more efficient than inflate() for - file i/o applications in that it avoids copying between the output and the - sliding window by simply making the window itself the output buffer. This - function trusts the application to not change the output buffer passed by - the output function, at least until inflateBack() returns. - - inflateBackInit() must be called first to allocate the internal state - and to initialize the state with the user-provided window buffer. - inflateBack() may then be used multiple times to inflate a complete, raw - deflate stream with each call. inflateBackEnd() is then called to free - the allocated state. - - A raw deflate stream is one with no zlib or gzip header or trailer. - This routine would normally be used in a utility that reads zip or gzip - files and writes out uncompressed files. The utility would decode the - header and process the trailer on its own, hence this routine expects - only the raw deflate stream to decompress. This is different from the - normal behavior of inflate(), which expects either a zlib or gzip header and - trailer around the deflate stream. - - inflateBack() uses two subroutines supplied by the caller that are then - called by inflateBack() for input and output. inflateBack() calls those - routines until it reads a complete deflate stream and writes out all of the - uncompressed data, or until it encounters an error. The function's - parameters and return types are defined above in the in_func and out_func - typedefs. inflateBack() will call in(in_desc, &buf) which should return the - number of bytes of provided input, and a pointer to that input in buf. If - there is no input available, in() must return zero--buf is ignored in that - case--and inflateBack() will return a buffer error. inflateBack() will call - out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. out() - should return zero on success, or non-zero on failure. If out() returns - non-zero, inflateBack() will return with an error. Neither in() nor out() - are permitted to change the contents of the window provided to - inflateBackInit(), which is also the buffer that out() uses to write from. - The length written by out() will be at most the window size. Any non-zero - amount of input may be provided by in(). - - For convenience, inflateBack() can be provided input on the first call by - setting strm->next_in and strm->avail_in. If that input is exhausted, then - in() will be called. Therefore strm->next_in must be initialized before - calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called - immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in - must also be initialized, and then if strm->avail_in is not zero, input will - initially be taken from strm->next_in[0 .. strm->avail_in - 1]. - - The in_desc and out_desc parameters of inflateBack() is passed as the - first parameter of in() and out() respectively when they are called. These - descriptors can be optionally used to pass any information that the caller- - supplied in() and out() functions need to do their job. - - On return, inflateBack() will set strm->next_in and strm->avail_in to - pass back any unused input that was provided by the last in() call. The - return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR - if in() or out() returned an error, Z_DATA_ERROR if there was a format - error in the deflate stream (in which case strm->msg is set to indicate the - nature of the error), or Z_STREAM_ERROR if the stream was not properly - initialized. In the case of Z_BUF_ERROR, an input or output error can be - distinguished using strm->next_in which will be Z_NULL only if in() returned - an error. If strm->next is not Z_NULL, then the Z_BUF_ERROR was due to - out() returning non-zero. (in() will always be called before out(), so - strm->next_in is assured to be defined if out() returns non-zero.) Note - that inflateBack() cannot return Z_OK. -*/ - -ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm)); -/* - All memory allocated by inflateBackInit() is freed. - - inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream - state was inconsistent. -*/ - -ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void)); -/* Return flags indicating compile-time options. - - Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other: - 1.0: size of uInt - 3.2: size of uLong - 5.4: size of voidpf (pointer) - 7.6: size of z_off_t - - Compiler, assembler, and debug options: - 8: DEBUG - 9: ASMV or ASMINF -- use ASM code - 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention - 11: 0 (reserved) - - One-time table building (smaller code, but not thread-safe if true): - 12: BUILDFIXED -- build static block decoding tables when needed - 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed - 14,15: 0 (reserved) - - Library content (indicates missing functionality): - 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking - deflate code when not needed) - 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect - and decode gzip streams (to avoid linking crc code) - 18-19: 0 (reserved) - - Operation variations (changes in library functionality): - 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate - 21: FASTEST -- deflate algorithm with only one, lowest compression level - 22,23: 0 (reserved) - - The sprintf variant used by gzprintf (zero is best): - 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format - 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure! - 26: 0 = returns value, 1 = void -- 1 means inferred string length returned - - Remainder: - 27-31: 0 (reserved) - */ - - - /* utility functions */ - -/* - The following utility functions are implemented on top of the - basic stream-oriented functions. To simplify the interface, some - default options are assumed (compression level and memory usage, - standard memory allocation functions). The source code of these - utility functions can easily be modified if you need special options. -*/ - -ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen, - const Bytef *source, uLong sourceLen)); -/* - Compresses the source buffer into the destination buffer. sourceLen is - the byte length of the source buffer. Upon entry, destLen is the total - size of the destination buffer, which must be at least the value returned - by compressBound(sourceLen). Upon exit, destLen is the actual size of the - compressed buffer. - This function can be used to compress a whole file at once if the - input file is mmap'ed. - compress returns Z_OK if success, Z_MEM_ERROR if there was not - enough memory, Z_BUF_ERROR if there was not enough room in the output - buffer. -*/ - -ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen, - const Bytef *source, uLong sourceLen, - int level)); -/* - Compresses the source buffer into the destination buffer. The level - parameter has the same meaning as in deflateInit. sourceLen is the byte - length of the source buffer. Upon entry, destLen is the total size of the - destination buffer, which must be at least the value returned by - compressBound(sourceLen). Upon exit, destLen is the actual size of the - compressed buffer. - - compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough - memory, Z_BUF_ERROR if there was not enough room in the output buffer, - Z_STREAM_ERROR if the level parameter is invalid. -*/ - -ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen)); -/* - compressBound() returns an upper bound on the compressed size after - compress() or compress2() on sourceLen bytes. It would be used before - a compress() or compress2() call to allocate the destination buffer. -*/ - -ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen, - const Bytef *source, uLong sourceLen)); -/* - Decompresses the source buffer into the destination buffer. sourceLen is - the byte length of the source buffer. Upon entry, destLen is the total - size of the destination buffer, which must be large enough to hold the - entire uncompressed data. (The size of the uncompressed data must have - been saved previously by the compressor and transmitted to the decompressor - by some mechanism outside the scope of this compression library.) - Upon exit, destLen is the actual size of the compressed buffer. - This function can be used to decompress a whole file at once if the - input file is mmap'ed. - - uncompress returns Z_OK if success, Z_MEM_ERROR if there was not - enough memory, Z_BUF_ERROR if there was not enough room in the output - buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete. -*/ - - -typedef voidp gzFile; - -ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode)); -/* - Opens a gzip (.gz) file for reading or writing. The mode parameter - is as in fopen ("rb" or "wb") but can also include a compression level - ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for - Huffman only compression as in "wb1h", or 'R' for run-length encoding - as in "wb1R". (See the description of deflateInit2 for more information - about the strategy parameter.) - - gzopen can be used to read a file which is not in gzip format; in this - case gzread will directly read from the file without decompression. - - gzopen returns NULL if the file could not be opened or if there was - insufficient memory to allocate the (de)compression state; errno - can be checked to distinguish the two cases (if errno is zero, the - zlib error is Z_MEM_ERROR). */ - -ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode)); -/* - gzdopen() associates a gzFile with the file descriptor fd. File - descriptors are obtained from calls like open, dup, creat, pipe or - fileno (in the file has been previously opened with fopen). - The mode parameter is as in gzopen. - The next call of gzclose on the returned gzFile will also close the - file descriptor fd, just like fclose(fdopen(fd), mode) closes the file - descriptor fd. If you want to keep fd open, use gzdopen(dup(fd), mode). - gzdopen returns NULL if there was insufficient memory to allocate - the (de)compression state. -*/ - -ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy)); -/* - Dynamically update the compression level or strategy. See the description - of deflateInit2 for the meaning of these parameters. - gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not - opened for writing. -*/ - -ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len)); -/* - Reads the given number of uncompressed bytes from the compressed file. - If the input file was not in gzip format, gzread copies the given number - of bytes into the buffer. - gzread returns the number of uncompressed bytes actually read (0 for - end of file, -1 for error). */ - -ZEXTERN int ZEXPORT gzwrite OF((gzFile file, - voidpc buf, unsigned len)); -/* - Writes the given number of uncompressed bytes into the compressed file. - gzwrite returns the number of uncompressed bytes actually written - (0 in case of error). -*/ - -ZEXTERN int ZEXPORTVA gzprintf OF((gzFile file, const char *format, ...)); -/* - Converts, formats, and writes the args to the compressed file under - control of the format string, as in fprintf. gzprintf returns the number of - uncompressed bytes actually written (0 in case of error). The number of - uncompressed bytes written is limited to 4095. The caller should assure that - this limit is not exceeded. If it is exceeded, then gzprintf() will return - return an error (0) with nothing written. In this case, there may also be a - buffer overflow with unpredictable consequences, which is possible only if - zlib was compiled with the insecure functions sprintf() or vsprintf() - because the secure snprintf() or vsnprintf() functions were not available. -*/ - -ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s)); -/* - Writes the given null-terminated string to the compressed file, excluding - the terminating null character. - gzputs returns the number of characters written, or -1 in case of error. -*/ - -ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len)); -/* - Reads bytes from the compressed file until len-1 characters are read, or - a newline character is read and transferred to buf, or an end-of-file - condition is encountered. The string is then terminated with a null - character. - gzgets returns buf, or Z_NULL in case of error. -*/ - -ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c)); -/* - Writes c, converted to an unsigned char, into the compressed file. - gzputc returns the value that was written, or -1 in case of error. -*/ - -ZEXTERN int ZEXPORT gzgetc OF((gzFile file)); -/* - Reads one byte from the compressed file. gzgetc returns this byte - or -1 in case of end of file or error. -*/ - -ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file)); -/* - Push one character back onto the stream to be read again later. - Only one character of push-back is allowed. gzungetc() returns the - character pushed, or -1 on failure. gzungetc() will fail if a - character has been pushed but not read yet, or if c is -1. The pushed - character will be discarded if the stream is repositioned with gzseek() - or gzrewind(). -*/ - -ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush)); -/* - Flushes all pending output into the compressed file. The parameter - flush is as in the deflate() function. The return value is the zlib - error number (see function gzerror below). gzflush returns Z_OK if - the flush parameter is Z_FINISH and all output could be flushed. - gzflush should be called only when strictly necessary because it can - degrade compression. -*/ - -ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file, - z_off_t offset, int whence)); -/* - Sets the starting position for the next gzread or gzwrite on the - given compressed file. The offset represents a number of bytes in the - uncompressed data stream. The whence parameter is defined as in lseek(2); - the value SEEK_END is not supported. - If the file is opened for reading, this function is emulated but can be - extremely slow. If the file is opened for writing, only forward seeks are - supported; gzseek then compresses a sequence of zeroes up to the new - starting position. - - gzseek returns the resulting offset location as measured in bytes from - the beginning of the uncompressed stream, or -1 in case of error, in - particular if the file is opened for writing and the new starting position - would be before the current position. -*/ - -ZEXTERN int ZEXPORT gzrewind OF((gzFile file)); -/* - Rewinds the given file. This function is supported only for reading. - - gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET) -*/ - -ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file)); -/* - Returns the starting position for the next gzread or gzwrite on the - given compressed file. This position represents a number of bytes in the - uncompressed data stream. - - gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR) -*/ - -ZEXTERN int ZEXPORT gzeof OF((gzFile file)); -/* - Returns 1 when EOF has previously been detected reading the given - input stream, otherwise zero. -*/ - -ZEXTERN int ZEXPORT gzdirect OF((gzFile file)); -/* - Returns 1 if file is being read directly without decompression, otherwise - zero. -*/ - -ZEXTERN int ZEXPORT gzclose OF((gzFile file)); -/* - Flushes all pending output if necessary, closes the compressed file - and deallocates all the (de)compression state. The return value is the zlib - error number (see function gzerror below). -*/ - -ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum)); -/* - Returns the error message for the last error which occurred on the - given compressed file. errnum is set to zlib error number. If an - error occurred in the file system and not in the compression library, - errnum is set to Z_ERRNO and the application may consult errno - to get the exact error code. -*/ - -ZEXTERN void ZEXPORT gzclearerr OF((gzFile file)); -/* - Clears the error and end-of-file flags for file. This is analogous to the - clearerr() function in stdio. This is useful for continuing to read a gzip - file that is being written concurrently. -*/ - - /* checksum functions */ - -/* - These functions are not related to compression but are exported - anyway because they might be useful in applications using the - compression library. -*/ - -ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len)); -/* - Update a running Adler-32 checksum with the bytes buf[0..len-1] and - return the updated checksum. If buf is NULL, this function returns - the required initial value for the checksum. - An Adler-32 checksum is almost as reliable as a CRC32 but can be computed - much faster. Usage example: - - uLong adler = adler32(0L, Z_NULL, 0); - - while (read_buffer(buffer, length) != EOF) { - adler = adler32(adler, buffer, length); - } - if (adler != original_adler) error(); -*/ - -ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2, - z_off_t len2)); -/* - Combine two Adler-32 checksums into one. For two sequences of bytes, seq1 - and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for - each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of - seq1 and seq2 concatenated, requiring only adler1, adler2, and len2. -*/ - -ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len)); -/* - Update a running CRC-32 with the bytes buf[0..len-1] and return the - updated CRC-32. If buf is NULL, this function returns the required initial - value for the for the crc. Pre- and post-conditioning (one's complement) is - performed within this function so it shouldn't be done by the application. - Usage example: - - uLong crc = crc32(0L, Z_NULL, 0); - - while (read_buffer(buffer, length) != EOF) { - crc = crc32(crc, buffer, length); - } - if (crc != original_crc) error(); -*/ - -ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2)); - -/* - Combine two CRC-32 check values into one. For two sequences of bytes, - seq1 and seq2 with lengths len1 and len2, CRC-32 check values were - calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32 - check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and - len2. -*/ - - - /* various hacks, don't look :) */ - -/* deflateInit and inflateInit are macros to allow checking the zlib version - * and the compiler's view of z_stream: - */ -ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level, - const char *version, int stream_size)); -ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm, - const char *version, int stream_size)); -ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method, - int windowBits, int memLevel, - int strategy, const char *version, - int stream_size)); -ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits, - const char *version, int stream_size)); -ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits, - unsigned char FAR *window, - const char *version, - int stream_size)); -#define deflateInit(strm, level) \ - deflateInit_((strm), (level), ZLIB_VERSION, sizeof(z_stream)) -#define inflateInit(strm) \ - inflateInit_((strm), ZLIB_VERSION, sizeof(z_stream)) -#define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \ - deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\ - (strategy), ZLIB_VERSION, sizeof(z_stream)) -#define inflateInit2(strm, windowBits) \ - inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream)) -#define inflateBackInit(strm, windowBits, window) \ - inflateBackInit_((strm), (windowBits), (window), \ - ZLIB_VERSION, sizeof(z_stream)) - - -#if !defined(ZUTIL_H) && !defined(NO_DUMMY_DECL) - struct internal_state {int dummy;}; /* hack for buggy compilers */ -#endif - -ZEXTERN const char * ZEXPORT zError OF((int)); -ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp z)); -ZEXTERN const uLongf * ZEXPORT get_crc_table OF((void)); - -#ifdef __cplusplus -} -#endif - -#endif /* ZLIB_H */ +/* zlib.h -- interface of the 'zlib' general purpose compression library + version 1.2.3, July 18th, 2005 + + Copyright (C) 1995-2005 Jean-loup Gailly and Mark Adler + + 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. + + Jean-loup Gailly Mark Adler + jloup@gzip.org madler@alumni.caltech.edu + + + The data format used by the zlib library is described by RFCs (Request for + Comments) 1950 to 1952 in the files http://www.ietf.org/rfc/rfc1950.txt + (zlib format), rfc1951.txt (deflate format) and rfc1952.txt (gzip format). +*/ + +#ifndef ZLIB_H +#define ZLIB_H + +#include "zconf.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define ZLIB_VERSION "1.2.3" +#define ZLIB_VERNUM 0x1230 + +/* + The 'zlib' compression library provides in-memory compression and + decompression functions, including integrity checks of the uncompressed + data. This version of the library supports only one compression method + (deflation) but other algorithms will be added later and will have the same + stream interface. + + Compression can be done in a single step if the buffers are large + enough (for example if an input file is mmap'ed), or can be done by + repeated calls of the compression function. In the latter case, the + application must provide more input and/or consume the output + (providing more output space) before each call. + + The compressed data format used by default by the in-memory functions is + the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped + around a deflate stream, which is itself documented in RFC 1951. + + The library also supports reading and writing files in gzip (.gz) format + with an interface similar to that of stdio using the functions that start + with "gz". The gzip format is different from the zlib format. gzip is a + gzip wrapper, documented in RFC 1952, wrapped around a deflate stream. + + This library can optionally read and write gzip streams in memory as well. + + The zlib format was designed to be compact and fast for use in memory + and on communications channels. The gzip format was designed for single- + file compression on file systems, has a larger header than zlib to maintain + directory information, and uses a different, slower check method than zlib. + + The library does not install any signal handler. The decoder checks + the consistency of the compressed data, so the library should never + crash even in case of corrupted input. +*/ + +typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size)); +typedef void (*free_func) OF((voidpf opaque, voidpf address)); + +struct internal_state; + +typedef struct z_stream_s { + Bytef *next_in; /* next input byte */ + uInt avail_in; /* number of bytes available at next_in */ + uLong total_in; /* total nb of input bytes read so far */ + + Bytef *next_out; /* next output byte should be put there */ + uInt avail_out; /* remaining free space at next_out */ + uLong total_out; /* total nb of bytes output so far */ + + char *msg; /* last error message, NULL if no error */ + struct internal_state FAR *state; /* not visible by applications */ + + alloc_func zalloc; /* used to allocate the internal state */ + free_func zfree; /* used to free the internal state */ + voidpf opaque; /* private data object passed to zalloc and zfree */ + + int data_type; /* best guess about the data type: binary or text */ + uLong adler; /* adler32 value of the uncompressed data */ + uLong reserved; /* reserved for future use */ +} z_stream; + +typedef z_stream FAR *z_streamp; + +/* + gzip header information passed to and from zlib routines. See RFC 1952 + for more details on the meanings of these fields. +*/ +typedef struct gz_header_s { + int text; /* true if compressed data believed to be text */ + uLong time; /* modification time */ + int xflags; /* extra flags (not used when writing a gzip file) */ + int os; /* operating system */ + Bytef *extra; /* pointer to extra field or Z_NULL if none */ + uInt extra_len; /* extra field length (valid if extra != Z_NULL) */ + uInt extra_max; /* space at extra (only when reading header) */ + Bytef *name; /* pointer to zero-terminated file name or Z_NULL */ + uInt name_max; /* space at name (only when reading header) */ + Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */ + uInt comm_max; /* space at comment (only when reading header) */ + int hcrc; /* true if there was or will be a header crc */ + int done; /* true when done reading gzip header (not used + when writing a gzip file) */ +} gz_header; + +typedef gz_header FAR *gz_headerp; + +/* + The application must update next_in and avail_in when avail_in has + dropped to zero. It must update next_out and avail_out when avail_out + has dropped to zero. The application must initialize zalloc, zfree and + opaque before calling the init function. All other fields are set by the + compression library and must not be updated by the application. + + The opaque value provided by the application will be passed as the first + parameter for calls of zalloc and zfree. This can be useful for custom + memory management. The compression library attaches no meaning to the + opaque value. + + zalloc must return Z_NULL if there is not enough memory for the object. + If zlib is used in a multi-threaded application, zalloc and zfree must be + thread safe. + + On 16-bit systems, the functions zalloc and zfree must be able to allocate + exactly 65536 bytes, but will not be required to allocate more than this + if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS, + pointers returned by zalloc for objects of exactly 65536 bytes *must* + have their offset normalized to zero. The default allocation function + provided by this library ensures this (see zutil.c). To reduce memory + requirements and avoid any allocation of 64K objects, at the expense of + compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h). + + The fields total_in and total_out can be used for statistics or + progress reports. After compression, total_in holds the total size of + the uncompressed data and may be saved for use in the decompressor + (particularly if the decompressor wants to decompress everything in + a single step). +*/ + + /* constants */ + +#define Z_NO_FLUSH 0 +#define Z_PARTIAL_FLUSH 1 /* will be removed, use Z_SYNC_FLUSH instead */ +#define Z_SYNC_FLUSH 2 +#define Z_FULL_FLUSH 3 +#define Z_FINISH 4 +#define Z_BLOCK 5 +/* Allowed flush values; see deflate() and inflate() below for details */ + +#define Z_OK 0 +#define Z_STREAM_END 1 +#define Z_NEED_DICT 2 +#define Z_ERRNO (-1) +#define Z_STREAM_ERROR (-2) +#define Z_DATA_ERROR (-3) +#define Z_MEM_ERROR (-4) +#define Z_BUF_ERROR (-5) +#define Z_VERSION_ERROR (-6) +/* Return codes for the compression/decompression functions. Negative + * values are errors, positive values are used for special but normal events. + */ + +#define Z_NO_COMPRESSION 0 +#define Z_BEST_SPEED 1 +#define Z_BEST_COMPRESSION 9 +#define Z_DEFAULT_COMPRESSION (-1) +/* compression levels */ + +#define Z_FILTERED 1 +#define Z_HUFFMAN_ONLY 2 +#define Z_RLE 3 +#define Z_FIXED 4 +#define Z_DEFAULT_STRATEGY 0 +/* compression strategy; see deflateInit2() below for details */ + +#define Z_BINARY 0 +#define Z_TEXT 1 +#define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */ +#define Z_UNKNOWN 2 +/* Possible values of the data_type field (though see inflate()) */ + +#define Z_DEFLATED 8 +/* The deflate compression method (the only one supported in this version) */ + +#define Z_NULL 0 /* for initializing zalloc, zfree, opaque */ + +#define zlib_version zlibVersion() +/* for compatibility with versions < 1.0.2 */ + + /* basic functions */ + +ZEXTERN const char * ZEXPORT zlibVersion OF((void)); +/* The application can compare zlibVersion and ZLIB_VERSION for consistency. + If the first character differs, the library code actually used is + not compatible with the zlib.h header file used by the application. + This check is automatically made by deflateInit and inflateInit. + */ + +/* +ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level)); + + Initializes the internal stream state for compression. The fields + zalloc, zfree and opaque must be initialized before by the caller. + If zalloc and zfree are set to Z_NULL, deflateInit updates them to + use default allocation functions. + + The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9: + 1 gives best speed, 9 gives best compression, 0 gives no compression at + all (the input data is simply copied a block at a time). + Z_DEFAULT_COMPRESSION requests a default compromise between speed and + compression (currently equivalent to level 6). + + deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_STREAM_ERROR if level is not a valid compression level, + Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible + with the version assumed by the caller (ZLIB_VERSION). + msg is set to null if there is no error message. deflateInit does not + perform any compression: this will be done by deflate(). +*/ + + +ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush)); +/* + deflate compresses as much data as possible, and stops when the input + buffer becomes empty or the output buffer becomes full. It may introduce some + output latency (reading input without producing any output) except when + forced to flush. + + The detailed semantics are as follows. deflate performs one or both of the + following actions: + + - Compress more input starting at next_in and update next_in and avail_in + accordingly. If not all input can be processed (because there is not + enough room in the output buffer), next_in and avail_in are updated and + processing will resume at this point for the next call of deflate(). + + - Provide more output starting at next_out and update next_out and avail_out + accordingly. This action is forced if the parameter flush is non zero. + Forcing flush frequently degrades the compression ratio, so this parameter + should be set only when necessary (in interactive applications). + Some output may be provided even if flush is not set. + + Before the call of deflate(), the application should ensure that at least + one of the actions is possible, by providing more input and/or consuming + more output, and updating avail_in or avail_out accordingly; avail_out + should never be zero before the call. The application can consume the + compressed output when it wants, for example when the output buffer is full + (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK + and with zero avail_out, it must be called again after making room in the + output buffer because there might be more output pending. + + Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to + decide how much data to accumualte before producing output, in order to + maximize compression. + + If the parameter flush is set to Z_SYNC_FLUSH, all pending output is + flushed to the output buffer and the output is aligned on a byte boundary, so + that the decompressor can get all input data available so far. (In particular + avail_in is zero after the call if enough output space has been provided + before the call.) Flushing may degrade compression for some compression + algorithms and so it should be used only when necessary. + + If flush is set to Z_FULL_FLUSH, all output is flushed as with + Z_SYNC_FLUSH, and the compression state is reset so that decompression can + restart from this point if previous compressed data has been damaged or if + random access is desired. Using Z_FULL_FLUSH too often can seriously degrade + compression. + + If deflate returns with avail_out == 0, this function must be called again + with the same value of the flush parameter and more output space (updated + avail_out), until the flush is complete (deflate returns with non-zero + avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that + avail_out is greater than six to avoid repeated flush markers due to + avail_out == 0 on return. + + If the parameter flush is set to Z_FINISH, pending input is processed, + pending output is flushed and deflate returns with Z_STREAM_END if there + was enough output space; if deflate returns with Z_OK, this function must be + called again with Z_FINISH and more output space (updated avail_out) but no + more input data, until it returns with Z_STREAM_END or an error. After + deflate has returned Z_STREAM_END, the only possible operations on the + stream are deflateReset or deflateEnd. + + Z_FINISH can be used immediately after deflateInit if all the compression + is to be done in a single step. In this case, avail_out must be at least + the value returned by deflateBound (see below). If deflate does not return + Z_STREAM_END, then it must be called again as described above. + + deflate() sets strm->adler to the adler32 checksum of all input read + so far (that is, total_in bytes). + + deflate() may update strm->data_type if it can make a good guess about + the input data type (Z_BINARY or Z_TEXT). In doubt, the data is considered + binary. This field is only for information purposes and does not affect + the compression algorithm in any manner. + + deflate() returns Z_OK if some progress has been made (more input + processed or more output produced), Z_STREAM_END if all input has been + consumed and all output has been produced (only when flush is set to + Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example + if next_in or next_out was NULL), Z_BUF_ERROR if no progress is possible + (for example avail_in or avail_out was zero). Note that Z_BUF_ERROR is not + fatal, and deflate() can be called again with more input and more output + space to continue compressing. +*/ + + +ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm)); +/* + All dynamically allocated data structures for this stream are freed. + This function discards any unprocessed input and does not flush any + pending output. + + deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the + stream state was inconsistent, Z_DATA_ERROR if the stream was freed + prematurely (some input or output was discarded). In the error case, + msg may be set but then points to a static string (which must not be + deallocated). +*/ + + +/* +ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm)); + + Initializes the internal stream state for decompression. The fields + next_in, avail_in, zalloc, zfree and opaque must be initialized before by + the caller. If next_in is not Z_NULL and avail_in is large enough (the exact + value depends on the compression method), inflateInit determines the + compression method from the zlib header and allocates all data structures + accordingly; otherwise the allocation will be deferred to the first call of + inflate. If zalloc and zfree are set to Z_NULL, inflateInit updates them to + use default allocation functions. + + inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_VERSION_ERROR if the zlib library version is incompatible with the + version assumed by the caller. msg is set to null if there is no error + message. inflateInit does not perform any decompression apart from reading + the zlib header if present: this will be done by inflate(). (So next_in and + avail_in may be modified, but next_out and avail_out are unchanged.) +*/ + + +ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush)); +/* + inflate decompresses as much data as possible, and stops when the input + buffer becomes empty or the output buffer becomes full. It may introduce + some output latency (reading input without producing any output) except when + forced to flush. + + The detailed semantics are as follows. inflate performs one or both of the + following actions: + + - Decompress more input starting at next_in and update next_in and avail_in + accordingly. If not all input can be processed (because there is not + enough room in the output buffer), next_in is updated and processing + will resume at this point for the next call of inflate(). + + - Provide more output starting at next_out and update next_out and avail_out + accordingly. inflate() provides as much output as possible, until there + is no more input data or no more space in the output buffer (see below + about the flush parameter). + + Before the call of inflate(), the application should ensure that at least + one of the actions is possible, by providing more input and/or consuming + more output, and updating the next_* and avail_* values accordingly. + The application can consume the uncompressed output when it wants, for + example when the output buffer is full (avail_out == 0), or after each + call of inflate(). If inflate returns Z_OK and with zero avail_out, it + must be called again after making room in the output buffer because there + might be more output pending. + + The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH, + Z_FINISH, or Z_BLOCK. Z_SYNC_FLUSH requests that inflate() flush as much + output as possible to the output buffer. Z_BLOCK requests that inflate() stop + if and when it gets to the next deflate block boundary. When decoding the + zlib or gzip format, this will cause inflate() to return immediately after + the header and before the first block. When doing a raw inflate, inflate() + will go ahead and process the first block, and will return when it gets to + the end of that block, or when it runs out of data. + + The Z_BLOCK option assists in appending to or combining deflate streams. + Also to assist in this, on return inflate() will set strm->data_type to the + number of unused bits in the last byte taken from strm->next_in, plus 64 + if inflate() is currently decoding the last block in the deflate stream, + plus 128 if inflate() returned immediately after decoding an end-of-block + code or decoding the complete header up to just before the first byte of the + deflate stream. The end-of-block will not be indicated until all of the + uncompressed data from that block has been written to strm->next_out. The + number of unused bits may in general be greater than seven, except when + bit 7 of data_type is set, in which case the number of unused bits will be + less than eight. + + inflate() should normally be called until it returns Z_STREAM_END or an + error. However if all decompression is to be performed in a single step + (a single call of inflate), the parameter flush should be set to + Z_FINISH. In this case all pending input is processed and all pending + output is flushed; avail_out must be large enough to hold all the + uncompressed data. (The size of the uncompressed data may have been saved + by the compressor for this purpose.) The next operation on this stream must + be inflateEnd to deallocate the decompression state. The use of Z_FINISH + is never required, but can be used to inform inflate that a faster approach + may be used for the single inflate() call. + + In this implementation, inflate() always flushes as much output as + possible to the output buffer, and always uses the faster approach on the + first call. So the only effect of the flush parameter in this implementation + is on the return value of inflate(), as noted below, or when it returns early + because Z_BLOCK is used. + + If a preset dictionary is needed after this call (see inflateSetDictionary + below), inflate sets strm->adler to the adler32 checksum of the dictionary + chosen by the compressor and returns Z_NEED_DICT; otherwise it sets + strm->adler to the adler32 checksum of all output produced so far (that is, + total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described + below. At the end of the stream, inflate() checks that its computed adler32 + checksum is equal to that saved by the compressor and returns Z_STREAM_END + only if the checksum is correct. + + inflate() will decompress and check either zlib-wrapped or gzip-wrapped + deflate data. The header type is detected automatically. Any information + contained in the gzip header is not retained, so applications that need that + information should instead use raw inflate, see inflateInit2() below, or + inflateBack() and perform their own processing of the gzip header and + trailer. + + inflate() returns Z_OK if some progress has been made (more input processed + or more output produced), Z_STREAM_END if the end of the compressed data has + been reached and all uncompressed output has been produced, Z_NEED_DICT if a + preset dictionary is needed at this point, Z_DATA_ERROR if the input data was + corrupted (input stream not conforming to the zlib format or incorrect check + value), Z_STREAM_ERROR if the stream structure was inconsistent (for example + if next_in or next_out was NULL), Z_MEM_ERROR if there was not enough memory, + Z_BUF_ERROR if no progress is possible or if there was not enough room in the + output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and + inflate() can be called again with more input and more output space to + continue decompressing. If Z_DATA_ERROR is returned, the application may then + call inflateSync() to look for a good compression block if a partial recovery + of the data is desired. +*/ + + +ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm)); +/* + All dynamically allocated data structures for this stream are freed. + This function discards any unprocessed input and does not flush any + pending output. + + inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state + was inconsistent. In the error case, msg may be set but then points to a + static string (which must not be deallocated). +*/ + + /* Advanced functions */ + +/* + The following functions are needed only in some special applications. +*/ + +/* +ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm, + int level, + int method, + int windowBits, + int memLevel, + int strategy)); + + This is another version of deflateInit with more compression options. The + fields next_in, zalloc, zfree and opaque must be initialized before by + the caller. + + The method parameter is the compression method. It must be Z_DEFLATED in + this version of the library. + + The windowBits parameter is the base two logarithm of the window size + (the size of the history buffer). It should be in the range 8..15 for this + version of the library. Larger values of this parameter result in better + compression at the expense of memory usage. The default value is 15 if + deflateInit is used instead. + + windowBits can also be -8..-15 for raw deflate. In this case, -windowBits + determines the window size. deflate() will then generate raw deflate data + with no zlib header or trailer, and will not compute an adler32 check value. + + windowBits can also be greater than 15 for optional gzip encoding. Add + 16 to windowBits to write a simple gzip header and trailer around the + compressed data instead of a zlib wrapper. The gzip header will have no + file name, no extra data, no comment, no modification time (set to zero), + no header crc, and the operating system will be set to 255 (unknown). If a + gzip stream is being written, strm->adler is a crc32 instead of an adler32. + + The memLevel parameter specifies how much memory should be allocated + for the internal compression state. memLevel=1 uses minimum memory but + is slow and reduces compression ratio; memLevel=9 uses maximum memory + for optimal speed. The default value is 8. See zconf.h for total memory + usage as a function of windowBits and memLevel. + + The strategy parameter is used to tune the compression algorithm. Use the + value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a + filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no + string match), or Z_RLE to limit match distances to one (run-length + encoding). Filtered data consists mostly of small values with a somewhat + random distribution. In this case, the compression algorithm is tuned to + compress them better. The effect of Z_FILTERED is to force more Huffman + coding and less string matching; it is somewhat intermediate between + Z_DEFAULT and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as fast as + Z_HUFFMAN_ONLY, but give better compression for PNG image data. The strategy + parameter only affects the compression ratio but not the correctness of the + compressed output even if it is not set appropriately. Z_FIXED prevents the + use of dynamic Huffman codes, allowing for a simpler decoder for special + applications. + + deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_STREAM_ERROR if a parameter is invalid (such as an invalid + method). msg is set to null if there is no error message. deflateInit2 does + not perform any compression: this will be done by deflate(). +*/ + +ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm, + const Bytef *dictionary, + uInt dictLength)); +/* + Initializes the compression dictionary from the given byte sequence + without producing any compressed output. This function must be called + immediately after deflateInit, deflateInit2 or deflateReset, before any + call of deflate. The compressor and decompressor must use exactly the same + dictionary (see inflateSetDictionary). + + The dictionary should consist of strings (byte sequences) that are likely + to be encountered later in the data to be compressed, with the most commonly + used strings preferably put towards the end of the dictionary. Using a + dictionary is most useful when the data to be compressed is short and can be + predicted with good accuracy; the data can then be compressed better than + with the default empty dictionary. + + Depending on the size of the compression data structures selected by + deflateInit or deflateInit2, a part of the dictionary may in effect be + discarded, for example if the dictionary is larger than the window size in + deflate or deflate2. Thus the strings most likely to be useful should be + put at the end of the dictionary, not at the front. In addition, the + current implementation of deflate will use at most the window size minus + 262 bytes of the provided dictionary. + + Upon return of this function, strm->adler is set to the adler32 value + of the dictionary; the decompressor may later use this value to determine + which dictionary has been used by the compressor. (The adler32 value + applies to the whole dictionary even if only a subset of the dictionary is + actually used by the compressor.) If a raw deflate was requested, then the + adler32 value is not computed and strm->adler is not set. + + deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a + parameter is invalid (such as NULL dictionary) or the stream state is + inconsistent (for example if deflate has already been called for this stream + or if the compression method is bsort). deflateSetDictionary does not + perform any compression: this will be done by deflate(). +*/ + +ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest, + z_streamp source)); +/* + Sets the destination stream as a complete copy of the source stream. + + This function can be useful when several compression strategies will be + tried, for example when there are several ways of pre-processing the input + data with a filter. The streams that will be discarded should then be freed + by calling deflateEnd. Note that deflateCopy duplicates the internal + compression state which can be quite large, so this strategy is slow and + can consume lots of memory. + + deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_STREAM_ERROR if the source stream state was inconsistent + (such as zalloc being NULL). msg is left unchanged in both source and + destination. +*/ + +ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm)); +/* + This function is equivalent to deflateEnd followed by deflateInit, + but does not free and reallocate all the internal compression state. + The stream will keep the same compression level and any other attributes + that may have been set by deflateInit2. + + deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent (such as zalloc or state being NULL). +*/ + +ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm, + int level, + int strategy)); +/* + Dynamically update the compression level and compression strategy. The + interpretation of level and strategy is as in deflateInit2. This can be + used to switch between compression and straight copy of the input data, or + to switch to a different kind of input data requiring a different + strategy. If the compression level is changed, the input available so far + is compressed with the old level (and may be flushed); the new level will + take effect only at the next call of deflate(). + + Before the call of deflateParams, the stream state must be set as for + a call of deflate(), since the currently available input may have to + be compressed and flushed. In particular, strm->avail_out must be non-zero. + + deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source + stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR + if strm->avail_out was zero. +*/ + +ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm, + int good_length, + int max_lazy, + int nice_length, + int max_chain)); +/* + Fine tune deflate's internal compression parameters. This should only be + used by someone who understands the algorithm used by zlib's deflate for + searching for the best matching string, and even then only by the most + fanatic optimizer trying to squeeze out the last compressed bit for their + specific input data. Read the deflate.c source code for the meaning of the + max_lazy, good_length, nice_length, and max_chain parameters. + + deflateTune() can be called after deflateInit() or deflateInit2(), and + returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream. + */ + +ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm, + uLong sourceLen)); +/* + deflateBound() returns an upper bound on the compressed size after + deflation of sourceLen bytes. It must be called after deflateInit() + or deflateInit2(). This would be used to allocate an output buffer + for deflation in a single pass, and so would be called before deflate(). +*/ + +ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm, + int bits, + int value)); +/* + deflatePrime() inserts bits in the deflate output stream. The intent + is that this function is used to start off the deflate output with the + bits leftover from a previous deflate stream when appending to it. As such, + this function can only be used for raw deflate, and must be used before the + first deflate() call after a deflateInit2() or deflateReset(). bits must be + less than or equal to 16, and that many of the least significant bits of + value will be inserted in the output. + + deflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent. +*/ + +ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm, + gz_headerp head)); +/* + deflateSetHeader() provides gzip header information for when a gzip + stream is requested by deflateInit2(). deflateSetHeader() may be called + after deflateInit2() or deflateReset() and before the first call of + deflate(). The text, time, os, extra field, name, and comment information + in the provided gz_header structure are written to the gzip header (xflag is + ignored -- the extra flags are set according to the compression level). The + caller must assure that, if not Z_NULL, name and comment are terminated with + a zero byte, and that if extra is not Z_NULL, that extra_len bytes are + available there. If hcrc is true, a gzip header crc is included. Note that + the current versions of the command-line version of gzip (up through version + 1.3.x) do not support header crc's, and will report that it is a "multi-part + gzip file" and give up. + + If deflateSetHeader is not used, the default gzip header has text false, + the time set to zero, and os set to 255, with no extra, name, or comment + fields. The gzip header is returned to the default state by deflateReset(). + + deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent. +*/ + +/* +ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm, + int windowBits)); + + This is another version of inflateInit with an extra parameter. The + fields next_in, avail_in, zalloc, zfree and opaque must be initialized + before by the caller. + + The windowBits parameter is the base two logarithm of the maximum window + size (the size of the history buffer). It should be in the range 8..15 for + this version of the library. The default value is 15 if inflateInit is used + instead. windowBits must be greater than or equal to the windowBits value + provided to deflateInit2() while compressing, or it must be equal to 15 if + deflateInit2() was not used. If a compressed stream with a larger window + size is given as input, inflate() will return with the error code + Z_DATA_ERROR instead of trying to allocate a larger window. + + windowBits can also be -8..-15 for raw inflate. In this case, -windowBits + determines the window size. inflate() will then process raw deflate data, + not looking for a zlib or gzip header, not generating a check value, and not + looking for any check values for comparison at the end of the stream. This + is for use with other formats that use the deflate compressed data format + such as zip. Those formats provide their own check values. If a custom + format is developed using the raw deflate format for compressed data, it is + recommended that a check value such as an adler32 or a crc32 be applied to + the uncompressed data as is done in the zlib, gzip, and zip formats. For + most applications, the zlib format should be used as is. Note that comments + above on the use in deflateInit2() applies to the magnitude of windowBits. + + windowBits can also be greater than 15 for optional gzip decoding. Add + 32 to windowBits to enable zlib and gzip decoding with automatic header + detection, or add 16 to decode only the gzip format (the zlib format will + return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is + a crc32 instead of an adler32. + + inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_STREAM_ERROR if a parameter is invalid (such as a null strm). msg + is set to null if there is no error message. inflateInit2 does not perform + any decompression apart from reading the zlib header if present: this will + be done by inflate(). (So next_in and avail_in may be modified, but next_out + and avail_out are unchanged.) +*/ + +ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm, + const Bytef *dictionary, + uInt dictLength)); +/* + Initializes the decompression dictionary from the given uncompressed byte + sequence. This function must be called immediately after a call of inflate, + if that call returned Z_NEED_DICT. The dictionary chosen by the compressor + can be determined from the adler32 value returned by that call of inflate. + The compressor and decompressor must use exactly the same dictionary (see + deflateSetDictionary). For raw inflate, this function can be called + immediately after inflateInit2() or inflateReset() and before any call of + inflate() to set the dictionary. The application must insure that the + dictionary that was used for compression is provided. + + inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a + parameter is invalid (such as NULL dictionary) or the stream state is + inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the + expected one (incorrect adler32 value). inflateSetDictionary does not + perform any decompression: this will be done by subsequent calls of + inflate(). +*/ + +ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm)); +/* + Skips invalid compressed data until a full flush point (see above the + description of deflate with Z_FULL_FLUSH) can be found, or until all + available input is skipped. No output is provided. + + inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR + if no more input was provided, Z_DATA_ERROR if no flush point has been found, + or Z_STREAM_ERROR if the stream structure was inconsistent. In the success + case, the application may save the current current value of total_in which + indicates where valid compressed data was found. In the error case, the + application may repeatedly call inflateSync, providing more input each time, + until success or end of the input data. +*/ + +ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest, + z_streamp source)); +/* + Sets the destination stream as a complete copy of the source stream. + + This function can be useful when randomly accessing a large stream. The + first pass through the stream can periodically record the inflate state, + allowing restarting inflate at those points when randomly accessing the + stream. + + inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_STREAM_ERROR if the source stream state was inconsistent + (such as zalloc being NULL). msg is left unchanged in both source and + destination. +*/ + +ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm)); +/* + This function is equivalent to inflateEnd followed by inflateInit, + but does not free and reallocate all the internal decompression state. + The stream will keep attributes that may have been set by inflateInit2. + + inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent (such as zalloc or state being NULL). +*/ + +ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm, + int bits, + int value)); +/* + This function inserts bits in the inflate input stream. The intent is + that this function is used to start inflating at a bit position in the + middle of a byte. The provided bits will be used before any bytes are used + from next_in. This function should only be used with raw inflate, and + should be used before the first inflate() call after inflateInit2() or + inflateReset(). bits must be less than or equal to 16, and that many of the + least significant bits of value will be inserted in the input. + + inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent. +*/ + +ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm, + gz_headerp head)); +/* + inflateGetHeader() requests that gzip header information be stored in the + provided gz_header structure. inflateGetHeader() may be called after + inflateInit2() or inflateReset(), and before the first call of inflate(). + As inflate() processes the gzip stream, head->done is zero until the header + is completed, at which time head->done is set to one. If a zlib stream is + being decoded, then head->done is set to -1 to indicate that there will be + no gzip header information forthcoming. Note that Z_BLOCK can be used to + force inflate() to return immediately after header processing is complete + and before any actual data is decompressed. + + The text, time, xflags, and os fields are filled in with the gzip header + contents. hcrc is set to true if there is a header CRC. (The header CRC + was valid if done is set to one.) If extra is not Z_NULL, then extra_max + contains the maximum number of bytes to write to extra. Once done is true, + extra_len contains the actual extra field length, and extra contains the + extra field, or that field truncated if extra_max is less than extra_len. + If name is not Z_NULL, then up to name_max characters are written there, + terminated with a zero unless the length is greater than name_max. If + comment is not Z_NULL, then up to comm_max characters are written there, + terminated with a zero unless the length is greater than comm_max. When + any of extra, name, or comment are not Z_NULL and the respective field is + not present in the header, then that field is set to Z_NULL to signal its + absence. This allows the use of deflateSetHeader() with the returned + structure to duplicate the header. However if those fields are set to + allocated memory, then the application will need to save those pointers + elsewhere so that they can be eventually freed. + + If inflateGetHeader is not used, then the header information is simply + discarded. The header is always checked for validity, including the header + CRC if present. inflateReset() will reset the process to discard the header + information. The application would need to call inflateGetHeader() again to + retrieve the header from the next gzip stream. + + inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent. +*/ + +/* +ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits, + unsigned char FAR *window)); + + Initialize the internal stream state for decompression using inflateBack() + calls. The fields zalloc, zfree and opaque in strm must be initialized + before the call. If zalloc and zfree are Z_NULL, then the default library- + derived memory allocation routines are used. windowBits is the base two + logarithm of the window size, in the range 8..15. window is a caller + supplied buffer of that size. Except for special applications where it is + assured that deflate was used with small window sizes, windowBits must be 15 + and a 32K byte window must be supplied to be able to decompress general + deflate streams. + + See inflateBack() for the usage of these routines. + + inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of + the paramaters are invalid, Z_MEM_ERROR if the internal state could not + be allocated, or Z_VERSION_ERROR if the version of the library does not + match the version of the header file. +*/ + +typedef unsigned (*in_func) OF((void FAR *, unsigned char FAR * FAR *)); +typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned)); + +ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm, + in_func in, void FAR *in_desc, + out_func out, void FAR *out_desc)); +/* + inflateBack() does a raw inflate with a single call using a call-back + interface for input and output. This is more efficient than inflate() for + file i/o applications in that it avoids copying between the output and the + sliding window by simply making the window itself the output buffer. This + function trusts the application to not change the output buffer passed by + the output function, at least until inflateBack() returns. + + inflateBackInit() must be called first to allocate the internal state + and to initialize the state with the user-provided window buffer. + inflateBack() may then be used multiple times to inflate a complete, raw + deflate stream with each call. inflateBackEnd() is then called to free + the allocated state. + + A raw deflate stream is one with no zlib or gzip header or trailer. + This routine would normally be used in a utility that reads zip or gzip + files and writes out uncompressed files. The utility would decode the + header and process the trailer on its own, hence this routine expects + only the raw deflate stream to decompress. This is different from the + normal behavior of inflate(), which expects either a zlib or gzip header and + trailer around the deflate stream. + + inflateBack() uses two subroutines supplied by the caller that are then + called by inflateBack() for input and output. inflateBack() calls those + routines until it reads a complete deflate stream and writes out all of the + uncompressed data, or until it encounters an error. The function's + parameters and return types are defined above in the in_func and out_func + typedefs. inflateBack() will call in(in_desc, &buf) which should return the + number of bytes of provided input, and a pointer to that input in buf. If + there is no input available, in() must return zero--buf is ignored in that + case--and inflateBack() will return a buffer error. inflateBack() will call + out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. out() + should return zero on success, or non-zero on failure. If out() returns + non-zero, inflateBack() will return with an error. Neither in() nor out() + are permitted to change the contents of the window provided to + inflateBackInit(), which is also the buffer that out() uses to write from. + The length written by out() will be at most the window size. Any non-zero + amount of input may be provided by in(). + + For convenience, inflateBack() can be provided input on the first call by + setting strm->next_in and strm->avail_in. If that input is exhausted, then + in() will be called. Therefore strm->next_in must be initialized before + calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called + immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in + must also be initialized, and then if strm->avail_in is not zero, input will + initially be taken from strm->next_in[0 .. strm->avail_in - 1]. + + The in_desc and out_desc parameters of inflateBack() is passed as the + first parameter of in() and out() respectively when they are called. These + descriptors can be optionally used to pass any information that the caller- + supplied in() and out() functions need to do their job. + + On return, inflateBack() will set strm->next_in and strm->avail_in to + pass back any unused input that was provided by the last in() call. The + return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR + if in() or out() returned an error, Z_DATA_ERROR if there was a format + error in the deflate stream (in which case strm->msg is set to indicate the + nature of the error), or Z_STREAM_ERROR if the stream was not properly + initialized. In the case of Z_BUF_ERROR, an input or output error can be + distinguished using strm->next_in which will be Z_NULL only if in() returned + an error. If strm->next is not Z_NULL, then the Z_BUF_ERROR was due to + out() returning non-zero. (in() will always be called before out(), so + strm->next_in is assured to be defined if out() returns non-zero.) Note + that inflateBack() cannot return Z_OK. +*/ + +ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm)); +/* + All memory allocated by inflateBackInit() is freed. + + inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream + state was inconsistent. +*/ + +ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void)); +/* Return flags indicating compile-time options. + + Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other: + 1.0: size of uInt + 3.2: size of uLong + 5.4: size of voidpf (pointer) + 7.6: size of z_off_t + + Compiler, assembler, and debug options: + 8: DEBUG + 9: ASMV or ASMINF -- use ASM code + 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention + 11: 0 (reserved) + + One-time table building (smaller code, but not thread-safe if true): + 12: BUILDFIXED -- build static block decoding tables when needed + 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed + 14,15: 0 (reserved) + + Library content (indicates missing functionality): + 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking + deflate code when not needed) + 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect + and decode gzip streams (to avoid linking crc code) + 18-19: 0 (reserved) + + Operation variations (changes in library functionality): + 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate + 21: FASTEST -- deflate algorithm with only one, lowest compression level + 22,23: 0 (reserved) + + The sprintf variant used by gzprintf (zero is best): + 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format + 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure! + 26: 0 = returns value, 1 = void -- 1 means inferred string length returned + + Remainder: + 27-31: 0 (reserved) + */ + + + /* utility functions */ + +/* + The following utility functions are implemented on top of the + basic stream-oriented functions. To simplify the interface, some + default options are assumed (compression level and memory usage, + standard memory allocation functions). The source code of these + utility functions can easily be modified if you need special options. +*/ + +ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen, + const Bytef *source, uLong sourceLen)); +/* + Compresses the source buffer into the destination buffer. sourceLen is + the byte length of the source buffer. Upon entry, destLen is the total + size of the destination buffer, which must be at least the value returned + by compressBound(sourceLen). Upon exit, destLen is the actual size of the + compressed buffer. + This function can be used to compress a whole file at once if the + input file is mmap'ed. + compress returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_BUF_ERROR if there was not enough room in the output + buffer. +*/ + +ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen, + const Bytef *source, uLong sourceLen, + int level)); +/* + Compresses the source buffer into the destination buffer. The level + parameter has the same meaning as in deflateInit. sourceLen is the byte + length of the source buffer. Upon entry, destLen is the total size of the + destination buffer, which must be at least the value returned by + compressBound(sourceLen). Upon exit, destLen is the actual size of the + compressed buffer. + + compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_BUF_ERROR if there was not enough room in the output buffer, + Z_STREAM_ERROR if the level parameter is invalid. +*/ + +ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen)); +/* + compressBound() returns an upper bound on the compressed size after + compress() or compress2() on sourceLen bytes. It would be used before + a compress() or compress2() call to allocate the destination buffer. +*/ + +ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen, + const Bytef *source, uLong sourceLen)); +/* + Decompresses the source buffer into the destination buffer. sourceLen is + the byte length of the source buffer. Upon entry, destLen is the total + size of the destination buffer, which must be large enough to hold the + entire uncompressed data. (The size of the uncompressed data must have + been saved previously by the compressor and transmitted to the decompressor + by some mechanism outside the scope of this compression library.) + Upon exit, destLen is the actual size of the compressed buffer. + This function can be used to decompress a whole file at once if the + input file is mmap'ed. + + uncompress returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_BUF_ERROR if there was not enough room in the output + buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete. +*/ + + +typedef voidp gzFile; + +ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode)); +/* + Opens a gzip (.gz) file for reading or writing. The mode parameter + is as in fopen ("rb" or "wb") but can also include a compression level + ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for + Huffman only compression as in "wb1h", or 'R' for run-length encoding + as in "wb1R". (See the description of deflateInit2 for more information + about the strategy parameter.) + + gzopen can be used to read a file which is not in gzip format; in this + case gzread will directly read from the file without decompression. + + gzopen returns NULL if the file could not be opened or if there was + insufficient memory to allocate the (de)compression state; errno + can be checked to distinguish the two cases (if errno is zero, the + zlib error is Z_MEM_ERROR). */ + +ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode)); +/* + gzdopen() associates a gzFile with the file descriptor fd. File + descriptors are obtained from calls like open, dup, creat, pipe or + fileno (in the file has been previously opened with fopen). + The mode parameter is as in gzopen. + The next call of gzclose on the returned gzFile will also close the + file descriptor fd, just like fclose(fdopen(fd), mode) closes the file + descriptor fd. If you want to keep fd open, use gzdopen(dup(fd), mode). + gzdopen returns NULL if there was insufficient memory to allocate + the (de)compression state. +*/ + +ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy)); +/* + Dynamically update the compression level or strategy. See the description + of deflateInit2 for the meaning of these parameters. + gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not + opened for writing. +*/ + +ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len)); +/* + Reads the given number of uncompressed bytes from the compressed file. + If the input file was not in gzip format, gzread copies the given number + of bytes into the buffer. + gzread returns the number of uncompressed bytes actually read (0 for + end of file, -1 for error). */ + +ZEXTERN int ZEXPORT gzwrite OF((gzFile file, + voidpc buf, unsigned len)); +/* + Writes the given number of uncompressed bytes into the compressed file. + gzwrite returns the number of uncompressed bytes actually written + (0 in case of error). +*/ + +ZEXTERN int ZEXPORTVA gzprintf OF((gzFile file, const char *format, ...)); +/* + Converts, formats, and writes the args to the compressed file under + control of the format string, as in fprintf. gzprintf returns the number of + uncompressed bytes actually written (0 in case of error). The number of + uncompressed bytes written is limited to 4095. The caller should assure that + this limit is not exceeded. If it is exceeded, then gzprintf() will return + return an error (0) with nothing written. In this case, there may also be a + buffer overflow with unpredictable consequences, which is possible only if + zlib was compiled with the insecure functions sprintf() or vsprintf() + because the secure snprintf() or vsnprintf() functions were not available. +*/ + +ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s)); +/* + Writes the given null-terminated string to the compressed file, excluding + the terminating null character. + gzputs returns the number of characters written, or -1 in case of error. +*/ + +ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len)); +/* + Reads bytes from the compressed file until len-1 characters are read, or + a newline character is read and transferred to buf, or an end-of-file + condition is encountered. The string is then terminated with a null + character. + gzgets returns buf, or Z_NULL in case of error. +*/ + +ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c)); +/* + Writes c, converted to an unsigned char, into the compressed file. + gzputc returns the value that was written, or -1 in case of error. +*/ + +ZEXTERN int ZEXPORT gzgetc OF((gzFile file)); +/* + Reads one byte from the compressed file. gzgetc returns this byte + or -1 in case of end of file or error. +*/ + +ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file)); +/* + Push one character back onto the stream to be read again later. + Only one character of push-back is allowed. gzungetc() returns the + character pushed, or -1 on failure. gzungetc() will fail if a + character has been pushed but not read yet, or if c is -1. The pushed + character will be discarded if the stream is repositioned with gzseek() + or gzrewind(). +*/ + +ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush)); +/* + Flushes all pending output into the compressed file. The parameter + flush is as in the deflate() function. The return value is the zlib + error number (see function gzerror below). gzflush returns Z_OK if + the flush parameter is Z_FINISH and all output could be flushed. + gzflush should be called only when strictly necessary because it can + degrade compression. +*/ + +ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file, + z_off_t offset, int whence)); +/* + Sets the starting position for the next gzread or gzwrite on the + given compressed file. The offset represents a number of bytes in the + uncompressed data stream. The whence parameter is defined as in lseek(2); + the value SEEK_END is not supported. + If the file is opened for reading, this function is emulated but can be + extremely slow. If the file is opened for writing, only forward seeks are + supported; gzseek then compresses a sequence of zeroes up to the new + starting position. + + gzseek returns the resulting offset location as measured in bytes from + the beginning of the uncompressed stream, or -1 in case of error, in + particular if the file is opened for writing and the new starting position + would be before the current position. +*/ + +ZEXTERN int ZEXPORT gzrewind OF((gzFile file)); +/* + Rewinds the given file. This function is supported only for reading. + + gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET) +*/ + +ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file)); +/* + Returns the starting position for the next gzread or gzwrite on the + given compressed file. This position represents a number of bytes in the + uncompressed data stream. + + gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR) +*/ + +ZEXTERN int ZEXPORT gzeof OF((gzFile file)); +/* + Returns 1 when EOF has previously been detected reading the given + input stream, otherwise zero. +*/ + +ZEXTERN int ZEXPORT gzdirect OF((gzFile file)); +/* + Returns 1 if file is being read directly without decompression, otherwise + zero. +*/ + +ZEXTERN int ZEXPORT gzclose OF((gzFile file)); +/* + Flushes all pending output if necessary, closes the compressed file + and deallocates all the (de)compression state. The return value is the zlib + error number (see function gzerror below). +*/ + +ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum)); +/* + Returns the error message for the last error which occurred on the + given compressed file. errnum is set to zlib error number. If an + error occurred in the file system and not in the compression library, + errnum is set to Z_ERRNO and the application may consult errno + to get the exact error code. +*/ + +ZEXTERN void ZEXPORT gzclearerr OF((gzFile file)); +/* + Clears the error and end-of-file flags for file. This is analogous to the + clearerr() function in stdio. This is useful for continuing to read a gzip + file that is being written concurrently. +*/ + + /* checksum functions */ + +/* + These functions are not related to compression but are exported + anyway because they might be useful in applications using the + compression library. +*/ + +ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len)); +/* + Update a running Adler-32 checksum with the bytes buf[0..len-1] and + return the updated checksum. If buf is NULL, this function returns + the required initial value for the checksum. + An Adler-32 checksum is almost as reliable as a CRC32 but can be computed + much faster. Usage example: + + uLong adler = adler32(0L, Z_NULL, 0); + + while (read_buffer(buffer, length) != EOF) { + adler = adler32(adler, buffer, length); + } + if (adler != original_adler) error(); +*/ + +ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2, + z_off_t len2)); +/* + Combine two Adler-32 checksums into one. For two sequences of bytes, seq1 + and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for + each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of + seq1 and seq2 concatenated, requiring only adler1, adler2, and len2. +*/ + +ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len)); +/* + Update a running CRC-32 with the bytes buf[0..len-1] and return the + updated CRC-32. If buf is NULL, this function returns the required initial + value for the for the crc. Pre- and post-conditioning (one's complement) is + performed within this function so it shouldn't be done by the application. + Usage example: + + uLong crc = crc32(0L, Z_NULL, 0); + + while (read_buffer(buffer, length) != EOF) { + crc = crc32(crc, buffer, length); + } + if (crc != original_crc) error(); +*/ + +ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2)); + +/* + Combine two CRC-32 check values into one. For two sequences of bytes, + seq1 and seq2 with lengths len1 and len2, CRC-32 check values were + calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32 + check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and + len2. +*/ + + + /* various hacks, don't look :) */ + +/* deflateInit and inflateInit are macros to allow checking the zlib version + * and the compiler's view of z_stream: + */ +ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level, + const char *version, int stream_size)); +ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm, + const char *version, int stream_size)); +ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method, + int windowBits, int memLevel, + int strategy, const char *version, + int stream_size)); +ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits, + const char *version, int stream_size)); +ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits, + unsigned char FAR *window, + const char *version, + int stream_size)); +#define deflateInit(strm, level) \ + deflateInit_((strm), (level), ZLIB_VERSION, sizeof(z_stream)) +#define inflateInit(strm) \ + inflateInit_((strm), ZLIB_VERSION, sizeof(z_stream)) +#define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \ + deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\ + (strategy), ZLIB_VERSION, sizeof(z_stream)) +#define inflateInit2(strm, windowBits) \ + inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream)) +#define inflateBackInit(strm, windowBits, window) \ + inflateBackInit_((strm), (windowBits), (window), \ + ZLIB_VERSION, sizeof(z_stream)) + + +#if !defined(ZUTIL_H) && !defined(NO_DUMMY_DECL) + struct internal_state {int dummy;}; /* hack for buggy compilers */ +#endif + +ZEXTERN const char * ZEXPORT zError OF((int)); +ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp z)); +ZEXTERN const uLongf * ZEXPORT get_crc_table OF((void)); + +#ifdef __cplusplus +} +#endif + +#endif /* ZLIB_H */ diff --git a/Foundation/samples/ActiveMethod/ActiveMethod.vmsbuild b/Foundation/samples/ActiveMethod/ActiveMethod.vmsbuild index 11e108168..753c8c21e 100644 --- a/Foundation/samples/ActiveMethod/ActiveMethod.vmsbuild +++ b/Foundation/samples/ActiveMethod/ActiveMethod.vmsbuild @@ -1,8 +1,8 @@ -# -# sample.vmsbuild -# -# $Id: //poco/1.2/Foundation/samples/ActiveMethod/ActiveMethod.vmsbuild#1 $ -# -EXE=ActiveMethod -ActiveMethod - +# +# sample.vmsbuild +# +# $Id: //poco/1.2/Foundation/samples/ActiveMethod/ActiveMethod.vmsbuild#1 $ +# +EXE=ActiveMethod +ActiveMethod + diff --git a/Foundation/samples/ActiveMethod/ActiveMethod_vs71.vcproj b/Foundation/samples/ActiveMethod/ActiveMethod_vs71.vcproj index 05e5b9fef..fc23b1dde 100644 --- a/Foundation/samples/ActiveMethod/ActiveMethod_vs71.vcproj +++ b/Foundation/samples/ActiveMethod/ActiveMethod_vs71.vcproj @@ -1,149 +1,149 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Foundation/samples/ActiveMethod/ActiveMethod_vs80.vcproj b/Foundation/samples/ActiveMethod/ActiveMethod_vs80.vcproj index d45a580b4..049a64b98 100644 --- a/Foundation/samples/ActiveMethod/ActiveMethod_vs80.vcproj +++ b/Foundation/samples/ActiveMethod/ActiveMethod_vs80.vcproj @@ -1,213 +1,213 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Foundation/samples/ActiveMethod/Makefile b/Foundation/samples/ActiveMethod/Makefile index 97da55bc6..c29260dbc 100644 --- a/Foundation/samples/ActiveMethod/Makefile +++ b/Foundation/samples/ActiveMethod/Makefile @@ -1,17 +1,17 @@ -# -# Makefile -# -# $Id: //poco/1.2/Foundation/samples/ActiveMethod/Makefile#1 $ -# -# Makefile for Poco ActiveMethod -# - -include $(POCO_BASE)/build/rules/global - -objects = ActiveMethod - -target = ActiveMethod -target_version = 1 -target_libs = PocoFoundation - -include $(POCO_BASE)/build/rules/exec +# +# Makefile +# +# $Id: //poco/1.2/Foundation/samples/ActiveMethod/Makefile#1 $ +# +# Makefile for Poco ActiveMethod +# + +include $(POCO_BASE)/build/rules/global + +objects = ActiveMethod + +target = ActiveMethod +target_version = 1 +target_libs = PocoFoundation + +include $(POCO_BASE)/build/rules/exec diff --git a/Foundation/samples/ActiveMethod/src/ActiveMethod.cpp b/Foundation/samples/ActiveMethod/src/ActiveMethod.cpp index 1e113789a..bdb57c0f2 100644 --- a/Foundation/samples/ActiveMethod/src/ActiveMethod.cpp +++ b/Foundation/samples/ActiveMethod/src/ActiveMethod.cpp @@ -1,78 +1,78 @@ -// -// ActiveMethod.cpp -// -// $Id: //poco/1.2/Foundation/samples/ActiveMethod/src/ActiveMethod.cpp#1 $ -// -// This sample demonstrates the ActiveMethod and ActiveResult classes. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/ActiveMethod.h" -#include "Poco/ActiveResult.h" -#include - - -using Poco::ActiveMethod; -using Poco::ActiveResult; - - -class ActiveMethodExample -{ -public: - struct AddArgs - { - int a; - int b; - }; - - ActiveMethodExample(): - activeAdd(this, &ActiveMethodExample::activeAddImp) - { - } - - ActiveMethod activeAdd; - -private: - int activeAddImp(const AddArgs& args) - { - return args.a + args.b; - } -}; - - -int main(int argc, char** argv) -{ - ActiveMethodExample example; - - ActiveMethodExample::AddArgs args = {1, 2}; - ActiveResult result = example.activeAdd(args); - result.wait(); - std::cout << result.data() << std::endl; - - return 0; -} +// +// ActiveMethod.cpp +// +// $Id: //poco/1.2/Foundation/samples/ActiveMethod/src/ActiveMethod.cpp#1 $ +// +// This sample demonstrates the ActiveMethod and ActiveResult classes. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/ActiveMethod.h" +#include "Poco/ActiveResult.h" +#include + + +using Poco::ActiveMethod; +using Poco::ActiveResult; + + +class ActiveMethodExample +{ +public: + struct AddArgs + { + int a; + int b; + }; + + ActiveMethodExample(): + activeAdd(this, &ActiveMethodExample::activeAddImp) + { + } + + ActiveMethod activeAdd; + +private: + int activeAddImp(const AddArgs& args) + { + return args.a + args.b; + } +}; + + +int main(int argc, char** argv) +{ + ActiveMethodExample example; + + ActiveMethodExample::AddArgs args = {1, 2}; + ActiveResult result = example.activeAdd(args); + result.wait(); + std::cout << result.data() << std::endl; + + return 0; +} diff --git a/Foundation/samples/Activity/Activity.vmsbuild b/Foundation/samples/Activity/Activity.vmsbuild index 60e454309..39ef366e0 100644 --- a/Foundation/samples/Activity/Activity.vmsbuild +++ b/Foundation/samples/Activity/Activity.vmsbuild @@ -1,8 +1,8 @@ -# -# sample.vmsbuild -# -# $Id: //poco/1.2/Foundation/samples/Activity/Activity.vmsbuild#1 $ -# -EXE=Activity -Activity - +# +# sample.vmsbuild +# +# $Id: //poco/1.2/Foundation/samples/Activity/Activity.vmsbuild#1 $ +# +EXE=Activity +Activity + diff --git a/Foundation/samples/Activity/Activity_vs71.vcproj b/Foundation/samples/Activity/Activity_vs71.vcproj index 956781364..3fa611c6b 100644 --- a/Foundation/samples/Activity/Activity_vs71.vcproj +++ b/Foundation/samples/Activity/Activity_vs71.vcproj @@ -1,149 +1,149 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Foundation/samples/Activity/Activity_vs80.vcproj b/Foundation/samples/Activity/Activity_vs80.vcproj index 839ee2e49..7f99a80ca 100644 --- a/Foundation/samples/Activity/Activity_vs80.vcproj +++ b/Foundation/samples/Activity/Activity_vs80.vcproj @@ -1,213 +1,213 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Foundation/samples/Activity/Makefile b/Foundation/samples/Activity/Makefile index be2213f0a..2705efc86 100644 --- a/Foundation/samples/Activity/Makefile +++ b/Foundation/samples/Activity/Makefile @@ -1,17 +1,17 @@ -# -# Makefile -# -# $Id: //poco/Foundation/samples/Activity/Makefile#2 $ -# -# Makefile for Poco Activity -# - -include $(POCO_BASE)/build/rules/global - -objects = Activity - -target = Activity -target_version = 1 -target_libs = PocoFoundation - -include $(POCO_BASE)/build/rules/exec +# +# Makefile +# +# $Id: //poco/Foundation/samples/Activity/Makefile#2 $ +# +# Makefile for Poco Activity +# + +include $(POCO_BASE)/build/rules/global + +objects = Activity + +target = Activity +target_version = 1 +target_libs = PocoFoundation + +include $(POCO_BASE)/build/rules/exec diff --git a/Foundation/samples/Activity/src/Activity.cpp b/Foundation/samples/Activity/src/Activity.cpp index 648452c8c..a16605d20 100644 --- a/Foundation/samples/Activity/src/Activity.cpp +++ b/Foundation/samples/Activity/src/Activity.cpp @@ -1,90 +1,90 @@ -// -// Activity.cpp -// -// $Id: //poco/1.2/Foundation/samples/Activity/src/Activity.cpp#1 $ -// -// This sample demonstrates the Activity class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/Activity.h" -#include "Poco/Thread.h" -#include - - -using Poco::Activity; -using Poco::Thread; - - -class ActivityExample -{ -public: - ActivityExample(): - _activity(this, &ActivityExample::runActivity) - { - } - - void start() - { - _activity.start(); - } - - void stop() - { - _activity.stop(); - _activity.wait(); - } - -protected: - void runActivity() - { - while (!_activity.isStopped()) - { - std::cout << "Activity running." << std::endl; - Thread::sleep(250); - } - std::cout << "Activity stopped." << std::endl; - } - -private: - Activity _activity; -}; - - -int main(int argc, char** argv) -{ - ActivityExample example; - example.start(); - Thread::sleep(2000); - example.stop(); - - example.start(); - example.stop(); - - return 0; -} +// +// Activity.cpp +// +// $Id: //poco/1.2/Foundation/samples/Activity/src/Activity.cpp#1 $ +// +// This sample demonstrates the Activity class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/Activity.h" +#include "Poco/Thread.h" +#include + + +using Poco::Activity; +using Poco::Thread; + + +class ActivityExample +{ +public: + ActivityExample(): + _activity(this, &ActivityExample::runActivity) + { + } + + void start() + { + _activity.start(); + } + + void stop() + { + _activity.stop(); + _activity.wait(); + } + +protected: + void runActivity() + { + while (!_activity.isStopped()) + { + std::cout << "Activity running." << std::endl; + Thread::sleep(250); + } + std::cout << "Activity stopped." << std::endl; + } + +private: + Activity _activity; +}; + + +int main(int argc, char** argv) +{ + ActivityExample example; + example.start(); + Thread::sleep(2000); + example.stop(); + + example.start(); + example.stop(); + + return 0; +} diff --git a/Foundation/samples/BinaryReaderWriter/BinaryReaderWriter.vmsbuild b/Foundation/samples/BinaryReaderWriter/BinaryReaderWriter.vmsbuild index 3e61e0ec2..40c79f3c3 100644 --- a/Foundation/samples/BinaryReaderWriter/BinaryReaderWriter.vmsbuild +++ b/Foundation/samples/BinaryReaderWriter/BinaryReaderWriter.vmsbuild @@ -1,8 +1,8 @@ -# -# sample.vmsbuild -# -# $Id: //poco/1.2/Foundation/samples/BinaryReaderWriter/BinaryReaderWriter.vmsbuild#1 $ -# -EXE=BinaryReaderWriter -BinaryReaderWriter - +# +# sample.vmsbuild +# +# $Id: //poco/1.2/Foundation/samples/BinaryReaderWriter/BinaryReaderWriter.vmsbuild#1 $ +# +EXE=BinaryReaderWriter +BinaryReaderWriter + diff --git a/Foundation/samples/BinaryReaderWriter/BinaryReaderWriter_vs71.vcproj b/Foundation/samples/BinaryReaderWriter/BinaryReaderWriter_vs71.vcproj index e45491e0e..a5afbd2ae 100644 --- a/Foundation/samples/BinaryReaderWriter/BinaryReaderWriter_vs71.vcproj +++ b/Foundation/samples/BinaryReaderWriter/BinaryReaderWriter_vs71.vcproj @@ -1,149 +1,149 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Foundation/samples/BinaryReaderWriter/BinaryReaderWriter_vs80.vcproj b/Foundation/samples/BinaryReaderWriter/BinaryReaderWriter_vs80.vcproj index 20ce07a09..7772b3a6e 100644 --- a/Foundation/samples/BinaryReaderWriter/BinaryReaderWriter_vs80.vcproj +++ b/Foundation/samples/BinaryReaderWriter/BinaryReaderWriter_vs80.vcproj @@ -1,213 +1,213 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Foundation/samples/BinaryReaderWriter/Makefile b/Foundation/samples/BinaryReaderWriter/Makefile index 345243dfb..10ebc9c2c 100644 --- a/Foundation/samples/BinaryReaderWriter/Makefile +++ b/Foundation/samples/BinaryReaderWriter/Makefile @@ -1,17 +1,17 @@ -# -# Makefile -# -# $Id: //poco/1.2/Foundation/samples/BinaryReaderWriter/Makefile#1 $ -# -# Makefile for Poco BinaryReaderWriter -# - -include $(POCO_BASE)/build/rules/global - -objects = BinaryReaderWriter - -target = BinaryReaderWriter -target_version = 1 -target_libs = PocoFoundation - -include $(POCO_BASE)/build/rules/exec +# +# Makefile +# +# $Id: //poco/1.2/Foundation/samples/BinaryReaderWriter/Makefile#1 $ +# +# Makefile for Poco BinaryReaderWriter +# + +include $(POCO_BASE)/build/rules/global + +objects = BinaryReaderWriter + +target = BinaryReaderWriter +target_version = 1 +target_libs = PocoFoundation + +include $(POCO_BASE)/build/rules/exec diff --git a/Foundation/samples/BinaryReaderWriter/src/BinaryReaderWriter.cpp b/Foundation/samples/BinaryReaderWriter/src/BinaryReaderWriter.cpp index 8eed7a89f..8ca8f702b 100644 --- a/Foundation/samples/BinaryReaderWriter/src/BinaryReaderWriter.cpp +++ b/Foundation/samples/BinaryReaderWriter/src/BinaryReaderWriter.cpp @@ -1,76 +1,76 @@ -// -// BinaryReaderWriter.cpp -// -// $Id: //poco/1.2/Foundation/samples/BinaryReaderWriter/src/BinaryReaderWriter.cpp#1 $ -// -// This sample demonstrates the BinaryWriter and BinaryReader classes. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/BinaryWriter.h" -#include "Poco/BinaryReader.h" -#include -#include - - -using Poco::BinaryWriter; -using Poco::BinaryReader; - - -int main(int argc, char** argv) -{ - std::stringstream str; - - BinaryWriter writer(str); - writer << true - << 'x' - << 42 - << 3.14159265 - << "foo bar"; - - bool b; - char c; - int i; - double d; - std::string s; - - BinaryReader reader(str); - reader >> b - >> c - >> i - >> d - >> s; - - std::cout << b << std::endl - << c << std::endl - << i << std::endl - << d << std::endl - << s << std::endl; - - return 0; -} +// +// BinaryReaderWriter.cpp +// +// $Id: //poco/1.2/Foundation/samples/BinaryReaderWriter/src/BinaryReaderWriter.cpp#1 $ +// +// This sample demonstrates the BinaryWriter and BinaryReader classes. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/BinaryWriter.h" +#include "Poco/BinaryReader.h" +#include +#include + + +using Poco::BinaryWriter; +using Poco::BinaryReader; + + +int main(int argc, char** argv) +{ + std::stringstream str; + + BinaryWriter writer(str); + writer << true + << 'x' + << 42 + << 3.14159265 + << "foo bar"; + + bool b; + char c; + int i; + double d; + std::string s; + + BinaryReader reader(str); + reader >> b + >> c + >> i + >> d + >> s; + + std::cout << b << std::endl + << c << std::endl + << i << std::endl + << d << std::endl + << s << std::endl; + + return 0; +} diff --git a/Foundation/samples/DateTime/DateTime.vmsbuild b/Foundation/samples/DateTime/DateTime.vmsbuild index d7ab16d07..4568473ee 100644 --- a/Foundation/samples/DateTime/DateTime.vmsbuild +++ b/Foundation/samples/DateTime/DateTime.vmsbuild @@ -1,8 +1,8 @@ -# -# sample.vmsbuild -# -# $Id: //poco/1.2/Foundation/samples/DateTime/DateTime.vmsbuild#1 $ -# -EXE=DateTime -DateTime - +# +# sample.vmsbuild +# +# $Id: //poco/1.2/Foundation/samples/DateTime/DateTime.vmsbuild#1 $ +# +EXE=DateTime +DateTime + diff --git a/Foundation/samples/DateTime/DateTime_vs71.vcproj b/Foundation/samples/DateTime/DateTime_vs71.vcproj index df497b268..adf9115a4 100644 --- a/Foundation/samples/DateTime/DateTime_vs71.vcproj +++ b/Foundation/samples/DateTime/DateTime_vs71.vcproj @@ -1,149 +1,149 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Foundation/samples/DateTime/DateTime_vs80.vcproj b/Foundation/samples/DateTime/DateTime_vs80.vcproj index fce70988b..777dc2877 100644 --- a/Foundation/samples/DateTime/DateTime_vs80.vcproj +++ b/Foundation/samples/DateTime/DateTime_vs80.vcproj @@ -1,213 +1,213 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Foundation/samples/DateTime/Makefile b/Foundation/samples/DateTime/Makefile index 6ae986f5a..1d0d6693c 100644 --- a/Foundation/samples/DateTime/Makefile +++ b/Foundation/samples/DateTime/Makefile @@ -1,17 +1,17 @@ -# -# Makefile -# -# $Id: //poco/1.2/Foundation/samples/DateTime/Makefile#1 $ -# -# Makefile for Poco DateTime -# - -include $(POCO_BASE)/build/rules/global - -objects = DateTime - -target = DateTime -target_version = 1 -target_libs = PocoFoundation - -include $(POCO_BASE)/build/rules/exec +# +# Makefile +# +# $Id: //poco/1.2/Foundation/samples/DateTime/Makefile#1 $ +# +# Makefile for Poco DateTime +# + +include $(POCO_BASE)/build/rules/global + +objects = DateTime + +target = DateTime +target_version = 1 +target_libs = PocoFoundation + +include $(POCO_BASE)/build/rules/exec diff --git a/Foundation/samples/DateTime/src/DateTime.cpp b/Foundation/samples/DateTime/src/DateTime.cpp index c69cc76fe..2bd965e8e 100644 --- a/Foundation/samples/DateTime/src/DateTime.cpp +++ b/Foundation/samples/DateTime/src/DateTime.cpp @@ -1,61 +1,61 @@ -// -// DateTime.cpp -// -// $Id: //poco/1.2/Foundation/samples/DateTime/src/DateTime.cpp#1 $ -// -// This sample demonstrates the DateTime class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/DateTime.h" -#include "Poco/DateTimeFormat.h" -#include - - -using Poco::DateTime; -using Poco::DateTimeFormat; - - -int main(int argc, char** argv) -{ - DateTime now; - - std::cout << "Today is " - << DateTimeFormat::WEEKDAY_NAMES[now.dayOfWeek()] << ", " - << DateTimeFormat::MONTH_NAMES[now.month() - 1] << " " - << now.day() << " - " - << "day number " - << now.dayOfYear() - << " in " - << now.year() - << " and day number " - << (long) now.julianDay() - << " in the Julian calendar." << std::endl; - - return 0; -} +// +// DateTime.cpp +// +// $Id: //poco/1.2/Foundation/samples/DateTime/src/DateTime.cpp#1 $ +// +// This sample demonstrates the DateTime class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/DateTime.h" +#include "Poco/DateTimeFormat.h" +#include + + +using Poco::DateTime; +using Poco::DateTimeFormat; + + +int main(int argc, char** argv) +{ + DateTime now; + + std::cout << "Today is " + << DateTimeFormat::WEEKDAY_NAMES[now.dayOfWeek()] << ", " + << DateTimeFormat::MONTH_NAMES[now.month() - 1] << " " + << now.day() << " - " + << "day number " + << now.dayOfYear() + << " in " + << now.year() + << " and day number " + << (long) now.julianDay() + << " in the Julian calendar." << std::endl; + + return 0; +} diff --git a/Foundation/samples/Logger/Logger.vmsbuild b/Foundation/samples/Logger/Logger.vmsbuild index 15ec53619..b5070f301 100644 --- a/Foundation/samples/Logger/Logger.vmsbuild +++ b/Foundation/samples/Logger/Logger.vmsbuild @@ -1,8 +1,8 @@ -# -# sample.vmsbuild -# -# $Id: //poco/1.2/Foundation/samples/Logger/Logger.vmsbuild#1 $ -# -EXE=Logger -Logger - +# +# sample.vmsbuild +# +# $Id: //poco/1.2/Foundation/samples/Logger/Logger.vmsbuild#1 $ +# +EXE=Logger +Logger + diff --git a/Foundation/samples/Logger/Logger_vs71.vcproj b/Foundation/samples/Logger/Logger_vs71.vcproj index ecdeca1ce..bd3504323 100644 --- a/Foundation/samples/Logger/Logger_vs71.vcproj +++ b/Foundation/samples/Logger/Logger_vs71.vcproj @@ -1,149 +1,149 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Foundation/samples/Logger/Logger_vs80.vcproj b/Foundation/samples/Logger/Logger_vs80.vcproj index a57eb129f..8429659d2 100644 --- a/Foundation/samples/Logger/Logger_vs80.vcproj +++ b/Foundation/samples/Logger/Logger_vs80.vcproj @@ -1,213 +1,213 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Foundation/samples/Logger/Makefile b/Foundation/samples/Logger/Makefile index b5650ad3f..06e1ae530 100644 --- a/Foundation/samples/Logger/Makefile +++ b/Foundation/samples/Logger/Makefile @@ -1,17 +1,17 @@ -# -# Makefile -# -# $Id: //poco/1.2/Foundation/samples/Logger/Makefile#1 $ -# -# Makefile for Poco Logger -# - -include $(POCO_BASE)/build/rules/global - -objects = Logger - -target = Logger -target_version = 1 -target_libs = PocoFoundation - -include $(POCO_BASE)/build/rules/exec +# +# Makefile +# +# $Id: //poco/1.2/Foundation/samples/Logger/Makefile#1 $ +# +# Makefile for Poco Logger +# + +include $(POCO_BASE)/build/rules/global + +objects = Logger + +target = Logger +target_version = 1 +target_libs = PocoFoundation + +include $(POCO_BASE)/build/rules/exec diff --git a/Foundation/samples/Logger/src/Logger.cpp b/Foundation/samples/Logger/src/Logger.cpp index fc20cd43c..ce989796a 100644 --- a/Foundation/samples/Logger/src/Logger.cpp +++ b/Foundation/samples/Logger/src/Logger.cpp @@ -1,82 +1,82 @@ -// -// Logger.cpp -// -// $Id: //poco/1.2/Foundation/samples/Logger/src/Logger.cpp#1 $ -// -// This class demonstrates the Logger, PatternFormatter, FormattingChannel, -// ConsoleChannel and FileChannel classes. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/Logger.h" -#include "Poco/PatternFormatter.h" -#include "Poco/FormattingChannel.h" -#include "Poco/ConsoleChannel.h" -#include "Poco/FileChannel.h" -#include "Poco/Message.h" - - -using Poco::Logger; -using Poco::PatternFormatter; -using Poco::FormattingChannel; -using Poco::ConsoleChannel; -using Poco::FileChannel; -using Poco::Message; - - -int main(int argc, char** argv) -{ - // set up two channel chains - one to the - // console and the other one to a log file. - FormattingChannel* pFCConsole = new FormattingChannel(new PatternFormatter("%s: %p: %t")); - pFCConsole->setChannel(new ConsoleChannel); - pFCConsole->open(); - - FormattingChannel* pFCFile = new FormattingChannel(new PatternFormatter("%Y-%m-%d %H:%M:%S.%c %N[%P]:%s:%q:%t")); - pFCFile->setChannel(new FileChannel("sample.log")); - pFCFile->open(); - - // create two Logger objects - one for - // each channel chain. - Logger& consoleLogger = Logger::create("ConsoleLogger", pFCConsole, Message::PRIO_INFORMATION); - Logger& fileLogger = Logger::create("FileLogger", pFCFile, Message::PRIO_WARNING); - - // log some messages - consoleLogger.error("An error message"); - fileLogger.error("An error message"); - - consoleLogger.warning("A warning message"); - fileLogger.error("A warning message"); - - consoleLogger.information("An information message"); - fileLogger.information("An information message"); - - Logger::get("ConsoleLogger").error("Another error message"); - - return 0; -} +// +// Logger.cpp +// +// $Id: //poco/1.2/Foundation/samples/Logger/src/Logger.cpp#1 $ +// +// This class demonstrates the Logger, PatternFormatter, FormattingChannel, +// ConsoleChannel and FileChannel classes. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/Logger.h" +#include "Poco/PatternFormatter.h" +#include "Poco/FormattingChannel.h" +#include "Poco/ConsoleChannel.h" +#include "Poco/FileChannel.h" +#include "Poco/Message.h" + + +using Poco::Logger; +using Poco::PatternFormatter; +using Poco::FormattingChannel; +using Poco::ConsoleChannel; +using Poco::FileChannel; +using Poco::Message; + + +int main(int argc, char** argv) +{ + // set up two channel chains - one to the + // console and the other one to a log file. + FormattingChannel* pFCConsole = new FormattingChannel(new PatternFormatter("%s: %p: %t")); + pFCConsole->setChannel(new ConsoleChannel); + pFCConsole->open(); + + FormattingChannel* pFCFile = new FormattingChannel(new PatternFormatter("%Y-%m-%d %H:%M:%S.%c %N[%P]:%s:%q:%t")); + pFCFile->setChannel(new FileChannel("sample.log")); + pFCFile->open(); + + // create two Logger objects - one for + // each channel chain. + Logger& consoleLogger = Logger::create("ConsoleLogger", pFCConsole, Message::PRIO_INFORMATION); + Logger& fileLogger = Logger::create("FileLogger", pFCFile, Message::PRIO_WARNING); + + // log some messages + consoleLogger.error("An error message"); + fileLogger.error("An error message"); + + consoleLogger.warning("A warning message"); + fileLogger.error("A warning message"); + + consoleLogger.information("An information message"); + fileLogger.information("An information message"); + + Logger::get("ConsoleLogger").error("Another error message"); + + return 0; +} diff --git a/Foundation/samples/Makefile b/Foundation/samples/Makefile index e0f1e9e00..9b109a267 100644 --- a/Foundation/samples/Makefile +++ b/Foundation/samples/Makefile @@ -1,29 +1,29 @@ -# -# Makefile -# -# $Id: //poco/1.2/Foundation/samples/Makefile#1 $ -# -# Makefile for Poco Foundation Samples -# - -.PHONY: projects -clean all: projects -projects: - $(MAKE) -C ActiveMethod $(MAKECMDGOALS) - $(MAKE) -C Activity $(MAKECMDGOALS) - $(MAKE) -C Timer $(MAKECMDGOALS) - $(MAKE) -C BinaryReaderWriter $(MAKECMDGOALS) - $(MAKE) -C base64decode $(MAKECMDGOALS) - $(MAKE) -C base64encode $(MAKECMDGOALS) - $(MAKE) -C deflate $(MAKECMDGOALS) - $(MAKE) -C inflate $(MAKECMDGOALS) - $(MAKE) -C DateTime $(MAKECMDGOALS) - $(MAKE) -C Logger $(MAKECMDGOALS) - $(MAKE) -C grep $(MAKECMDGOALS) - $(MAKE) -C dir $(MAKECMDGOALS) - $(MAKE) -C md5 $(MAKECMDGOALS) - $(MAKE) -C hmacmd5 $(MAKECMDGOALS) - $(MAKE) -C NotificationQueue $(MAKECMDGOALS) - $(MAKE) -C StringTokenizer $(MAKECMDGOALS) - $(MAKE) -C URI $(MAKECMDGOALS) - $(MAKE) -C uuidgen $(MAKECMDGOALS) +# +# Makefile +# +# $Id: //poco/1.2/Foundation/samples/Makefile#1 $ +# +# Makefile for Poco Foundation Samples +# + +.PHONY: projects +clean all: projects +projects: + $(MAKE) -C ActiveMethod $(MAKECMDGOALS) + $(MAKE) -C Activity $(MAKECMDGOALS) + $(MAKE) -C Timer $(MAKECMDGOALS) + $(MAKE) -C BinaryReaderWriter $(MAKECMDGOALS) + $(MAKE) -C base64decode $(MAKECMDGOALS) + $(MAKE) -C base64encode $(MAKECMDGOALS) + $(MAKE) -C deflate $(MAKECMDGOALS) + $(MAKE) -C inflate $(MAKECMDGOALS) + $(MAKE) -C DateTime $(MAKECMDGOALS) + $(MAKE) -C Logger $(MAKECMDGOALS) + $(MAKE) -C grep $(MAKECMDGOALS) + $(MAKE) -C dir $(MAKECMDGOALS) + $(MAKE) -C md5 $(MAKECMDGOALS) + $(MAKE) -C hmacmd5 $(MAKECMDGOALS) + $(MAKE) -C NotificationQueue $(MAKECMDGOALS) + $(MAKE) -C StringTokenizer $(MAKECMDGOALS) + $(MAKE) -C URI $(MAKECMDGOALS) + $(MAKE) -C uuidgen $(MAKECMDGOALS) diff --git a/Foundation/samples/NotificationQueue/Makefile b/Foundation/samples/NotificationQueue/Makefile index 655b57868..fcd1f911d 100644 --- a/Foundation/samples/NotificationQueue/Makefile +++ b/Foundation/samples/NotificationQueue/Makefile @@ -1,17 +1,17 @@ -# -# Makefile -# -# $Id: //poco/1.2/Foundation/samples/NotificationQueue/Makefile#1 $ -# -# Makefile for Poco NotificationQueue -# - -include $(POCO_BASE)/build/rules/global - -objects = NotificationQueue - -target = NotificationQueue -target_version = 1 -target_libs = PocoFoundation - -include $(POCO_BASE)/build/rules/exec +# +# Makefile +# +# $Id: //poco/1.2/Foundation/samples/NotificationQueue/Makefile#1 $ +# +# Makefile for Poco NotificationQueue +# + +include $(POCO_BASE)/build/rules/global + +objects = NotificationQueue + +target = NotificationQueue +target_version = 1 +target_libs = PocoFoundation + +include $(POCO_BASE)/build/rules/exec diff --git a/Foundation/samples/NotificationQueue/NotificationQueue.vmsbuild b/Foundation/samples/NotificationQueue/NotificationQueue.vmsbuild index 59a1ac3c0..680fad1a5 100644 --- a/Foundation/samples/NotificationQueue/NotificationQueue.vmsbuild +++ b/Foundation/samples/NotificationQueue/NotificationQueue.vmsbuild @@ -1,8 +1,8 @@ -# -# sample.vmsbuild -# -# $Id: //poco/1.2/Foundation/samples/NotificationQueue/NotificationQueue.vmsbuild#1 $ -# -EXE=NotificationQueue -NotificationQueue - +# +# sample.vmsbuild +# +# $Id: //poco/1.2/Foundation/samples/NotificationQueue/NotificationQueue.vmsbuild#1 $ +# +EXE=NotificationQueue +NotificationQueue + diff --git a/Foundation/samples/NotificationQueue/NotificationQueue_vs71.vcproj b/Foundation/samples/NotificationQueue/NotificationQueue_vs71.vcproj index 5f20601f2..af61e8ce1 100644 --- a/Foundation/samples/NotificationQueue/NotificationQueue_vs71.vcproj +++ b/Foundation/samples/NotificationQueue/NotificationQueue_vs71.vcproj @@ -1,149 +1,149 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Foundation/samples/NotificationQueue/NotificationQueue_vs80.vcproj b/Foundation/samples/NotificationQueue/NotificationQueue_vs80.vcproj index 5fa6bca03..af27076d8 100644 --- a/Foundation/samples/NotificationQueue/NotificationQueue_vs80.vcproj +++ b/Foundation/samples/NotificationQueue/NotificationQueue_vs80.vcproj @@ -1,213 +1,213 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Foundation/samples/NotificationQueue/src/NotificationQueue.cpp b/Foundation/samples/NotificationQueue/src/NotificationQueue.cpp index 85e4e7afb..a94037f15 100644 --- a/Foundation/samples/NotificationQueue/src/NotificationQueue.cpp +++ b/Foundation/samples/NotificationQueue/src/NotificationQueue.cpp @@ -1,149 +1,149 @@ -// -// NotificationQueue.cpp -// -// $Id: //poco/1.2/Foundation/samples/NotificationQueue/src/NotificationQueue.cpp#1 $ -// -// This sample demonstrates the NotificationQueue, ThreadPool, -// FastMutex and ScopedLock classes. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/Notification.h" -#include "Poco/NotificationQueue.h" -#include "Poco/ThreadPool.h" -#include "Poco/Thread.h" -#include "Poco/Runnable.h" -#include "Poco/Mutex.h" -#include "Poco/Random.h" -#include "Poco/AutoPtr.h" -#include - - -using Poco::Notification; -using Poco::NotificationQueue; -using Poco::ThreadPool; -using Poco::Thread; -using Poco::Runnable; -using Poco::FastMutex; -using Poco::Random; -using Poco::AutoPtr; - - -class WorkNotification: public Notification - // The notification sent to worker threads. -{ -public: - WorkNotification(int data): - _data(data) - { - } - - int data() const - { - return _data; - } - -private: - int _data; -}; - - -class Worker: public Runnable - // A worker thread that gets work items - // from a NotificationQueue. -{ -public: - Worker(const std::string& name, NotificationQueue& queue): - _name(name), - _queue(queue) - { - } - - void run() - { - Random rnd; - for (;;) - { - AutoPtr pNf(_queue.waitDequeueNotification()); - if (pNf) - { - WorkNotification* pWorkNf = dynamic_cast(pNf.get()); - if (pWorkNf) - { - FastMutex::ScopedLock lock(_mutex); - - std::cout << _name << " got work notification " << pWorkNf->data() << std::endl; - - Thread::sleep(rnd.next(200)); - } - } - else break; - } - } - -private: - std::string _name; - NotificationQueue& _queue; - static FastMutex _mutex; -}; - - -FastMutex Worker::_mutex; - - -int main(int argc, char** argv) -{ - NotificationQueue queue; - - // create some worker threads - Worker worker1("Worker 1", queue); - Worker worker2("Worker 2", queue); - Worker worker3("Worker 3", queue); - - // start worker threads - ThreadPool::defaultPool().start(worker1); - ThreadPool::defaultPool().start(worker2); - ThreadPool::defaultPool().start(worker3); - - // distribute some work - for (int i = 0; i < 50; ++i) - { - queue.enqueueNotification(new WorkNotification(i)); - } - - // wait until queue is empty and all threads are - // waiting for new work. - while (!queue.empty()) Thread::sleep(200); - Thread::sleep(500); - - // stop all worker threads - queue.wakeUpAll(); - ThreadPool::defaultPool().joinAll(); - - return 0; -} +// +// NotificationQueue.cpp +// +// $Id: //poco/1.2/Foundation/samples/NotificationQueue/src/NotificationQueue.cpp#1 $ +// +// This sample demonstrates the NotificationQueue, ThreadPool, +// FastMutex and ScopedLock classes. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/Notification.h" +#include "Poco/NotificationQueue.h" +#include "Poco/ThreadPool.h" +#include "Poco/Thread.h" +#include "Poco/Runnable.h" +#include "Poco/Mutex.h" +#include "Poco/Random.h" +#include "Poco/AutoPtr.h" +#include + + +using Poco::Notification; +using Poco::NotificationQueue; +using Poco::ThreadPool; +using Poco::Thread; +using Poco::Runnable; +using Poco::FastMutex; +using Poco::Random; +using Poco::AutoPtr; + + +class WorkNotification: public Notification + // The notification sent to worker threads. +{ +public: + WorkNotification(int data): + _data(data) + { + } + + int data() const + { + return _data; + } + +private: + int _data; +}; + + +class Worker: public Runnable + // A worker thread that gets work items + // from a NotificationQueue. +{ +public: + Worker(const std::string& name, NotificationQueue& queue): + _name(name), + _queue(queue) + { + } + + void run() + { + Random rnd; + for (;;) + { + AutoPtr pNf(_queue.waitDequeueNotification()); + if (pNf) + { + WorkNotification* pWorkNf = dynamic_cast(pNf.get()); + if (pWorkNf) + { + FastMutex::ScopedLock lock(_mutex); + + std::cout << _name << " got work notification " << pWorkNf->data() << std::endl; + + Thread::sleep(rnd.next(200)); + } + } + else break; + } + } + +private: + std::string _name; + NotificationQueue& _queue; + static FastMutex _mutex; +}; + + +FastMutex Worker::_mutex; + + +int main(int argc, char** argv) +{ + NotificationQueue queue; + + // create some worker threads + Worker worker1("Worker 1", queue); + Worker worker2("Worker 2", queue); + Worker worker3("Worker 3", queue); + + // start worker threads + ThreadPool::defaultPool().start(worker1); + ThreadPool::defaultPool().start(worker2); + ThreadPool::defaultPool().start(worker3); + + // distribute some work + for (int i = 0; i < 50; ++i) + { + queue.enqueueNotification(new WorkNotification(i)); + } + + // wait until queue is empty and all threads are + // waiting for new work. + while (!queue.empty()) Thread::sleep(200); + Thread::sleep(500); + + // stop all worker threads + queue.wakeUpAll(); + ThreadPool::defaultPool().joinAll(); + + return 0; +} diff --git a/Foundation/samples/StringTokenizer/Makefile b/Foundation/samples/StringTokenizer/Makefile index 9f2e01a1b..1bc3f4325 100644 --- a/Foundation/samples/StringTokenizer/Makefile +++ b/Foundation/samples/StringTokenizer/Makefile @@ -1,17 +1,17 @@ -# -# Makefile -# -# $Id: //poco/1.2/Foundation/samples/StringTokenizer/Makefile#1 $ -# -# Makefile for Poco StringTokenizer -# - -include $(POCO_BASE)/build/rules/global - -objects = StringTokenizer - -target = StringTokenizer -target_version = 1 -target_libs = PocoFoundation - -include $(POCO_BASE)/build/rules/exec +# +# Makefile +# +# $Id: //poco/1.2/Foundation/samples/StringTokenizer/Makefile#1 $ +# +# Makefile for Poco StringTokenizer +# + +include $(POCO_BASE)/build/rules/global + +objects = StringTokenizer + +target = StringTokenizer +target_version = 1 +target_libs = PocoFoundation + +include $(POCO_BASE)/build/rules/exec diff --git a/Foundation/samples/StringTokenizer/StringTokenizer.vmsbuild b/Foundation/samples/StringTokenizer/StringTokenizer.vmsbuild index ef238c918..f68f4e283 100644 --- a/Foundation/samples/StringTokenizer/StringTokenizer.vmsbuild +++ b/Foundation/samples/StringTokenizer/StringTokenizer.vmsbuild @@ -1,8 +1,8 @@ -# -# sample.vmsbuild -# -# $Id: //poco/1.2/Foundation/samples/StringTokenizer/StringTokenizer.vmsbuild#1 $ -# -EXE=StringTokenizer -StringTokenizer - +# +# sample.vmsbuild +# +# $Id: //poco/1.2/Foundation/samples/StringTokenizer/StringTokenizer.vmsbuild#1 $ +# +EXE=StringTokenizer +StringTokenizer + diff --git a/Foundation/samples/StringTokenizer/StringTokenizer_vs71.vcproj b/Foundation/samples/StringTokenizer/StringTokenizer_vs71.vcproj index be366ca1a..014f9f93d 100644 --- a/Foundation/samples/StringTokenizer/StringTokenizer_vs71.vcproj +++ b/Foundation/samples/StringTokenizer/StringTokenizer_vs71.vcproj @@ -1,149 +1,149 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Foundation/samples/StringTokenizer/StringTokenizer_vs80.vcproj b/Foundation/samples/StringTokenizer/StringTokenizer_vs80.vcproj index a22df445f..f3701f7cd 100644 --- a/Foundation/samples/StringTokenizer/StringTokenizer_vs80.vcproj +++ b/Foundation/samples/StringTokenizer/StringTokenizer_vs80.vcproj @@ -1,213 +1,213 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Foundation/samples/StringTokenizer/src/StringTokenizer.cpp b/Foundation/samples/StringTokenizer/src/StringTokenizer.cpp index 2410f77c7..4af45af5a 100644 --- a/Foundation/samples/StringTokenizer/src/StringTokenizer.cpp +++ b/Foundation/samples/StringTokenizer/src/StringTokenizer.cpp @@ -1,51 +1,51 @@ -// -// StringTokenizer.cpp -// -// $Id: //poco/1.2/Foundation/samples/StringTokenizer/src/StringTokenizer.cpp#1 $ -// -// This sample demonstrates the usage of the StringTokenizer class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/StringTokenizer.h" -#include - - -using Poco::StringTokenizer; - - -int main(int argc, char** argv) -{ - std::string tokens = "white; black; magenta, blue, green; yellow"; - StringTokenizer tokenizer(tokens, ";,", StringTokenizer::TOK_TRIM); - for (StringTokenizer::Iterator it = tokenizer.begin(); it != tokenizer.end(); ++it) - { - std::cout << *it << std::endl; - } - return 0; -} +// +// StringTokenizer.cpp +// +// $Id: //poco/1.2/Foundation/samples/StringTokenizer/src/StringTokenizer.cpp#1 $ +// +// This sample demonstrates the usage of the StringTokenizer class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/StringTokenizer.h" +#include + + +using Poco::StringTokenizer; + + +int main(int argc, char** argv) +{ + std::string tokens = "white; black; magenta, blue, green; yellow"; + StringTokenizer tokenizer(tokens, ";,", StringTokenizer::TOK_TRIM); + for (StringTokenizer::Iterator it = tokenizer.begin(); it != tokenizer.end(); ++it) + { + std::cout << *it << std::endl; + } + return 0; +} diff --git a/Foundation/samples/Timer/Makefile b/Foundation/samples/Timer/Makefile index dc0147765..97df8278c 100644 --- a/Foundation/samples/Timer/Makefile +++ b/Foundation/samples/Timer/Makefile @@ -1,17 +1,17 @@ -# -# Makefile -# -# $Id: //poco/1.2/Foundation/samples/Timer/Makefile#1 $ -# -# Makefile for Poco Timer -# - -include $(POCO_BASE)/build/rules/global - -objects = Timer - -target = Timer -target_version = 1 -target_libs = PocoFoundation - -include $(POCO_BASE)/build/rules/exec +# +# Makefile +# +# $Id: //poco/1.2/Foundation/samples/Timer/Makefile#1 $ +# +# Makefile for Poco Timer +# + +include $(POCO_BASE)/build/rules/global + +objects = Timer + +target = Timer +target_version = 1 +target_libs = PocoFoundation + +include $(POCO_BASE)/build/rules/exec diff --git a/Foundation/samples/Timer/Timer.vmsbuild b/Foundation/samples/Timer/Timer.vmsbuild index cec0f3bbd..424266589 100644 --- a/Foundation/samples/Timer/Timer.vmsbuild +++ b/Foundation/samples/Timer/Timer.vmsbuild @@ -1,8 +1,8 @@ -# -# sample.vmsbuild -# -# $Id: //poco/1.2/Foundation/samples/Timer/Timer.vmsbuild#1 $ -# -EXE=Timer -Timer - +# +# sample.vmsbuild +# +# $Id: //poco/1.2/Foundation/samples/Timer/Timer.vmsbuild#1 $ +# +EXE=Timer +Timer + diff --git a/Foundation/samples/Timer/Timer_vs71.vcproj b/Foundation/samples/Timer/Timer_vs71.vcproj index 6e7c7c8b5..e25df5151 100644 --- a/Foundation/samples/Timer/Timer_vs71.vcproj +++ b/Foundation/samples/Timer/Timer_vs71.vcproj @@ -1,149 +1,149 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Foundation/samples/Timer/Timer_vs80.vcproj b/Foundation/samples/Timer/Timer_vs80.vcproj index 636616553..ed5ade82b 100644 --- a/Foundation/samples/Timer/Timer_vs80.vcproj +++ b/Foundation/samples/Timer/Timer_vs80.vcproj @@ -1,213 +1,213 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Foundation/samples/Timer/src/Timer.cpp b/Foundation/samples/Timer/src/Timer.cpp index fb67e415b..160015115 100644 --- a/Foundation/samples/Timer/src/Timer.cpp +++ b/Foundation/samples/Timer/src/Timer.cpp @@ -1,77 +1,77 @@ -// -// Timer.cpp -// -// $Id: //poco/1.2/Foundation/samples/Timer/src/Timer.cpp#1 $ -// -// This sample demonstrates the Timer and Stopwatch classes. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/Timer.h" -#include "Poco/Thread.h" -#include "Poco/Stopwatch.h" -#include - - -using Poco::Timer; -using Poco::TimerCallback; -using Poco::Thread; -using Poco::Stopwatch; - - -class TimerExample -{ -public: - TimerExample() - { - _sw.start(); - } - - void onTimer(Timer& timer) - { - std::cout << "Callback called after " << _sw.elapsed()/1000 << " milliseconds." << std::endl; - } - -private: - Stopwatch _sw; -}; - - -int main(int argc, char** argv) -{ - TimerExample example; - - Timer timer(250, 500); - timer.start(TimerCallback(example, &TimerExample::onTimer)); - - Thread::sleep(5000); - - timer.stop(); - - return 0; -} +// +// Timer.cpp +// +// $Id: //poco/1.2/Foundation/samples/Timer/src/Timer.cpp#1 $ +// +// This sample demonstrates the Timer and Stopwatch classes. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/Timer.h" +#include "Poco/Thread.h" +#include "Poco/Stopwatch.h" +#include + + +using Poco::Timer; +using Poco::TimerCallback; +using Poco::Thread; +using Poco::Stopwatch; + + +class TimerExample +{ +public: + TimerExample() + { + _sw.start(); + } + + void onTimer(Timer& timer) + { + std::cout << "Callback called after " << _sw.elapsed()/1000 << " milliseconds." << std::endl; + } + +private: + Stopwatch _sw; +}; + + +int main(int argc, char** argv) +{ + TimerExample example; + + Timer timer(250, 500); + timer.start(TimerCallback(example, &TimerExample::onTimer)); + + Thread::sleep(5000); + + timer.stop(); + + return 0; +} diff --git a/Foundation/samples/URI/Makefile b/Foundation/samples/URI/Makefile index def3d7510..119826d74 100644 --- a/Foundation/samples/URI/Makefile +++ b/Foundation/samples/URI/Makefile @@ -1,17 +1,17 @@ -# -# Makefile -# -# $Id: //poco/1.2/Foundation/samples/URI/Makefile#1 $ -# -# Makefile for Poco URI -# - -include $(POCO_BASE)/build/rules/global - -objects = URI - -target = URI -target_version = 1 -target_libs = PocoFoundation - -include $(POCO_BASE)/build/rules/exec +# +# Makefile +# +# $Id: //poco/1.2/Foundation/samples/URI/Makefile#1 $ +# +# Makefile for Poco URI +# + +include $(POCO_BASE)/build/rules/global + +objects = URI + +target = URI +target_version = 1 +target_libs = PocoFoundation + +include $(POCO_BASE)/build/rules/exec diff --git a/Foundation/samples/URI/URI.vmsbuild b/Foundation/samples/URI/URI.vmsbuild index 7439e9f43..f244b6f19 100644 --- a/Foundation/samples/URI/URI.vmsbuild +++ b/Foundation/samples/URI/URI.vmsbuild @@ -1,8 +1,8 @@ -# -# sample.vmsbuild -# -# $Id: //poco/1.2/Foundation/samples/URI/URI.vmsbuild#1 $ -# -EXE=URI -URI - +# +# sample.vmsbuild +# +# $Id: //poco/1.2/Foundation/samples/URI/URI.vmsbuild#1 $ +# +EXE=URI +URI + diff --git a/Foundation/samples/URI/URI_vs71.vcproj b/Foundation/samples/URI/URI_vs71.vcproj index d350941cf..3d4dfd18d 100644 --- a/Foundation/samples/URI/URI_vs71.vcproj +++ b/Foundation/samples/URI/URI_vs71.vcproj @@ -1,149 +1,149 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Foundation/samples/URI/URI_vs80.vcproj b/Foundation/samples/URI/URI_vs80.vcproj index e326199c8..8ae8fb5dd 100644 --- a/Foundation/samples/URI/URI_vs80.vcproj +++ b/Foundation/samples/URI/URI_vs80.vcproj @@ -1,213 +1,213 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Foundation/samples/URI/src/URI.cpp b/Foundation/samples/URI/src/URI.cpp index 2c67d45bf..b00753e6b 100644 --- a/Foundation/samples/URI/src/URI.cpp +++ b/Foundation/samples/URI/src/URI.cpp @@ -1,60 +1,60 @@ -// -// URI.cpp -// -// $Id: //poco/1.2/Foundation/samples/URI/src/URI.cpp#1 $ -// -// This sample demonstrates the URI class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/URI.h" -#include - - -using Poco::URI; - - -int main(int argc, char** argv) -{ - URI uri1("http://www.appinf.com:81/sample?example-query#somewhere"); - - std::cout << "Scheme: " << uri1.getScheme() << std::endl - << "Authority: " << uri1.getAuthority() << std::endl - << "Path: " << uri1.getPath() << std::endl - << "Query: " << uri1.getQuery() << std::endl - << "Fragment: " << uri1.getFragment() << std::endl; - - URI uri2; - uri2.setScheme("https"); - uri2.setAuthority("www.appinf.com"); - uri2.setPath("/another sample"); - - std::cout << uri2.toString() << std::endl; - - return 0; -} +// +// URI.cpp +// +// $Id: //poco/1.2/Foundation/samples/URI/src/URI.cpp#1 $ +// +// This sample demonstrates the URI class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/URI.h" +#include + + +using Poco::URI; + + +int main(int argc, char** argv) +{ + URI uri1("http://www.appinf.com:81/sample?example-query#somewhere"); + + std::cout << "Scheme: " << uri1.getScheme() << std::endl + << "Authority: " << uri1.getAuthority() << std::endl + << "Path: " << uri1.getPath() << std::endl + << "Query: " << uri1.getQuery() << std::endl + << "Fragment: " << uri1.getFragment() << std::endl; + + URI uri2; + uri2.setScheme("https"); + uri2.setAuthority("www.appinf.com"); + uri2.setPath("/another sample"); + + std::cout << uri2.toString() << std::endl; + + return 0; +} diff --git a/Foundation/samples/base64decode/Makefile b/Foundation/samples/base64decode/Makefile index 10fdd3dad..327d163f4 100644 --- a/Foundation/samples/base64decode/Makefile +++ b/Foundation/samples/base64decode/Makefile @@ -1,17 +1,17 @@ -# -# Makefile -# -# $Id: //poco/1.2/Foundation/samples/base64decode/Makefile#1 $ -# -# Makefile for Poco base64decode -# - -include $(POCO_BASE)/build/rules/global - -objects = base64decode - -target = base64decode -target_version = 1 -target_libs = PocoFoundation - -include $(POCO_BASE)/build/rules/exec +# +# Makefile +# +# $Id: //poco/1.2/Foundation/samples/base64decode/Makefile#1 $ +# +# Makefile for Poco base64decode +# + +include $(POCO_BASE)/build/rules/global + +objects = base64decode + +target = base64decode +target_version = 1 +target_libs = PocoFoundation + +include $(POCO_BASE)/build/rules/exec diff --git a/Foundation/samples/base64decode/base64decode.vmsbuild b/Foundation/samples/base64decode/base64decode.vmsbuild index b269f836c..fb508b523 100644 --- a/Foundation/samples/base64decode/base64decode.vmsbuild +++ b/Foundation/samples/base64decode/base64decode.vmsbuild @@ -1,8 +1,8 @@ -# -# sample.vmsbuild -# -# $Id: //poco/1.2/Foundation/samples/base64decode/base64decode.vmsbuild#1 $ -# -EXE=base64decode -base64decode - +# +# sample.vmsbuild +# +# $Id: //poco/1.2/Foundation/samples/base64decode/base64decode.vmsbuild#1 $ +# +EXE=base64decode +base64decode + diff --git a/Foundation/samples/base64decode/base64decode_vs71.vcproj b/Foundation/samples/base64decode/base64decode_vs71.vcproj index 2f2148674..7ec836da2 100644 --- a/Foundation/samples/base64decode/base64decode_vs71.vcproj +++ b/Foundation/samples/base64decode/base64decode_vs71.vcproj @@ -1,149 +1,149 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Foundation/samples/base64decode/base64decode_vs80.vcproj b/Foundation/samples/base64decode/base64decode_vs80.vcproj index ba941c4c7..da32cc2a0 100644 --- a/Foundation/samples/base64decode/base64decode_vs80.vcproj +++ b/Foundation/samples/base64decode/base64decode_vs80.vcproj @@ -1,213 +1,213 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Foundation/samples/base64decode/src/base64decode.cpp b/Foundation/samples/base64decode/src/base64decode.cpp index 383f16b01..313ce72dd 100644 --- a/Foundation/samples/base64decode/src/base64decode.cpp +++ b/Foundation/samples/base64decode/src/base64decode.cpp @@ -1,78 +1,78 @@ -// -// base64decode.cpp -// -// $Id: //poco/1.2/Foundation/samples/base64decode/src/base64decode.cpp#1 $ -// -// This sample demonstrates the Base64Decoder and StreamCopier classes. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/Base64Decoder.h" -#include "Poco/StreamCopier.h" -#include -#include - - -using Poco::Base64Decoder; -using Poco::StreamCopier; - - -int main(int argc, char** argv) -{ - if (argc != 3) - { - std::cout << "usage: " << argv[0] << ": " << std::endl - << " read base64-encoded , decode it and write the result to " << std::endl; - return 1; - } - - std::ifstream istr(argv[1]); - if (!istr) - { - std::cerr << "cannot open input file: " << argv[1] << std::endl; - return 2; - } - - std::ofstream ostr(argv[2], std::ios::binary); - if (!ostr) - { - std::cerr << "cannot open output file: " << argv[2] << std::endl; - return 3; - } - - Base64Decoder decoder(istr); - StreamCopier::copyStream(decoder, ostr); - - if (!ostr) - { - std::cerr << "error writing output file: " << argv[2] << std::endl; - return 4; - } - - return 0; -} +// +// base64decode.cpp +// +// $Id: //poco/1.2/Foundation/samples/base64decode/src/base64decode.cpp#1 $ +// +// This sample demonstrates the Base64Decoder and StreamCopier classes. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/Base64Decoder.h" +#include "Poco/StreamCopier.h" +#include +#include + + +using Poco::Base64Decoder; +using Poco::StreamCopier; + + +int main(int argc, char** argv) +{ + if (argc != 3) + { + std::cout << "usage: " << argv[0] << ": " << std::endl + << " read base64-encoded , decode it and write the result to " << std::endl; + return 1; + } + + std::ifstream istr(argv[1]); + if (!istr) + { + std::cerr << "cannot open input file: " << argv[1] << std::endl; + return 2; + } + + std::ofstream ostr(argv[2], std::ios::binary); + if (!ostr) + { + std::cerr << "cannot open output file: " << argv[2] << std::endl; + return 3; + } + + Base64Decoder decoder(istr); + StreamCopier::copyStream(decoder, ostr); + + if (!ostr) + { + std::cerr << "error writing output file: " << argv[2] << std::endl; + return 4; + } + + return 0; +} diff --git a/Foundation/samples/base64encode/Makefile b/Foundation/samples/base64encode/Makefile index c4904910c..c6a233d5a 100644 --- a/Foundation/samples/base64encode/Makefile +++ b/Foundation/samples/base64encode/Makefile @@ -1,17 +1,17 @@ -# -# Makefile -# -# $Id: //poco/1.2/Foundation/samples/base64encode/Makefile#1 $ -# -# Makefile for Poco base64encode -# - -include $(POCO_BASE)/build/rules/global - -objects = base64encode - -target = base64encode -target_version = 1 -target_libs = PocoFoundation - -include $(POCO_BASE)/build/rules/exec +# +# Makefile +# +# $Id: //poco/1.2/Foundation/samples/base64encode/Makefile#1 $ +# +# Makefile for Poco base64encode +# + +include $(POCO_BASE)/build/rules/global + +objects = base64encode + +target = base64encode +target_version = 1 +target_libs = PocoFoundation + +include $(POCO_BASE)/build/rules/exec diff --git a/Foundation/samples/base64encode/base64encode.vmsbuild b/Foundation/samples/base64encode/base64encode.vmsbuild index 00d69ec4e..185c8be58 100644 --- a/Foundation/samples/base64encode/base64encode.vmsbuild +++ b/Foundation/samples/base64encode/base64encode.vmsbuild @@ -1,8 +1,8 @@ -# -# sample.vmsbuild -# -# $Id: //poco/1.2/Foundation/samples/base64encode/base64encode.vmsbuild#1 $ -# -EXE=base64encode -base64encode - +# +# sample.vmsbuild +# +# $Id: //poco/1.2/Foundation/samples/base64encode/base64encode.vmsbuild#1 $ +# +EXE=base64encode +base64encode + diff --git a/Foundation/samples/base64encode/base64encode_vs71.vcproj b/Foundation/samples/base64encode/base64encode_vs71.vcproj index 5b8d11d75..c6869428a 100644 --- a/Foundation/samples/base64encode/base64encode_vs71.vcproj +++ b/Foundation/samples/base64encode/base64encode_vs71.vcproj @@ -1,149 +1,149 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Foundation/samples/base64encode/base64encode_vs80.vcproj b/Foundation/samples/base64encode/base64encode_vs80.vcproj index 6321d53c7..72dadc4d0 100644 --- a/Foundation/samples/base64encode/base64encode_vs80.vcproj +++ b/Foundation/samples/base64encode/base64encode_vs80.vcproj @@ -1,213 +1,213 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Foundation/samples/base64encode/src/base64encode.cpp b/Foundation/samples/base64encode/src/base64encode.cpp index 879999b1d..cd6319ca8 100644 --- a/Foundation/samples/base64encode/src/base64encode.cpp +++ b/Foundation/samples/base64encode/src/base64encode.cpp @@ -1,78 +1,78 @@ -// -// base64encode.cpp -// -// $Id: //poco/1.2/Foundation/samples/base64encode/src/base64encode.cpp#1 $ -// -// This sample demonstrates the Base64Encoder and StreamCopier classes. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/Base64Encoder.h" -#include "Poco/StreamCopier.h" -#include -#include - - -using Poco::Base64Encoder; -using Poco::StreamCopier; - - -int main(int argc, char** argv) -{ - if (argc != 3) - { - std::cout << "usage: " << argv[0] << ": " << std::endl - << " read , base64-encode it and write the result to " << std::endl; - return 1; - } - - std::ifstream istr(argv[1], std::ios::binary); - if (!istr) - { - std::cerr << "cannot open input file: " << argv[1] << std::endl; - return 2; - } - - std::ofstream ostr(argv[2]); - if (!ostr) - { - std::cerr << "cannot open output file: " << argv[2] << std::endl; - return 3; - } - - Base64Encoder encoder(ostr); - StreamCopier::copyStream(istr, encoder); - - if (!ostr) - { - std::cerr << "error writing output file: " << argv[2] << std::endl; - return 4; - } - - return 0; -} +// +// base64encode.cpp +// +// $Id: //poco/1.2/Foundation/samples/base64encode/src/base64encode.cpp#1 $ +// +// This sample demonstrates the Base64Encoder and StreamCopier classes. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/Base64Encoder.h" +#include "Poco/StreamCopier.h" +#include +#include + + +using Poco::Base64Encoder; +using Poco::StreamCopier; + + +int main(int argc, char** argv) +{ + if (argc != 3) + { + std::cout << "usage: " << argv[0] << ": " << std::endl + << " read , base64-encode it and write the result to " << std::endl; + return 1; + } + + std::ifstream istr(argv[1], std::ios::binary); + if (!istr) + { + std::cerr << "cannot open input file: " << argv[1] << std::endl; + return 2; + } + + std::ofstream ostr(argv[2]); + if (!ostr) + { + std::cerr << "cannot open output file: " << argv[2] << std::endl; + return 3; + } + + Base64Encoder encoder(ostr); + StreamCopier::copyStream(istr, encoder); + + if (!ostr) + { + std::cerr << "error writing output file: " << argv[2] << std::endl; + return 4; + } + + return 0; +} diff --git a/Foundation/samples/deflate/Makefile b/Foundation/samples/deflate/Makefile index 3abdd6489..a0d1d1b10 100644 --- a/Foundation/samples/deflate/Makefile +++ b/Foundation/samples/deflate/Makefile @@ -1,17 +1,17 @@ -# -# Makefile -# -# $Id: //poco/1.2/Foundation/samples/deflate/Makefile#1 $ -# -# Makefile for Poco deflate -# - -include $(POCO_BASE)/build/rules/global - -objects = deflate - -target = deflate -target_version = 1 -target_libs = PocoFoundation - -include $(POCO_BASE)/build/rules/exec +# +# Makefile +# +# $Id: //poco/1.2/Foundation/samples/deflate/Makefile#1 $ +# +# Makefile for Poco deflate +# + +include $(POCO_BASE)/build/rules/global + +objects = deflate + +target = deflate +target_version = 1 +target_libs = PocoFoundation + +include $(POCO_BASE)/build/rules/exec diff --git a/Foundation/samples/deflate/deflate.vmsbuild b/Foundation/samples/deflate/deflate.vmsbuild index 296c645d5..da7420809 100644 --- a/Foundation/samples/deflate/deflate.vmsbuild +++ b/Foundation/samples/deflate/deflate.vmsbuild @@ -1,8 +1,8 @@ -# -# sample.vmsbuild -# -# $Id: //poco/1.2/Foundation/samples/deflate/deflate.vmsbuild#1 $ -# -EXE=deflate -deflate - +# +# sample.vmsbuild +# +# $Id: //poco/1.2/Foundation/samples/deflate/deflate.vmsbuild#1 $ +# +EXE=deflate +deflate + diff --git a/Foundation/samples/deflate/deflate_vs71.vcproj b/Foundation/samples/deflate/deflate_vs71.vcproj index a5d434631..8ac8e6401 100644 --- a/Foundation/samples/deflate/deflate_vs71.vcproj +++ b/Foundation/samples/deflate/deflate_vs71.vcproj @@ -1,149 +1,149 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Foundation/samples/deflate/deflate_vs80.vcproj b/Foundation/samples/deflate/deflate_vs80.vcproj index 8f1b755f2..823136d8b 100644 --- a/Foundation/samples/deflate/deflate_vs80.vcproj +++ b/Foundation/samples/deflate/deflate_vs80.vcproj @@ -1,213 +1,213 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Foundation/samples/deflate/src/deflate.cpp b/Foundation/samples/deflate/src/deflate.cpp index 835a86ab6..b7f3b5988 100644 --- a/Foundation/samples/deflate/src/deflate.cpp +++ b/Foundation/samples/deflate/src/deflate.cpp @@ -1,78 +1,78 @@ -// -// deflate.cpp -// -// $Id: //poco/1.2/Foundation/samples/deflate/src/deflate.cpp#1 $ -// -// This sample demonstrates the DeflatingOutputStream and StreamCopier classes. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/DeflatingStream.h" -#include "Poco/StreamCopier.h" -#include -#include - - -using Poco::DeflatingOutputStream; -using Poco::StreamCopier; - - -int main(int argc, char** argv) -{ - if (argc != 3) - { - std::cout << "usage: " << argv[0] << ": " << std::endl - << " read , deflate (compress) it and write the result to " << std::endl; - return 1; - } - - std::ifstream istr(argv[1], std::ios::binary); - if (!istr) - { - std::cerr << "cannot open input file: " << argv[1] << std::endl; - return 2; - } - - std::ofstream ostr(argv[2], std::ios::binary); - if (!ostr) - { - std::cerr << "cannot open output file: " << argv[2] << std::endl; - return 3; - } - - DeflatingOutputStream deflater(ostr); - StreamCopier::copyStream(istr, deflater); - - if (!ostr) - { - std::cerr << "error writing output file: " << argv[2] << std::endl; - return 4; - } - - return 0; -} +// +// deflate.cpp +// +// $Id: //poco/1.2/Foundation/samples/deflate/src/deflate.cpp#1 $ +// +// This sample demonstrates the DeflatingOutputStream and StreamCopier classes. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/DeflatingStream.h" +#include "Poco/StreamCopier.h" +#include +#include + + +using Poco::DeflatingOutputStream; +using Poco::StreamCopier; + + +int main(int argc, char** argv) +{ + if (argc != 3) + { + std::cout << "usage: " << argv[0] << ": " << std::endl + << " read , deflate (compress) it and write the result to " << std::endl; + return 1; + } + + std::ifstream istr(argv[1], std::ios::binary); + if (!istr) + { + std::cerr << "cannot open input file: " << argv[1] << std::endl; + return 2; + } + + std::ofstream ostr(argv[2], std::ios::binary); + if (!ostr) + { + std::cerr << "cannot open output file: " << argv[2] << std::endl; + return 3; + } + + DeflatingOutputStream deflater(ostr); + StreamCopier::copyStream(istr, deflater); + + if (!ostr) + { + std::cerr << "error writing output file: " << argv[2] << std::endl; + return 4; + } + + return 0; +} diff --git a/Foundation/samples/dir/Makefile b/Foundation/samples/dir/Makefile index 1d33f0a4d..f07e6f75e 100644 --- a/Foundation/samples/dir/Makefile +++ b/Foundation/samples/dir/Makefile @@ -1,17 +1,17 @@ -# -# Makefile -# -# $Id: //poco/1.2/Foundation/samples/dir/Makefile#1 $ -# -# Makefile for Poco dir -# - -include $(POCO_BASE)/build/rules/global - -objects = dir - -target = dir -target_version = 1 -target_libs = PocoFoundation - -include $(POCO_BASE)/build/rules/exec +# +# Makefile +# +# $Id: //poco/1.2/Foundation/samples/dir/Makefile#1 $ +# +# Makefile for Poco dir +# + +include $(POCO_BASE)/build/rules/global + +objects = dir + +target = dir +target_version = 1 +target_libs = PocoFoundation + +include $(POCO_BASE)/build/rules/exec diff --git a/Foundation/samples/dir/dir.vmsbuild b/Foundation/samples/dir/dir.vmsbuild index 6f61db86d..174996b25 100644 --- a/Foundation/samples/dir/dir.vmsbuild +++ b/Foundation/samples/dir/dir.vmsbuild @@ -1,8 +1,8 @@ -# -# sample.vmsbuild -# -# $Id: //poco/1.2/Foundation/samples/dir/dir.vmsbuild#1 $ -# -EXE=dir -dir - +# +# sample.vmsbuild +# +# $Id: //poco/1.2/Foundation/samples/dir/dir.vmsbuild#1 $ +# +EXE=dir +dir + diff --git a/Foundation/samples/dir/dir_vs71.vcproj b/Foundation/samples/dir/dir_vs71.vcproj index 9a26e32c6..4f514ebda 100644 --- a/Foundation/samples/dir/dir_vs71.vcproj +++ b/Foundation/samples/dir/dir_vs71.vcproj @@ -1,149 +1,149 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Foundation/samples/dir/dir_vs80.vcproj b/Foundation/samples/dir/dir_vs80.vcproj index d74cffed9..963d21e34 100644 --- a/Foundation/samples/dir/dir_vs80.vcproj +++ b/Foundation/samples/dir/dir_vs80.vcproj @@ -1,213 +1,213 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Foundation/samples/dir/src/dir.cpp b/Foundation/samples/dir/src/dir.cpp index 79abf66c7..6d80a5938 100644 --- a/Foundation/samples/dir/src/dir.cpp +++ b/Foundation/samples/dir/src/dir.cpp @@ -1,84 +1,84 @@ -// -// dir.cpp -// -// $Id: //poco/1.2/Foundation/samples/dir/src/dir.cpp#1 $ -// -// This sample demonstrates the DirectoryIterator, File and Path classes. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/DirectoryIterator.h" -#include "Poco/File.h" -#include "Poco/Path.h" -#include "Poco/DateTimeFormatter.h" -#include "Poco/DateTimeFormat.h" -#include "Poco/Exception.h" -#include - - -using Poco::DirectoryIterator; -using Poco::File; -using Poco::Path; -using Poco::DateTimeFormatter; -using Poco::DateTimeFormat; - - -int main(int argc, char** argv) -{ - std::string dir; - if (argc > 1) - dir = argv[1]; - else - dir = Path::current(); - - try - { - DirectoryIterator it(dir); - DirectoryIterator end; - while (it != end) - { - Path p(it->path()); - std::cout << (it->isDirectory() ? 'd' : '-') - << (it->canRead() ? 'r' : '-') - << (it->canWrite() ? 'w' : '-') - << ' ' - << DateTimeFormatter::format(it->getLastModified(), DateTimeFormat::SORTABLE_FORMAT) - << ' ' - << p.getFileName() - << std::endl; - ++it; - } - } - catch (Poco::Exception& exc) - { - std::cerr << exc.displayText() << std::endl; - return 1; - } - - return 0; -} +// +// dir.cpp +// +// $Id: //poco/1.2/Foundation/samples/dir/src/dir.cpp#1 $ +// +// This sample demonstrates the DirectoryIterator, File and Path classes. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/DirectoryIterator.h" +#include "Poco/File.h" +#include "Poco/Path.h" +#include "Poco/DateTimeFormatter.h" +#include "Poco/DateTimeFormat.h" +#include "Poco/Exception.h" +#include + + +using Poco::DirectoryIterator; +using Poco::File; +using Poco::Path; +using Poco::DateTimeFormatter; +using Poco::DateTimeFormat; + + +int main(int argc, char** argv) +{ + std::string dir; + if (argc > 1) + dir = argv[1]; + else + dir = Path::current(); + + try + { + DirectoryIterator it(dir); + DirectoryIterator end; + while (it != end) + { + Path p(it->path()); + std::cout << (it->isDirectory() ? 'd' : '-') + << (it->canRead() ? 'r' : '-') + << (it->canWrite() ? 'w' : '-') + << ' ' + << DateTimeFormatter::format(it->getLastModified(), DateTimeFormat::SORTABLE_FORMAT) + << ' ' + << p.getFileName() + << std::endl; + ++it; + } + } + catch (Poco::Exception& exc) + { + std::cerr << exc.displayText() << std::endl; + return 1; + } + + return 0; +} diff --git a/Foundation/samples/grep/Makefile b/Foundation/samples/grep/Makefile index 5241a9429..31d556e22 100644 --- a/Foundation/samples/grep/Makefile +++ b/Foundation/samples/grep/Makefile @@ -1,17 +1,17 @@ -# -# Makefile -# -# $Id: //poco/1.2/Foundation/samples/grep/Makefile#1 $ -# -# Makefile for Poco grep -# - -include $(POCO_BASE)/build/rules/global - -objects = grep - -target = grep -target_version = 1 -target_libs = PocoFoundation - -include $(POCO_BASE)/build/rules/exec +# +# Makefile +# +# $Id: //poco/1.2/Foundation/samples/grep/Makefile#1 $ +# +# Makefile for Poco grep +# + +include $(POCO_BASE)/build/rules/global + +objects = grep + +target = grep +target_version = 1 +target_libs = PocoFoundation + +include $(POCO_BASE)/build/rules/exec diff --git a/Foundation/samples/grep/grep.vmsbuild b/Foundation/samples/grep/grep.vmsbuild index 7a0ce078a..64191a06e 100644 --- a/Foundation/samples/grep/grep.vmsbuild +++ b/Foundation/samples/grep/grep.vmsbuild @@ -1,8 +1,8 @@ -# -# sample.vmsbuild -# -# $Id: //poco/1.2/Foundation/samples/grep/grep.vmsbuild#1 $ -# -EXE=grep -grep - +# +# sample.vmsbuild +# +# $Id: //poco/1.2/Foundation/samples/grep/grep.vmsbuild#1 $ +# +EXE=grep +grep + diff --git a/Foundation/samples/grep/grep_vs71.vcproj b/Foundation/samples/grep/grep_vs71.vcproj index 9a01157d8..02bc86ff7 100644 --- a/Foundation/samples/grep/grep_vs71.vcproj +++ b/Foundation/samples/grep/grep_vs71.vcproj @@ -1,149 +1,149 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Foundation/samples/grep/grep_vs80.vcproj b/Foundation/samples/grep/grep_vs80.vcproj index 792cc6220..71675f9f2 100644 --- a/Foundation/samples/grep/grep_vs80.vcproj +++ b/Foundation/samples/grep/grep_vs80.vcproj @@ -1,213 +1,213 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Foundation/samples/grep/src/grep.cpp b/Foundation/samples/grep/src/grep.cpp index 09b8b54ae..82a9b6bba 100644 --- a/Foundation/samples/grep/src/grep.cpp +++ b/Foundation/samples/grep/src/grep.cpp @@ -1,83 +1,83 @@ -// -// grep.cpp -// -// $Id: //poco/1.2/Foundation/samples/grep/src/grep.cpp#1 $ -// -// This sample demonstrates the RegularExpression class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/RegularExpression.h" -#include - - -using Poco::RegularExpression; - - -int main(int argc, char** argv) -{ - if (argc < 2) - { - std::cout << "usage: " << argv[0] << ": [-i] [-x] pattern" << std::endl; - return 1; - } - - std::string pattern; - int options = 0; - for (int i = 1; i < argc; ++i) - { - std::string arg(argv[i]); - if (arg == "-i") - options += RegularExpression::RE_CASELESS; - else if (arg == "-x") - options += RegularExpression::RE_EXTENDED; - else - pattern = arg; - } - - RegularExpression re(pattern, options); - - int c = std::cin.get(); - while (c != -1) - { - std::string line; - while (c != -1 && c != '\n') - { - line += (char) c; - c = std::cin.get(); - } - - RegularExpression::Match mtch; - if (re.match(line, mtch)) - std::cout << line << std::endl; - - if (c != -1) c = std::cin.get(); - } - - return 0; -} +// +// grep.cpp +// +// $Id: //poco/1.2/Foundation/samples/grep/src/grep.cpp#1 $ +// +// This sample demonstrates the RegularExpression class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/RegularExpression.h" +#include + + +using Poco::RegularExpression; + + +int main(int argc, char** argv) +{ + if (argc < 2) + { + std::cout << "usage: " << argv[0] << ": [-i] [-x] pattern" << std::endl; + return 1; + } + + std::string pattern; + int options = 0; + for (int i = 1; i < argc; ++i) + { + std::string arg(argv[i]); + if (arg == "-i") + options += RegularExpression::RE_CASELESS; + else if (arg == "-x") + options += RegularExpression::RE_EXTENDED; + else + pattern = arg; + } + + RegularExpression re(pattern, options); + + int c = std::cin.get(); + while (c != -1) + { + std::string line; + while (c != -1 && c != '\n') + { + line += (char) c; + c = std::cin.get(); + } + + RegularExpression::Match mtch; + if (re.match(line, mtch)) + std::cout << line << std::endl; + + if (c != -1) c = std::cin.get(); + } + + return 0; +} diff --git a/Foundation/samples/hmacmd5/Makefile b/Foundation/samples/hmacmd5/Makefile index 6c9386163..3f56ee3b3 100644 --- a/Foundation/samples/hmacmd5/Makefile +++ b/Foundation/samples/hmacmd5/Makefile @@ -1,17 +1,17 @@ -# -# Makefile -# -# $Id: //poco/1.2/Foundation/samples/hmacmd5/Makefile#1 $ -# -# Makefile for Poco hmacmd5 -# - -include $(POCO_BASE)/build/rules/global - -objects = hmacmd5 - -target = hmacmd5 -target_version = 1 -target_libs = PocoFoundation - -include $(POCO_BASE)/build/rules/exec +# +# Makefile +# +# $Id: //poco/1.2/Foundation/samples/hmacmd5/Makefile#1 $ +# +# Makefile for Poco hmacmd5 +# + +include $(POCO_BASE)/build/rules/global + +objects = hmacmd5 + +target = hmacmd5 +target_version = 1 +target_libs = PocoFoundation + +include $(POCO_BASE)/build/rules/exec diff --git a/Foundation/samples/hmacmd5/hmacmd5.vmsbuild b/Foundation/samples/hmacmd5/hmacmd5.vmsbuild index 0b2248605..853c8cc81 100644 --- a/Foundation/samples/hmacmd5/hmacmd5.vmsbuild +++ b/Foundation/samples/hmacmd5/hmacmd5.vmsbuild @@ -1,8 +1,8 @@ -# -# sample.vmsbuild -# -# $Id: //poco/1.2/Foundation/samples/hmacmd5/hmacmd5.vmsbuild#1 $ -# -EXE=hmacmd5 -hmacmd5 - +# +# sample.vmsbuild +# +# $Id: //poco/1.2/Foundation/samples/hmacmd5/hmacmd5.vmsbuild#1 $ +# +EXE=hmacmd5 +hmacmd5 + diff --git a/Foundation/samples/hmacmd5/hmacmd5_vs71.vcproj b/Foundation/samples/hmacmd5/hmacmd5_vs71.vcproj index b43e8c257..a6b6b6ff6 100644 --- a/Foundation/samples/hmacmd5/hmacmd5_vs71.vcproj +++ b/Foundation/samples/hmacmd5/hmacmd5_vs71.vcproj @@ -1,149 +1,149 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Foundation/samples/hmacmd5/hmacmd5_vs80.vcproj b/Foundation/samples/hmacmd5/hmacmd5_vs80.vcproj index f82049b90..b653f8ea3 100644 --- a/Foundation/samples/hmacmd5/hmacmd5_vs80.vcproj +++ b/Foundation/samples/hmacmd5/hmacmd5_vs80.vcproj @@ -1,213 +1,213 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Foundation/samples/hmacmd5/src/hmacmd5.cpp b/Foundation/samples/hmacmd5/src/hmacmd5.cpp index b221f79c4..238dbba9e 100644 --- a/Foundation/samples/hmacmd5/src/hmacmd5.cpp +++ b/Foundation/samples/hmacmd5/src/hmacmd5.cpp @@ -1,77 +1,77 @@ -// -// hmacmd5.cpp -// -// $Id: //poco/1.2/Foundation/samples/hmacmd5/src/hmacmd5.cpp#1 $ -// -// This sample demonstrates the HMACEngine class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/HMACEngine.h" -#include "Poco/MD5Engine.h" -#include "Poco/DigestStream.h" -#include "Poco/StreamCopier.h" -#include -#include - - -using Poco::DigestEngine; -using Poco::HMACEngine; -using Poco::MD5Engine; -using Poco::DigestOutputStream; -using Poco::StreamCopier; - - -int main(int argc, char** argv) -{ - if (argc != 3) - { - std::cout << "usage: " << argv[0] << ": " << std::endl - << " create the HMAC-MD5 for , using " << std::endl; - return 1; - } - - std::string passphrase(argv[1]); - - std::ifstream istr(argv[2], std::ios::binary); - if (!istr) - { - std::cerr << "cannot open input file: " << argv[2] << std::endl; - return 2; - } - - HMACEngine hmac(passphrase); - DigestOutputStream dos(hmac); - - StreamCopier::copyStream(istr, dos); - dos.close(); - - std::cout << DigestEngine::digestToHex(hmac.digest()) << std::endl; - - return 0; -} +// +// hmacmd5.cpp +// +// $Id: //poco/1.2/Foundation/samples/hmacmd5/src/hmacmd5.cpp#1 $ +// +// This sample demonstrates the HMACEngine class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/HMACEngine.h" +#include "Poco/MD5Engine.h" +#include "Poco/DigestStream.h" +#include "Poco/StreamCopier.h" +#include +#include + + +using Poco::DigestEngine; +using Poco::HMACEngine; +using Poco::MD5Engine; +using Poco::DigestOutputStream; +using Poco::StreamCopier; + + +int main(int argc, char** argv) +{ + if (argc != 3) + { + std::cout << "usage: " << argv[0] << ": " << std::endl + << " create the HMAC-MD5 for , using " << std::endl; + return 1; + } + + std::string passphrase(argv[1]); + + std::ifstream istr(argv[2], std::ios::binary); + if (!istr) + { + std::cerr << "cannot open input file: " << argv[2] << std::endl; + return 2; + } + + HMACEngine hmac(passphrase); + DigestOutputStream dos(hmac); + + StreamCopier::copyStream(istr, dos); + dos.close(); + + std::cout << DigestEngine::digestToHex(hmac.digest()) << std::endl; + + return 0; +} diff --git a/Foundation/samples/inflate/Makefile b/Foundation/samples/inflate/Makefile index 408f9f48a..6aaa7f975 100644 --- a/Foundation/samples/inflate/Makefile +++ b/Foundation/samples/inflate/Makefile @@ -1,17 +1,17 @@ -# -# Makefile -# -# $Id: //poco/1.2/Foundation/samples/inflate/Makefile#1 $ -# -# Makefile for Poco inflate -# - -include $(POCO_BASE)/build/rules/global - -objects = inflate - -target = inflate -target_version = 1 -target_libs = PocoFoundation - -include $(POCO_BASE)/build/rules/exec +# +# Makefile +# +# $Id: //poco/1.2/Foundation/samples/inflate/Makefile#1 $ +# +# Makefile for Poco inflate +# + +include $(POCO_BASE)/build/rules/global + +objects = inflate + +target = inflate +target_version = 1 +target_libs = PocoFoundation + +include $(POCO_BASE)/build/rules/exec diff --git a/Foundation/samples/inflate/inflate.vmsbuild b/Foundation/samples/inflate/inflate.vmsbuild index 15e99619b..78e313a85 100644 --- a/Foundation/samples/inflate/inflate.vmsbuild +++ b/Foundation/samples/inflate/inflate.vmsbuild @@ -1,8 +1,8 @@ -# -# sample.vmsbuild -# -# $Id: //poco/1.2/Foundation/samples/inflate/inflate.vmsbuild#1 $ -# -EXE=inflate -inflate - +# +# sample.vmsbuild +# +# $Id: //poco/1.2/Foundation/samples/inflate/inflate.vmsbuild#1 $ +# +EXE=inflate +inflate + diff --git a/Foundation/samples/inflate/inflate_vs71.vcproj b/Foundation/samples/inflate/inflate_vs71.vcproj index e923fb654..6199379e1 100644 --- a/Foundation/samples/inflate/inflate_vs71.vcproj +++ b/Foundation/samples/inflate/inflate_vs71.vcproj @@ -1,149 +1,149 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Foundation/samples/inflate/inflate_vs80.vcproj b/Foundation/samples/inflate/inflate_vs80.vcproj index 7a8e91700..9f13869d7 100644 --- a/Foundation/samples/inflate/inflate_vs80.vcproj +++ b/Foundation/samples/inflate/inflate_vs80.vcproj @@ -1,213 +1,213 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Foundation/samples/inflate/src/inflate.cpp b/Foundation/samples/inflate/src/inflate.cpp index 8c408feae..ba99b27a8 100644 --- a/Foundation/samples/inflate/src/inflate.cpp +++ b/Foundation/samples/inflate/src/inflate.cpp @@ -1,78 +1,78 @@ -// -// inflate.cpp -// -// $Id: //poco/1.2/Foundation/samples/inflate/src/inflate.cpp#1 $ -// -// This sample demonstrates the InflatingInputStream and StreamCopier classes. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/InflatingStream.h" -#include "Poco/StreamCopier.h" -#include -#include - - -using Poco::InflatingInputStream; -using Poco::StreamCopier; - - -int main(int argc, char** argv) -{ - if (argc != 3) - { - std::cout << "usage: " << argv[0] << ": " << std::endl - << " read deflated (compressed) , inflate it and write the result to " << std::endl; - return 1; - } - - std::ifstream istr(argv[1], std::ios::binary); - if (!istr) - { - std::cerr << "cannot open input file: " << argv[1] << std::endl; - return 2; - } - - std::ofstream ostr(argv[2], std::ios::binary); - if (!ostr) - { - std::cerr << "cannot open output file: " << argv[2] << std::endl; - return 3; - } - - InflatingInputStream inflater(istr); - StreamCopier::copyStream(inflater, ostr); - - if (!ostr) - { - std::cerr << "error writing output file: " << argv[2] << std::endl; - return 4; - } - - return 0; -} +// +// inflate.cpp +// +// $Id: //poco/1.2/Foundation/samples/inflate/src/inflate.cpp#1 $ +// +// This sample demonstrates the InflatingInputStream and StreamCopier classes. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/InflatingStream.h" +#include "Poco/StreamCopier.h" +#include +#include + + +using Poco::InflatingInputStream; +using Poco::StreamCopier; + + +int main(int argc, char** argv) +{ + if (argc != 3) + { + std::cout << "usage: " << argv[0] << ": " << std::endl + << " read deflated (compressed) , inflate it and write the result to " << std::endl; + return 1; + } + + std::ifstream istr(argv[1], std::ios::binary); + if (!istr) + { + std::cerr << "cannot open input file: " << argv[1] << std::endl; + return 2; + } + + std::ofstream ostr(argv[2], std::ios::binary); + if (!ostr) + { + std::cerr << "cannot open output file: " << argv[2] << std::endl; + return 3; + } + + InflatingInputStream inflater(istr); + StreamCopier::copyStream(inflater, ostr); + + if (!ostr) + { + std::cerr << "error writing output file: " << argv[2] << std::endl; + return 4; + } + + return 0; +} diff --git a/Foundation/samples/md5/Makefile b/Foundation/samples/md5/Makefile index a5ef4f19a..c536d6a7f 100644 --- a/Foundation/samples/md5/Makefile +++ b/Foundation/samples/md5/Makefile @@ -1,17 +1,17 @@ -# -# Makefile -# -# $Id: //poco/1.2/Foundation/samples/md5/Makefile#1 $ -# -# Makefile for Poco md5 -# - -include $(POCO_BASE)/build/rules/global - -objects = md5 - -target = md5 -target_version = 1 -target_libs = PocoFoundation - -include $(POCO_BASE)/build/rules/exec +# +# Makefile +# +# $Id: //poco/1.2/Foundation/samples/md5/Makefile#1 $ +# +# Makefile for Poco md5 +# + +include $(POCO_BASE)/build/rules/global + +objects = md5 + +target = md5 +target_version = 1 +target_libs = PocoFoundation + +include $(POCO_BASE)/build/rules/exec diff --git a/Foundation/samples/md5/md5.vmsbuild b/Foundation/samples/md5/md5.vmsbuild index 333e79741..5c4e44029 100644 --- a/Foundation/samples/md5/md5.vmsbuild +++ b/Foundation/samples/md5/md5.vmsbuild @@ -1,8 +1,8 @@ -# -# sample.vmsbuild -# -# $Id: //poco/1.2/Foundation/samples/md5/md5.vmsbuild#1 $ -# -EXE=md5 -md5 - +# +# sample.vmsbuild +# +# $Id: //poco/1.2/Foundation/samples/md5/md5.vmsbuild#1 $ +# +EXE=md5 +md5 + diff --git a/Foundation/samples/md5/md5_vs71.vcproj b/Foundation/samples/md5/md5_vs71.vcproj index 357109c0b..62fca1cda 100644 --- a/Foundation/samples/md5/md5_vs71.vcproj +++ b/Foundation/samples/md5/md5_vs71.vcproj @@ -1,149 +1,149 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Foundation/samples/md5/md5_vs80.vcproj b/Foundation/samples/md5/md5_vs80.vcproj index b66f3fb93..f00cc9dd1 100644 --- a/Foundation/samples/md5/md5_vs80.vcproj +++ b/Foundation/samples/md5/md5_vs80.vcproj @@ -1,213 +1,213 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Foundation/samples/md5/src/md5.cpp b/Foundation/samples/md5/src/md5.cpp index e1d3aac93..a5bc2e92d 100644 --- a/Foundation/samples/md5/src/md5.cpp +++ b/Foundation/samples/md5/src/md5.cpp @@ -1,74 +1,74 @@ -// -// md5.cpp -// -// $Id: //poco/1.2/Foundation/samples/md5/src/md5.cpp#1 $ -// -// This sample demonstrates the DigestEngine, DigestOutputStream and -// MD5Engine classes. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/MD5Engine.h" -#include "Poco/DigestStream.h" -#include "Poco/StreamCopier.h" -#include -#include - - -using Poco::DigestEngine; -using Poco::MD5Engine; -using Poco::DigestOutputStream; -using Poco::StreamCopier; - - -int main(int argc, char** argv) -{ - if (argc != 2) - { - std::cout << "usage: " << argv[0] << ": " << std::endl - << " create the MD5 digest for " << std::endl; - return 1; - } - - std::ifstream istr(argv[1], std::ios::binary); - if (!istr) - { - std::cerr << "cannot open input file: " << argv[1] << std::endl; - return 2; - } - - MD5Engine md5; - DigestOutputStream dos(md5); - - StreamCopier::copyStream(istr, dos); - dos.close(); - - std::cout << DigestEngine::digestToHex(md5.digest()) << std::endl; - - return 0; -} +// +// md5.cpp +// +// $Id: //poco/1.2/Foundation/samples/md5/src/md5.cpp#1 $ +// +// This sample demonstrates the DigestEngine, DigestOutputStream and +// MD5Engine classes. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/MD5Engine.h" +#include "Poco/DigestStream.h" +#include "Poco/StreamCopier.h" +#include +#include + + +using Poco::DigestEngine; +using Poco::MD5Engine; +using Poco::DigestOutputStream; +using Poco::StreamCopier; + + +int main(int argc, char** argv) +{ + if (argc != 2) + { + std::cout << "usage: " << argv[0] << ": " << std::endl + << " create the MD5 digest for " << std::endl; + return 1; + } + + std::ifstream istr(argv[1], std::ios::binary); + if (!istr) + { + std::cerr << "cannot open input file: " << argv[1] << std::endl; + return 2; + } + + MD5Engine md5; + DigestOutputStream dos(md5); + + StreamCopier::copyStream(istr, dos); + dos.close(); + + std::cout << DigestEngine::digestToHex(md5.digest()) << std::endl; + + return 0; +} diff --git a/Foundation/samples/samples_vs71.sln b/Foundation/samples/samples_vs71.sln index fed58647b..875d2a52a 100644 --- a/Foundation/samples/samples_vs71.sln +++ b/Foundation/samples/samples_vs71.sln @@ -1,157 +1,157 @@ -Microsoft Visual Studio Solution File, Format Version 8.00 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "StringTokenizer", "StringTokenizer\StringTokenizer_vs71.vcproj", "{D49346E0-4F69-4BEC-9380-32D55D48063F}" - ProjectSection(ProjectDependencies) = postProject - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "base64encode", "base64encode\base64encode_vs71.vcproj", "{F325FEFC-2ADF-473D-8CBF-F6D54DB1AD8D}" - ProjectSection(ProjectDependencies) = postProject - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "base64decode", "base64decode\base64decode_vs71.vcproj", "{F9602261-CD9E-44E0-82D1-A1F30AA5CB67}" - ProjectSection(ProjectDependencies) = postProject - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "BinaryReaderWriter", "BinaryReaderWriter\BinaryReaderWriter_vs71.vcproj", "{9FFF12D2-4DCC-4AC2-AF3D-7FADBE7EE711}" - ProjectSection(ProjectDependencies) = postProject - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "deflate", "deflate\deflate_vs71.vcproj", "{188E8EB7-EE1C-4485-9C0A-52BAD6A30BE1}" - ProjectSection(ProjectDependencies) = postProject - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "inflate", "inflate\inflate_vs71.vcproj", "{60D48C6D-53D0-41E1-BFA0-8A6C354C6EE9}" - ProjectSection(ProjectDependencies) = postProject - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "md5", "md5\md5_vs71.vcproj", "{DB54AA95-8EA1-4950-9B59-1917A86B7E45}" - ProjectSection(ProjectDependencies) = postProject - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "hmacmd5", "hmacmd5\hmacmd5_vs71.vcproj", "{D6A19A85-C8EC-4EAC-B495-246E4D7C5EF6}" - ProjectSection(ProjectDependencies) = postProject - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "grep", "grep\grep_vs71.vcproj", "{52626367-962B-44AA-9750-42F55EDA292E}" - ProjectSection(ProjectDependencies) = postProject - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Logger", "Logger\Logger_vs71.vcproj", "{E7CE21A7-3D50-485E-9B68-E1BEC97ED2E3}" - ProjectSection(ProjectDependencies) = postProject - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "NotificationQueue", "NotificationQueue\NotificationQueue_vs71.vcproj", "{DB9948BB-A40E-4010-8E5E-DDCDFC1B8EFD}" - ProjectSection(ProjectDependencies) = postProject - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "dir", "dir\dir_vs71.vcproj", "{AA18CF6F-3B7F-4A92-9464-4DC07A758E2C}" - ProjectSection(ProjectDependencies) = postProject - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "DateTime", "DateTime\DateTime_vs71.vcproj", "{1413EE43-C5FC-45C2-AF6E-4EF10C8BF34E}" - ProjectSection(ProjectDependencies) = postProject - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "uuidgen", "uuidgen\uuidgen_vs71.vcproj", "{4A208D55-894A-4653-9F75-89D1373D9DA7}" - ProjectSection(ProjectDependencies) = postProject - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "URI", "URI\URI_vs71.vcproj", "{C4AA83D3-3BDF-4415-ADD3-057E16BB4261}" - ProjectSection(ProjectDependencies) = postProject - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Timer", "Timer\Timer_vs71.vcproj", "{DE2611F3-CC74-433C-9020-B9BB162CE89F}" - ProjectSection(ProjectDependencies) = postProject - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Activity", "Activity\Activity_vs71.vcproj", "{53851B48-4DAD-4B38-9BB4-5C747F9C62B1}" - ProjectSection(ProjectDependencies) = postProject - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ActiveMethod", "ActiveMethod\ActiveMethod_vs71.vcproj", "{0A3E3912-4205-41CA-BCCE-261FA564D3C7}" - ProjectSection(ProjectDependencies) = postProject - EndProjectSection -EndProject -Global - GlobalSection(SolutionConfiguration) = preSolution - debug_shared = debug_shared - release_shared = release_shared - EndGlobalSection - GlobalSection(ProjectConfiguration) = postSolution - {D49346E0-4F69-4BEC-9380-32D55D48063F}.debug_shared.ActiveCfg = debug_shared|Win32 - {D49346E0-4F69-4BEC-9380-32D55D48063F}.debug_shared.Build.0 = debug_shared|Win32 - {D49346E0-4F69-4BEC-9380-32D55D48063F}.release_shared.ActiveCfg = release_shared|Win32 - {D49346E0-4F69-4BEC-9380-32D55D48063F}.release_shared.Build.0 = release_shared|Win32 - {F325FEFC-2ADF-473D-8CBF-F6D54DB1AD8D}.debug_shared.ActiveCfg = debug_shared|Win32 - {F325FEFC-2ADF-473D-8CBF-F6D54DB1AD8D}.debug_shared.Build.0 = debug_shared|Win32 - {F325FEFC-2ADF-473D-8CBF-F6D54DB1AD8D}.release_shared.ActiveCfg = release_shared|Win32 - {F325FEFC-2ADF-473D-8CBF-F6D54DB1AD8D}.release_shared.Build.0 = release_shared|Win32 - {F9602261-CD9E-44E0-82D1-A1F30AA5CB67}.debug_shared.ActiveCfg = debug_shared|Win32 - {F9602261-CD9E-44E0-82D1-A1F30AA5CB67}.debug_shared.Build.0 = debug_shared|Win32 - {F9602261-CD9E-44E0-82D1-A1F30AA5CB67}.release_shared.ActiveCfg = release_shared|Win32 - {F9602261-CD9E-44E0-82D1-A1F30AA5CB67}.release_shared.Build.0 = release_shared|Win32 - {9FFF12D2-4DCC-4AC2-AF3D-7FADBE7EE711}.debug_shared.ActiveCfg = debug_shared|Win32 - {9FFF12D2-4DCC-4AC2-AF3D-7FADBE7EE711}.debug_shared.Build.0 = debug_shared|Win32 - {9FFF12D2-4DCC-4AC2-AF3D-7FADBE7EE711}.release_shared.ActiveCfg = release_shared|Win32 - {9FFF12D2-4DCC-4AC2-AF3D-7FADBE7EE711}.release_shared.Build.0 = release_shared|Win32 - {188E8EB7-EE1C-4485-9C0A-52BAD6A30BE1}.debug_shared.ActiveCfg = debug_shared|Win32 - {188E8EB7-EE1C-4485-9C0A-52BAD6A30BE1}.debug_shared.Build.0 = debug_shared|Win32 - {188E8EB7-EE1C-4485-9C0A-52BAD6A30BE1}.release_shared.ActiveCfg = release_shared|Win32 - {188E8EB7-EE1C-4485-9C0A-52BAD6A30BE1}.release_shared.Build.0 = release_shared|Win32 - {60D48C6D-53D0-41E1-BFA0-8A6C354C6EE9}.debug_shared.ActiveCfg = debug_shared|Win32 - {60D48C6D-53D0-41E1-BFA0-8A6C354C6EE9}.debug_shared.Build.0 = debug_shared|Win32 - {60D48C6D-53D0-41E1-BFA0-8A6C354C6EE9}.release_shared.ActiveCfg = release_shared|Win32 - {60D48C6D-53D0-41E1-BFA0-8A6C354C6EE9}.release_shared.Build.0 = release_shared|Win32 - {DB54AA95-8EA1-4950-9B59-1917A86B7E45}.debug_shared.ActiveCfg = debug_shared|Win32 - {DB54AA95-8EA1-4950-9B59-1917A86B7E45}.debug_shared.Build.0 = debug_shared|Win32 - {DB54AA95-8EA1-4950-9B59-1917A86B7E45}.release_shared.ActiveCfg = release_shared|Win32 - {DB54AA95-8EA1-4950-9B59-1917A86B7E45}.release_shared.Build.0 = release_shared|Win32 - {D6A19A85-C8EC-4EAC-B495-246E4D7C5EF6}.debug_shared.ActiveCfg = debug_shared|Win32 - {D6A19A85-C8EC-4EAC-B495-246E4D7C5EF6}.debug_shared.Build.0 = debug_shared|Win32 - {D6A19A85-C8EC-4EAC-B495-246E4D7C5EF6}.release_shared.ActiveCfg = release_shared|Win32 - {D6A19A85-C8EC-4EAC-B495-246E4D7C5EF6}.release_shared.Build.0 = release_shared|Win32 - {52626367-962B-44AA-9750-42F55EDA292E}.debug_shared.ActiveCfg = debug_shared|Win32 - {52626367-962B-44AA-9750-42F55EDA292E}.debug_shared.Build.0 = debug_shared|Win32 - {52626367-962B-44AA-9750-42F55EDA292E}.release_shared.ActiveCfg = release_shared|Win32 - {52626367-962B-44AA-9750-42F55EDA292E}.release_shared.Build.0 = release_shared|Win32 - {E7CE21A7-3D50-485E-9B68-E1BEC97ED2E3}.debug_shared.ActiveCfg = debug_shared|Win32 - {E7CE21A7-3D50-485E-9B68-E1BEC97ED2E3}.debug_shared.Build.0 = debug_shared|Win32 - {E7CE21A7-3D50-485E-9B68-E1BEC97ED2E3}.release_shared.ActiveCfg = release_shared|Win32 - {E7CE21A7-3D50-485E-9B68-E1BEC97ED2E3}.release_shared.Build.0 = release_shared|Win32 - {DB9948BB-A40E-4010-8E5E-DDCDFC1B8EFD}.debug_shared.ActiveCfg = debug_shared|Win32 - {DB9948BB-A40E-4010-8E5E-DDCDFC1B8EFD}.debug_shared.Build.0 = debug_shared|Win32 - {DB9948BB-A40E-4010-8E5E-DDCDFC1B8EFD}.release_shared.ActiveCfg = release_shared|Win32 - {DB9948BB-A40E-4010-8E5E-DDCDFC1B8EFD}.release_shared.Build.0 = release_shared|Win32 - {AA18CF6F-3B7F-4A92-9464-4DC07A758E2C}.debug_shared.ActiveCfg = debug_shared|Win32 - {AA18CF6F-3B7F-4A92-9464-4DC07A758E2C}.debug_shared.Build.0 = debug_shared|Win32 - {AA18CF6F-3B7F-4A92-9464-4DC07A758E2C}.release_shared.ActiveCfg = release_shared|Win32 - {AA18CF6F-3B7F-4A92-9464-4DC07A758E2C}.release_shared.Build.0 = release_shared|Win32 - {1413EE43-C5FC-45C2-AF6E-4EF10C8BF34E}.debug_shared.ActiveCfg = debug_shared|Win32 - {1413EE43-C5FC-45C2-AF6E-4EF10C8BF34E}.debug_shared.Build.0 = debug_shared|Win32 - {1413EE43-C5FC-45C2-AF6E-4EF10C8BF34E}.release_shared.ActiveCfg = release_shared|Win32 - {1413EE43-C5FC-45C2-AF6E-4EF10C8BF34E}.release_shared.Build.0 = release_shared|Win32 - {4A208D55-894A-4653-9F75-89D1373D9DA7}.debug_shared.ActiveCfg = debug_shared|Win32 - {4A208D55-894A-4653-9F75-89D1373D9DA7}.debug_shared.Build.0 = debug_shared|Win32 - {4A208D55-894A-4653-9F75-89D1373D9DA7}.release_shared.ActiveCfg = release_shared|Win32 - {4A208D55-894A-4653-9F75-89D1373D9DA7}.release_shared.Build.0 = release_shared|Win32 - {C4AA83D3-3BDF-4415-ADD3-057E16BB4261}.debug_shared.ActiveCfg = debug_shared|Win32 - {C4AA83D3-3BDF-4415-ADD3-057E16BB4261}.debug_shared.Build.0 = debug_shared|Win32 - {C4AA83D3-3BDF-4415-ADD3-057E16BB4261}.release_shared.ActiveCfg = release_shared|Win32 - {C4AA83D3-3BDF-4415-ADD3-057E16BB4261}.release_shared.Build.0 = release_shared|Win32 - {DE2611F3-CC74-433C-9020-B9BB162CE89F}.debug_shared.ActiveCfg = debug_shared|Win32 - {DE2611F3-CC74-433C-9020-B9BB162CE89F}.debug_shared.Build.0 = debug_shared|Win32 - {DE2611F3-CC74-433C-9020-B9BB162CE89F}.release_shared.ActiveCfg = release_shared|Win32 - {DE2611F3-CC74-433C-9020-B9BB162CE89F}.release_shared.Build.0 = release_shared|Win32 - {53851B48-4DAD-4B38-9BB4-5C747F9C62B1}.debug_shared.ActiveCfg = debug_shared|Win32 - {53851B48-4DAD-4B38-9BB4-5C747F9C62B1}.debug_shared.Build.0 = debug_shared|Win32 - {53851B48-4DAD-4B38-9BB4-5C747F9C62B1}.release_shared.ActiveCfg = release_shared|Win32 - {53851B48-4DAD-4B38-9BB4-5C747F9C62B1}.release_shared.Build.0 = release_shared|Win32 - {0A3E3912-4205-41CA-BCCE-261FA564D3C7}.debug_shared.ActiveCfg = debug_shared|Win32 - {0A3E3912-4205-41CA-BCCE-261FA564D3C7}.debug_shared.Build.0 = debug_shared|Win32 - {0A3E3912-4205-41CA-BCCE-261FA564D3C7}.release_shared.ActiveCfg = release_shared|Win32 - {0A3E3912-4205-41CA-BCCE-261FA564D3C7}.release_shared.Build.0 = release_shared|Win32 - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - EndGlobalSection - GlobalSection(ExtensibilityAddIns) = postSolution - EndGlobalSection -EndGlobal +Microsoft Visual Studio Solution File, Format Version 8.00 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "StringTokenizer", "StringTokenizer\StringTokenizer_vs71.vcproj", "{D49346E0-4F69-4BEC-9380-32D55D48063F}" + ProjectSection(ProjectDependencies) = postProject + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "base64encode", "base64encode\base64encode_vs71.vcproj", "{F325FEFC-2ADF-473D-8CBF-F6D54DB1AD8D}" + ProjectSection(ProjectDependencies) = postProject + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "base64decode", "base64decode\base64decode_vs71.vcproj", "{F9602261-CD9E-44E0-82D1-A1F30AA5CB67}" + ProjectSection(ProjectDependencies) = postProject + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "BinaryReaderWriter", "BinaryReaderWriter\BinaryReaderWriter_vs71.vcproj", "{9FFF12D2-4DCC-4AC2-AF3D-7FADBE7EE711}" + ProjectSection(ProjectDependencies) = postProject + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "deflate", "deflate\deflate_vs71.vcproj", "{188E8EB7-EE1C-4485-9C0A-52BAD6A30BE1}" + ProjectSection(ProjectDependencies) = postProject + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "inflate", "inflate\inflate_vs71.vcproj", "{60D48C6D-53D0-41E1-BFA0-8A6C354C6EE9}" + ProjectSection(ProjectDependencies) = postProject + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "md5", "md5\md5_vs71.vcproj", "{DB54AA95-8EA1-4950-9B59-1917A86B7E45}" + ProjectSection(ProjectDependencies) = postProject + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "hmacmd5", "hmacmd5\hmacmd5_vs71.vcproj", "{D6A19A85-C8EC-4EAC-B495-246E4D7C5EF6}" + ProjectSection(ProjectDependencies) = postProject + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "grep", "grep\grep_vs71.vcproj", "{52626367-962B-44AA-9750-42F55EDA292E}" + ProjectSection(ProjectDependencies) = postProject + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Logger", "Logger\Logger_vs71.vcproj", "{E7CE21A7-3D50-485E-9B68-E1BEC97ED2E3}" + ProjectSection(ProjectDependencies) = postProject + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "NotificationQueue", "NotificationQueue\NotificationQueue_vs71.vcproj", "{DB9948BB-A40E-4010-8E5E-DDCDFC1B8EFD}" + ProjectSection(ProjectDependencies) = postProject + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "dir", "dir\dir_vs71.vcproj", "{AA18CF6F-3B7F-4A92-9464-4DC07A758E2C}" + ProjectSection(ProjectDependencies) = postProject + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "DateTime", "DateTime\DateTime_vs71.vcproj", "{1413EE43-C5FC-45C2-AF6E-4EF10C8BF34E}" + ProjectSection(ProjectDependencies) = postProject + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "uuidgen", "uuidgen\uuidgen_vs71.vcproj", "{4A208D55-894A-4653-9F75-89D1373D9DA7}" + ProjectSection(ProjectDependencies) = postProject + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "URI", "URI\URI_vs71.vcproj", "{C4AA83D3-3BDF-4415-ADD3-057E16BB4261}" + ProjectSection(ProjectDependencies) = postProject + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Timer", "Timer\Timer_vs71.vcproj", "{DE2611F3-CC74-433C-9020-B9BB162CE89F}" + ProjectSection(ProjectDependencies) = postProject + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Activity", "Activity\Activity_vs71.vcproj", "{53851B48-4DAD-4B38-9BB4-5C747F9C62B1}" + ProjectSection(ProjectDependencies) = postProject + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ActiveMethod", "ActiveMethod\ActiveMethod_vs71.vcproj", "{0A3E3912-4205-41CA-BCCE-261FA564D3C7}" + ProjectSection(ProjectDependencies) = postProject + EndProjectSection +EndProject +Global + GlobalSection(SolutionConfiguration) = preSolution + debug_shared = debug_shared + release_shared = release_shared + EndGlobalSection + GlobalSection(ProjectConfiguration) = postSolution + {D49346E0-4F69-4BEC-9380-32D55D48063F}.debug_shared.ActiveCfg = debug_shared|Win32 + {D49346E0-4F69-4BEC-9380-32D55D48063F}.debug_shared.Build.0 = debug_shared|Win32 + {D49346E0-4F69-4BEC-9380-32D55D48063F}.release_shared.ActiveCfg = release_shared|Win32 + {D49346E0-4F69-4BEC-9380-32D55D48063F}.release_shared.Build.0 = release_shared|Win32 + {F325FEFC-2ADF-473D-8CBF-F6D54DB1AD8D}.debug_shared.ActiveCfg = debug_shared|Win32 + {F325FEFC-2ADF-473D-8CBF-F6D54DB1AD8D}.debug_shared.Build.0 = debug_shared|Win32 + {F325FEFC-2ADF-473D-8CBF-F6D54DB1AD8D}.release_shared.ActiveCfg = release_shared|Win32 + {F325FEFC-2ADF-473D-8CBF-F6D54DB1AD8D}.release_shared.Build.0 = release_shared|Win32 + {F9602261-CD9E-44E0-82D1-A1F30AA5CB67}.debug_shared.ActiveCfg = debug_shared|Win32 + {F9602261-CD9E-44E0-82D1-A1F30AA5CB67}.debug_shared.Build.0 = debug_shared|Win32 + {F9602261-CD9E-44E0-82D1-A1F30AA5CB67}.release_shared.ActiveCfg = release_shared|Win32 + {F9602261-CD9E-44E0-82D1-A1F30AA5CB67}.release_shared.Build.0 = release_shared|Win32 + {9FFF12D2-4DCC-4AC2-AF3D-7FADBE7EE711}.debug_shared.ActiveCfg = debug_shared|Win32 + {9FFF12D2-4DCC-4AC2-AF3D-7FADBE7EE711}.debug_shared.Build.0 = debug_shared|Win32 + {9FFF12D2-4DCC-4AC2-AF3D-7FADBE7EE711}.release_shared.ActiveCfg = release_shared|Win32 + {9FFF12D2-4DCC-4AC2-AF3D-7FADBE7EE711}.release_shared.Build.0 = release_shared|Win32 + {188E8EB7-EE1C-4485-9C0A-52BAD6A30BE1}.debug_shared.ActiveCfg = debug_shared|Win32 + {188E8EB7-EE1C-4485-9C0A-52BAD6A30BE1}.debug_shared.Build.0 = debug_shared|Win32 + {188E8EB7-EE1C-4485-9C0A-52BAD6A30BE1}.release_shared.ActiveCfg = release_shared|Win32 + {188E8EB7-EE1C-4485-9C0A-52BAD6A30BE1}.release_shared.Build.0 = release_shared|Win32 + {60D48C6D-53D0-41E1-BFA0-8A6C354C6EE9}.debug_shared.ActiveCfg = debug_shared|Win32 + {60D48C6D-53D0-41E1-BFA0-8A6C354C6EE9}.debug_shared.Build.0 = debug_shared|Win32 + {60D48C6D-53D0-41E1-BFA0-8A6C354C6EE9}.release_shared.ActiveCfg = release_shared|Win32 + {60D48C6D-53D0-41E1-BFA0-8A6C354C6EE9}.release_shared.Build.0 = release_shared|Win32 + {DB54AA95-8EA1-4950-9B59-1917A86B7E45}.debug_shared.ActiveCfg = debug_shared|Win32 + {DB54AA95-8EA1-4950-9B59-1917A86B7E45}.debug_shared.Build.0 = debug_shared|Win32 + {DB54AA95-8EA1-4950-9B59-1917A86B7E45}.release_shared.ActiveCfg = release_shared|Win32 + {DB54AA95-8EA1-4950-9B59-1917A86B7E45}.release_shared.Build.0 = release_shared|Win32 + {D6A19A85-C8EC-4EAC-B495-246E4D7C5EF6}.debug_shared.ActiveCfg = debug_shared|Win32 + {D6A19A85-C8EC-4EAC-B495-246E4D7C5EF6}.debug_shared.Build.0 = debug_shared|Win32 + {D6A19A85-C8EC-4EAC-B495-246E4D7C5EF6}.release_shared.ActiveCfg = release_shared|Win32 + {D6A19A85-C8EC-4EAC-B495-246E4D7C5EF6}.release_shared.Build.0 = release_shared|Win32 + {52626367-962B-44AA-9750-42F55EDA292E}.debug_shared.ActiveCfg = debug_shared|Win32 + {52626367-962B-44AA-9750-42F55EDA292E}.debug_shared.Build.0 = debug_shared|Win32 + {52626367-962B-44AA-9750-42F55EDA292E}.release_shared.ActiveCfg = release_shared|Win32 + {52626367-962B-44AA-9750-42F55EDA292E}.release_shared.Build.0 = release_shared|Win32 + {E7CE21A7-3D50-485E-9B68-E1BEC97ED2E3}.debug_shared.ActiveCfg = debug_shared|Win32 + {E7CE21A7-3D50-485E-9B68-E1BEC97ED2E3}.debug_shared.Build.0 = debug_shared|Win32 + {E7CE21A7-3D50-485E-9B68-E1BEC97ED2E3}.release_shared.ActiveCfg = release_shared|Win32 + {E7CE21A7-3D50-485E-9B68-E1BEC97ED2E3}.release_shared.Build.0 = release_shared|Win32 + {DB9948BB-A40E-4010-8E5E-DDCDFC1B8EFD}.debug_shared.ActiveCfg = debug_shared|Win32 + {DB9948BB-A40E-4010-8E5E-DDCDFC1B8EFD}.debug_shared.Build.0 = debug_shared|Win32 + {DB9948BB-A40E-4010-8E5E-DDCDFC1B8EFD}.release_shared.ActiveCfg = release_shared|Win32 + {DB9948BB-A40E-4010-8E5E-DDCDFC1B8EFD}.release_shared.Build.0 = release_shared|Win32 + {AA18CF6F-3B7F-4A92-9464-4DC07A758E2C}.debug_shared.ActiveCfg = debug_shared|Win32 + {AA18CF6F-3B7F-4A92-9464-4DC07A758E2C}.debug_shared.Build.0 = debug_shared|Win32 + {AA18CF6F-3B7F-4A92-9464-4DC07A758E2C}.release_shared.ActiveCfg = release_shared|Win32 + {AA18CF6F-3B7F-4A92-9464-4DC07A758E2C}.release_shared.Build.0 = release_shared|Win32 + {1413EE43-C5FC-45C2-AF6E-4EF10C8BF34E}.debug_shared.ActiveCfg = debug_shared|Win32 + {1413EE43-C5FC-45C2-AF6E-4EF10C8BF34E}.debug_shared.Build.0 = debug_shared|Win32 + {1413EE43-C5FC-45C2-AF6E-4EF10C8BF34E}.release_shared.ActiveCfg = release_shared|Win32 + {1413EE43-C5FC-45C2-AF6E-4EF10C8BF34E}.release_shared.Build.0 = release_shared|Win32 + {4A208D55-894A-4653-9F75-89D1373D9DA7}.debug_shared.ActiveCfg = debug_shared|Win32 + {4A208D55-894A-4653-9F75-89D1373D9DA7}.debug_shared.Build.0 = debug_shared|Win32 + {4A208D55-894A-4653-9F75-89D1373D9DA7}.release_shared.ActiveCfg = release_shared|Win32 + {4A208D55-894A-4653-9F75-89D1373D9DA7}.release_shared.Build.0 = release_shared|Win32 + {C4AA83D3-3BDF-4415-ADD3-057E16BB4261}.debug_shared.ActiveCfg = debug_shared|Win32 + {C4AA83D3-3BDF-4415-ADD3-057E16BB4261}.debug_shared.Build.0 = debug_shared|Win32 + {C4AA83D3-3BDF-4415-ADD3-057E16BB4261}.release_shared.ActiveCfg = release_shared|Win32 + {C4AA83D3-3BDF-4415-ADD3-057E16BB4261}.release_shared.Build.0 = release_shared|Win32 + {DE2611F3-CC74-433C-9020-B9BB162CE89F}.debug_shared.ActiveCfg = debug_shared|Win32 + {DE2611F3-CC74-433C-9020-B9BB162CE89F}.debug_shared.Build.0 = debug_shared|Win32 + {DE2611F3-CC74-433C-9020-B9BB162CE89F}.release_shared.ActiveCfg = release_shared|Win32 + {DE2611F3-CC74-433C-9020-B9BB162CE89F}.release_shared.Build.0 = release_shared|Win32 + {53851B48-4DAD-4B38-9BB4-5C747F9C62B1}.debug_shared.ActiveCfg = debug_shared|Win32 + {53851B48-4DAD-4B38-9BB4-5C747F9C62B1}.debug_shared.Build.0 = debug_shared|Win32 + {53851B48-4DAD-4B38-9BB4-5C747F9C62B1}.release_shared.ActiveCfg = release_shared|Win32 + {53851B48-4DAD-4B38-9BB4-5C747F9C62B1}.release_shared.Build.0 = release_shared|Win32 + {0A3E3912-4205-41CA-BCCE-261FA564D3C7}.debug_shared.ActiveCfg = debug_shared|Win32 + {0A3E3912-4205-41CA-BCCE-261FA564D3C7}.debug_shared.Build.0 = debug_shared|Win32 + {0A3E3912-4205-41CA-BCCE-261FA564D3C7}.release_shared.ActiveCfg = release_shared|Win32 + {0A3E3912-4205-41CA-BCCE-261FA564D3C7}.release_shared.Build.0 = release_shared|Win32 + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + EndGlobalSection + GlobalSection(ExtensibilityAddIns) = postSolution + EndGlobalSection +EndGlobal diff --git a/Foundation/samples/samples_vs80.sln b/Foundation/samples/samples_vs80.sln index 88cfd95f4..bd474ef6f 100644 --- a/Foundation/samples/samples_vs80.sln +++ b/Foundation/samples/samples_vs80.sln @@ -1,121 +1,121 @@ -Microsoft Visual Studio Solution File, Format Version 9.00 -# Visual Studio 2005 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "StringTokenizer", "StringTokenizer\StringTokenizer_vs80.vcproj", "{D49346E0-4F69-4BEC-9380-32D55D48063F}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "base64encode", "base64encode\base64encode_vs80.vcproj", "{F325FEFC-2ADF-473D-8CBF-F6D54DB1AD8D}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "base64decode", "base64decode\base64decode_vs80.vcproj", "{F9602261-CD9E-44E0-82D1-A1F30AA5CB67}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "BinaryReaderWriter", "BinaryReaderWriter\BinaryReaderWriter_vs80.vcproj", "{9FFF12D2-4DCC-4AC2-AF3D-7FADBE7EE711}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "deflate", "deflate\deflate_vs80.vcproj", "{188E8EB7-EE1C-4485-9C0A-52BAD6A30BE1}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "inflate", "inflate\inflate_vs80.vcproj", "{60D48C6D-53D0-41E1-BFA0-8A6C354C6EE9}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "md5", "md5\md5_vs80.vcproj", "{DB54AA95-8EA1-4950-9B59-1917A86B7E45}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "hmacmd5", "hmacmd5\hmacmd5_vs80.vcproj", "{D6A19A85-C8EC-4EAC-B495-246E4D7C5EF6}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "grep", "grep\grep_vs80.vcproj", "{52626367-962B-44AA-9750-42F55EDA292E}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Logger", "Logger\Logger_vs80.vcproj", "{E7CE21A7-3D50-485E-9B68-E1BEC97ED2E3}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "NotificationQueue", "NotificationQueue\NotificationQueue_vs80.vcproj", "{DB9948BB-A40E-4010-8E5E-DDCDFC1B8EFD}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "dir", "dir\dir_vs80.vcproj", "{AA18CF6F-3B7F-4A92-9464-4DC07A758E2C}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "DateTime", "DateTime\DateTime_vs80.vcproj", "{1413EE43-C5FC-45C2-AF6E-4EF10C8BF34E}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "uuidgen", "uuidgen\uuidgen_vs80.vcproj", "{4A208D55-894A-4653-9F75-89D1373D9DA7}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "URI", "URI\URI_vs80.vcproj", "{C4AA83D3-3BDF-4415-ADD3-057E16BB4261}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Timer", "Timer\Timer_vs80.vcproj", "{DE2611F3-CC74-433C-9020-B9BB162CE89F}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Activity", "Activity\Activity_vs80.vcproj", "{53851B48-4DAD-4B38-9BB4-5C747F9C62B1}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ActiveMethod", "ActiveMethod\ActiveMethod_vs80.vcproj", "{0A3E3912-4205-41CA-BCCE-261FA564D3C7}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - debug_shared|Win32 = debug_shared|Win32 - release_shared|Win32 = release_shared|Win32 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {D49346E0-4F69-4BEC-9380-32D55D48063F}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 - {D49346E0-4F69-4BEC-9380-32D55D48063F}.debug_shared|Win32.Build.0 = debug_shared|Win32 - {D49346E0-4F69-4BEC-9380-32D55D48063F}.release_shared|Win32.ActiveCfg = release_shared|Win32 - {D49346E0-4F69-4BEC-9380-32D55D48063F}.release_shared|Win32.Build.0 = release_shared|Win32 - {F325FEFC-2ADF-473D-8CBF-F6D54DB1AD8D}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 - {F325FEFC-2ADF-473D-8CBF-F6D54DB1AD8D}.debug_shared|Win32.Build.0 = debug_shared|Win32 - {F325FEFC-2ADF-473D-8CBF-F6D54DB1AD8D}.release_shared|Win32.ActiveCfg = release_shared|Win32 - {F325FEFC-2ADF-473D-8CBF-F6D54DB1AD8D}.release_shared|Win32.Build.0 = release_shared|Win32 - {F9602261-CD9E-44E0-82D1-A1F30AA5CB67}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 - {F9602261-CD9E-44E0-82D1-A1F30AA5CB67}.debug_shared|Win32.Build.0 = debug_shared|Win32 - {F9602261-CD9E-44E0-82D1-A1F30AA5CB67}.release_shared|Win32.ActiveCfg = release_shared|Win32 - {F9602261-CD9E-44E0-82D1-A1F30AA5CB67}.release_shared|Win32.Build.0 = release_shared|Win32 - {9FFF12D2-4DCC-4AC2-AF3D-7FADBE7EE711}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 - {9FFF12D2-4DCC-4AC2-AF3D-7FADBE7EE711}.debug_shared|Win32.Build.0 = debug_shared|Win32 - {9FFF12D2-4DCC-4AC2-AF3D-7FADBE7EE711}.release_shared|Win32.ActiveCfg = release_shared|Win32 - {9FFF12D2-4DCC-4AC2-AF3D-7FADBE7EE711}.release_shared|Win32.Build.0 = release_shared|Win32 - {188E8EB7-EE1C-4485-9C0A-52BAD6A30BE1}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 - {188E8EB7-EE1C-4485-9C0A-52BAD6A30BE1}.debug_shared|Win32.Build.0 = debug_shared|Win32 - {188E8EB7-EE1C-4485-9C0A-52BAD6A30BE1}.release_shared|Win32.ActiveCfg = release_shared|Win32 - {188E8EB7-EE1C-4485-9C0A-52BAD6A30BE1}.release_shared|Win32.Build.0 = release_shared|Win32 - {60D48C6D-53D0-41E1-BFA0-8A6C354C6EE9}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 - {60D48C6D-53D0-41E1-BFA0-8A6C354C6EE9}.debug_shared|Win32.Build.0 = debug_shared|Win32 - {60D48C6D-53D0-41E1-BFA0-8A6C354C6EE9}.release_shared|Win32.ActiveCfg = release_shared|Win32 - {60D48C6D-53D0-41E1-BFA0-8A6C354C6EE9}.release_shared|Win32.Build.0 = release_shared|Win32 - {DB54AA95-8EA1-4950-9B59-1917A86B7E45}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 - {DB54AA95-8EA1-4950-9B59-1917A86B7E45}.debug_shared|Win32.Build.0 = debug_shared|Win32 - {DB54AA95-8EA1-4950-9B59-1917A86B7E45}.release_shared|Win32.ActiveCfg = release_shared|Win32 - {DB54AA95-8EA1-4950-9B59-1917A86B7E45}.release_shared|Win32.Build.0 = release_shared|Win32 - {D6A19A85-C8EC-4EAC-B495-246E4D7C5EF6}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 - {D6A19A85-C8EC-4EAC-B495-246E4D7C5EF6}.debug_shared|Win32.Build.0 = debug_shared|Win32 - {D6A19A85-C8EC-4EAC-B495-246E4D7C5EF6}.release_shared|Win32.ActiveCfg = release_shared|Win32 - {D6A19A85-C8EC-4EAC-B495-246E4D7C5EF6}.release_shared|Win32.Build.0 = release_shared|Win32 - {52626367-962B-44AA-9750-42F55EDA292E}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 - {52626367-962B-44AA-9750-42F55EDA292E}.debug_shared|Win32.Build.0 = debug_shared|Win32 - {52626367-962B-44AA-9750-42F55EDA292E}.release_shared|Win32.ActiveCfg = release_shared|Win32 - {52626367-962B-44AA-9750-42F55EDA292E}.release_shared|Win32.Build.0 = release_shared|Win32 - {E7CE21A7-3D50-485E-9B68-E1BEC97ED2E3}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 - {E7CE21A7-3D50-485E-9B68-E1BEC97ED2E3}.debug_shared|Win32.Build.0 = debug_shared|Win32 - {E7CE21A7-3D50-485E-9B68-E1BEC97ED2E3}.release_shared|Win32.ActiveCfg = release_shared|Win32 - {E7CE21A7-3D50-485E-9B68-E1BEC97ED2E3}.release_shared|Win32.Build.0 = release_shared|Win32 - {DB9948BB-A40E-4010-8E5E-DDCDFC1B8EFD}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 - {DB9948BB-A40E-4010-8E5E-DDCDFC1B8EFD}.debug_shared|Win32.Build.0 = debug_shared|Win32 - {DB9948BB-A40E-4010-8E5E-DDCDFC1B8EFD}.release_shared|Win32.ActiveCfg = release_shared|Win32 - {DB9948BB-A40E-4010-8E5E-DDCDFC1B8EFD}.release_shared|Win32.Build.0 = release_shared|Win32 - {AA18CF6F-3B7F-4A92-9464-4DC07A758E2C}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 - {AA18CF6F-3B7F-4A92-9464-4DC07A758E2C}.debug_shared|Win32.Build.0 = debug_shared|Win32 - {AA18CF6F-3B7F-4A92-9464-4DC07A758E2C}.release_shared|Win32.ActiveCfg = release_shared|Win32 - {AA18CF6F-3B7F-4A92-9464-4DC07A758E2C}.release_shared|Win32.Build.0 = release_shared|Win32 - {1413EE43-C5FC-45C2-AF6E-4EF10C8BF34E}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 - {1413EE43-C5FC-45C2-AF6E-4EF10C8BF34E}.debug_shared|Win32.Build.0 = debug_shared|Win32 - {1413EE43-C5FC-45C2-AF6E-4EF10C8BF34E}.release_shared|Win32.ActiveCfg = release_shared|Win32 - {1413EE43-C5FC-45C2-AF6E-4EF10C8BF34E}.release_shared|Win32.Build.0 = release_shared|Win32 - {4A208D55-894A-4653-9F75-89D1373D9DA7}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 - {4A208D55-894A-4653-9F75-89D1373D9DA7}.debug_shared|Win32.Build.0 = debug_shared|Win32 - {4A208D55-894A-4653-9F75-89D1373D9DA7}.release_shared|Win32.ActiveCfg = release_shared|Win32 - {4A208D55-894A-4653-9F75-89D1373D9DA7}.release_shared|Win32.Build.0 = release_shared|Win32 - {C4AA83D3-3BDF-4415-ADD3-057E16BB4261}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 - {C4AA83D3-3BDF-4415-ADD3-057E16BB4261}.debug_shared|Win32.Build.0 = debug_shared|Win32 - {C4AA83D3-3BDF-4415-ADD3-057E16BB4261}.release_shared|Win32.ActiveCfg = release_shared|Win32 - {C4AA83D3-3BDF-4415-ADD3-057E16BB4261}.release_shared|Win32.Build.0 = release_shared|Win32 - {DE2611F3-CC74-433C-9020-B9BB162CE89F}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 - {DE2611F3-CC74-433C-9020-B9BB162CE89F}.debug_shared|Win32.Build.0 = debug_shared|Win32 - {DE2611F3-CC74-433C-9020-B9BB162CE89F}.release_shared|Win32.ActiveCfg = release_shared|Win32 - {DE2611F3-CC74-433C-9020-B9BB162CE89F}.release_shared|Win32.Build.0 = release_shared|Win32 - {53851B48-4DAD-4B38-9BB4-5C747F9C62B1}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 - {53851B48-4DAD-4B38-9BB4-5C747F9C62B1}.debug_shared|Win32.Build.0 = debug_shared|Win32 - {53851B48-4DAD-4B38-9BB4-5C747F9C62B1}.release_shared|Win32.ActiveCfg = release_shared|Win32 - {53851B48-4DAD-4B38-9BB4-5C747F9C62B1}.release_shared|Win32.Build.0 = release_shared|Win32 - {0A3E3912-4205-41CA-BCCE-261FA564D3C7}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 - {0A3E3912-4205-41CA-BCCE-261FA564D3C7}.debug_shared|Win32.Build.0 = debug_shared|Win32 - {0A3E3912-4205-41CA-BCCE-261FA564D3C7}.release_shared|Win32.ActiveCfg = release_shared|Win32 - {0A3E3912-4205-41CA-BCCE-261FA564D3C7}.release_shared|Win32.Build.0 = release_shared|Win32 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal +Microsoft Visual Studio Solution File, Format Version 9.00 +# Visual Studio 2005 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "StringTokenizer", "StringTokenizer\StringTokenizer_vs80.vcproj", "{D49346E0-4F69-4BEC-9380-32D55D48063F}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "base64encode", "base64encode\base64encode_vs80.vcproj", "{F325FEFC-2ADF-473D-8CBF-F6D54DB1AD8D}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "base64decode", "base64decode\base64decode_vs80.vcproj", "{F9602261-CD9E-44E0-82D1-A1F30AA5CB67}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "BinaryReaderWriter", "BinaryReaderWriter\BinaryReaderWriter_vs80.vcproj", "{9FFF12D2-4DCC-4AC2-AF3D-7FADBE7EE711}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "deflate", "deflate\deflate_vs80.vcproj", "{188E8EB7-EE1C-4485-9C0A-52BAD6A30BE1}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "inflate", "inflate\inflate_vs80.vcproj", "{60D48C6D-53D0-41E1-BFA0-8A6C354C6EE9}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "md5", "md5\md5_vs80.vcproj", "{DB54AA95-8EA1-4950-9B59-1917A86B7E45}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "hmacmd5", "hmacmd5\hmacmd5_vs80.vcproj", "{D6A19A85-C8EC-4EAC-B495-246E4D7C5EF6}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "grep", "grep\grep_vs80.vcproj", "{52626367-962B-44AA-9750-42F55EDA292E}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Logger", "Logger\Logger_vs80.vcproj", "{E7CE21A7-3D50-485E-9B68-E1BEC97ED2E3}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "NotificationQueue", "NotificationQueue\NotificationQueue_vs80.vcproj", "{DB9948BB-A40E-4010-8E5E-DDCDFC1B8EFD}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "dir", "dir\dir_vs80.vcproj", "{AA18CF6F-3B7F-4A92-9464-4DC07A758E2C}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "DateTime", "DateTime\DateTime_vs80.vcproj", "{1413EE43-C5FC-45C2-AF6E-4EF10C8BF34E}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "uuidgen", "uuidgen\uuidgen_vs80.vcproj", "{4A208D55-894A-4653-9F75-89D1373D9DA7}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "URI", "URI\URI_vs80.vcproj", "{C4AA83D3-3BDF-4415-ADD3-057E16BB4261}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Timer", "Timer\Timer_vs80.vcproj", "{DE2611F3-CC74-433C-9020-B9BB162CE89F}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Activity", "Activity\Activity_vs80.vcproj", "{53851B48-4DAD-4B38-9BB4-5C747F9C62B1}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ActiveMethod", "ActiveMethod\ActiveMethod_vs80.vcproj", "{0A3E3912-4205-41CA-BCCE-261FA564D3C7}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + debug_shared|Win32 = debug_shared|Win32 + release_shared|Win32 = release_shared|Win32 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {D49346E0-4F69-4BEC-9380-32D55D48063F}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 + {D49346E0-4F69-4BEC-9380-32D55D48063F}.debug_shared|Win32.Build.0 = debug_shared|Win32 + {D49346E0-4F69-4BEC-9380-32D55D48063F}.release_shared|Win32.ActiveCfg = release_shared|Win32 + {D49346E0-4F69-4BEC-9380-32D55D48063F}.release_shared|Win32.Build.0 = release_shared|Win32 + {F325FEFC-2ADF-473D-8CBF-F6D54DB1AD8D}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 + {F325FEFC-2ADF-473D-8CBF-F6D54DB1AD8D}.debug_shared|Win32.Build.0 = debug_shared|Win32 + {F325FEFC-2ADF-473D-8CBF-F6D54DB1AD8D}.release_shared|Win32.ActiveCfg = release_shared|Win32 + {F325FEFC-2ADF-473D-8CBF-F6D54DB1AD8D}.release_shared|Win32.Build.0 = release_shared|Win32 + {F9602261-CD9E-44E0-82D1-A1F30AA5CB67}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 + {F9602261-CD9E-44E0-82D1-A1F30AA5CB67}.debug_shared|Win32.Build.0 = debug_shared|Win32 + {F9602261-CD9E-44E0-82D1-A1F30AA5CB67}.release_shared|Win32.ActiveCfg = release_shared|Win32 + {F9602261-CD9E-44E0-82D1-A1F30AA5CB67}.release_shared|Win32.Build.0 = release_shared|Win32 + {9FFF12D2-4DCC-4AC2-AF3D-7FADBE7EE711}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 + {9FFF12D2-4DCC-4AC2-AF3D-7FADBE7EE711}.debug_shared|Win32.Build.0 = debug_shared|Win32 + {9FFF12D2-4DCC-4AC2-AF3D-7FADBE7EE711}.release_shared|Win32.ActiveCfg = release_shared|Win32 + {9FFF12D2-4DCC-4AC2-AF3D-7FADBE7EE711}.release_shared|Win32.Build.0 = release_shared|Win32 + {188E8EB7-EE1C-4485-9C0A-52BAD6A30BE1}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 + {188E8EB7-EE1C-4485-9C0A-52BAD6A30BE1}.debug_shared|Win32.Build.0 = debug_shared|Win32 + {188E8EB7-EE1C-4485-9C0A-52BAD6A30BE1}.release_shared|Win32.ActiveCfg = release_shared|Win32 + {188E8EB7-EE1C-4485-9C0A-52BAD6A30BE1}.release_shared|Win32.Build.0 = release_shared|Win32 + {60D48C6D-53D0-41E1-BFA0-8A6C354C6EE9}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 + {60D48C6D-53D0-41E1-BFA0-8A6C354C6EE9}.debug_shared|Win32.Build.0 = debug_shared|Win32 + {60D48C6D-53D0-41E1-BFA0-8A6C354C6EE9}.release_shared|Win32.ActiveCfg = release_shared|Win32 + {60D48C6D-53D0-41E1-BFA0-8A6C354C6EE9}.release_shared|Win32.Build.0 = release_shared|Win32 + {DB54AA95-8EA1-4950-9B59-1917A86B7E45}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 + {DB54AA95-8EA1-4950-9B59-1917A86B7E45}.debug_shared|Win32.Build.0 = debug_shared|Win32 + {DB54AA95-8EA1-4950-9B59-1917A86B7E45}.release_shared|Win32.ActiveCfg = release_shared|Win32 + {DB54AA95-8EA1-4950-9B59-1917A86B7E45}.release_shared|Win32.Build.0 = release_shared|Win32 + {D6A19A85-C8EC-4EAC-B495-246E4D7C5EF6}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 + {D6A19A85-C8EC-4EAC-B495-246E4D7C5EF6}.debug_shared|Win32.Build.0 = debug_shared|Win32 + {D6A19A85-C8EC-4EAC-B495-246E4D7C5EF6}.release_shared|Win32.ActiveCfg = release_shared|Win32 + {D6A19A85-C8EC-4EAC-B495-246E4D7C5EF6}.release_shared|Win32.Build.0 = release_shared|Win32 + {52626367-962B-44AA-9750-42F55EDA292E}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 + {52626367-962B-44AA-9750-42F55EDA292E}.debug_shared|Win32.Build.0 = debug_shared|Win32 + {52626367-962B-44AA-9750-42F55EDA292E}.release_shared|Win32.ActiveCfg = release_shared|Win32 + {52626367-962B-44AA-9750-42F55EDA292E}.release_shared|Win32.Build.0 = release_shared|Win32 + {E7CE21A7-3D50-485E-9B68-E1BEC97ED2E3}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 + {E7CE21A7-3D50-485E-9B68-E1BEC97ED2E3}.debug_shared|Win32.Build.0 = debug_shared|Win32 + {E7CE21A7-3D50-485E-9B68-E1BEC97ED2E3}.release_shared|Win32.ActiveCfg = release_shared|Win32 + {E7CE21A7-3D50-485E-9B68-E1BEC97ED2E3}.release_shared|Win32.Build.0 = release_shared|Win32 + {DB9948BB-A40E-4010-8E5E-DDCDFC1B8EFD}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 + {DB9948BB-A40E-4010-8E5E-DDCDFC1B8EFD}.debug_shared|Win32.Build.0 = debug_shared|Win32 + {DB9948BB-A40E-4010-8E5E-DDCDFC1B8EFD}.release_shared|Win32.ActiveCfg = release_shared|Win32 + {DB9948BB-A40E-4010-8E5E-DDCDFC1B8EFD}.release_shared|Win32.Build.0 = release_shared|Win32 + {AA18CF6F-3B7F-4A92-9464-4DC07A758E2C}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 + {AA18CF6F-3B7F-4A92-9464-4DC07A758E2C}.debug_shared|Win32.Build.0 = debug_shared|Win32 + {AA18CF6F-3B7F-4A92-9464-4DC07A758E2C}.release_shared|Win32.ActiveCfg = release_shared|Win32 + {AA18CF6F-3B7F-4A92-9464-4DC07A758E2C}.release_shared|Win32.Build.0 = release_shared|Win32 + {1413EE43-C5FC-45C2-AF6E-4EF10C8BF34E}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 + {1413EE43-C5FC-45C2-AF6E-4EF10C8BF34E}.debug_shared|Win32.Build.0 = debug_shared|Win32 + {1413EE43-C5FC-45C2-AF6E-4EF10C8BF34E}.release_shared|Win32.ActiveCfg = release_shared|Win32 + {1413EE43-C5FC-45C2-AF6E-4EF10C8BF34E}.release_shared|Win32.Build.0 = release_shared|Win32 + {4A208D55-894A-4653-9F75-89D1373D9DA7}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 + {4A208D55-894A-4653-9F75-89D1373D9DA7}.debug_shared|Win32.Build.0 = debug_shared|Win32 + {4A208D55-894A-4653-9F75-89D1373D9DA7}.release_shared|Win32.ActiveCfg = release_shared|Win32 + {4A208D55-894A-4653-9F75-89D1373D9DA7}.release_shared|Win32.Build.0 = release_shared|Win32 + {C4AA83D3-3BDF-4415-ADD3-057E16BB4261}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 + {C4AA83D3-3BDF-4415-ADD3-057E16BB4261}.debug_shared|Win32.Build.0 = debug_shared|Win32 + {C4AA83D3-3BDF-4415-ADD3-057E16BB4261}.release_shared|Win32.ActiveCfg = release_shared|Win32 + {C4AA83D3-3BDF-4415-ADD3-057E16BB4261}.release_shared|Win32.Build.0 = release_shared|Win32 + {DE2611F3-CC74-433C-9020-B9BB162CE89F}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 + {DE2611F3-CC74-433C-9020-B9BB162CE89F}.debug_shared|Win32.Build.0 = debug_shared|Win32 + {DE2611F3-CC74-433C-9020-B9BB162CE89F}.release_shared|Win32.ActiveCfg = release_shared|Win32 + {DE2611F3-CC74-433C-9020-B9BB162CE89F}.release_shared|Win32.Build.0 = release_shared|Win32 + {53851B48-4DAD-4B38-9BB4-5C747F9C62B1}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 + {53851B48-4DAD-4B38-9BB4-5C747F9C62B1}.debug_shared|Win32.Build.0 = debug_shared|Win32 + {53851B48-4DAD-4B38-9BB4-5C747F9C62B1}.release_shared|Win32.ActiveCfg = release_shared|Win32 + {53851B48-4DAD-4B38-9BB4-5C747F9C62B1}.release_shared|Win32.Build.0 = release_shared|Win32 + {0A3E3912-4205-41CA-BCCE-261FA564D3C7}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 + {0A3E3912-4205-41CA-BCCE-261FA564D3C7}.debug_shared|Win32.Build.0 = debug_shared|Win32 + {0A3E3912-4205-41CA-BCCE-261FA564D3C7}.release_shared|Win32.ActiveCfg = release_shared|Win32 + {0A3E3912-4205-41CA-BCCE-261FA564D3C7}.release_shared|Win32.Build.0 = release_shared|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/Foundation/samples/uuidgen/Makefile b/Foundation/samples/uuidgen/Makefile index 23e11eaf0..0b63d9514 100644 --- a/Foundation/samples/uuidgen/Makefile +++ b/Foundation/samples/uuidgen/Makefile @@ -1,17 +1,17 @@ -# -# Makefile -# -# $Id: //poco/1.2/Foundation/samples/uuidgen/Makefile#1 $ -# -# Makefile for Poco uuidgen -# - -include $(POCO_BASE)/build/rules/global - -objects = uuidgen - -target = uuidgen -target_version = 1 -target_libs = PocoFoundation - -include $(POCO_BASE)/build/rules/exec +# +# Makefile +# +# $Id: //poco/1.2/Foundation/samples/uuidgen/Makefile#1 $ +# +# Makefile for Poco uuidgen +# + +include $(POCO_BASE)/build/rules/global + +objects = uuidgen + +target = uuidgen +target_version = 1 +target_libs = PocoFoundation + +include $(POCO_BASE)/build/rules/exec diff --git a/Foundation/samples/uuidgen/src/uuidgen.cpp b/Foundation/samples/uuidgen/src/uuidgen.cpp index f623ed89c..b4fbb1d28 100644 --- a/Foundation/samples/uuidgen/src/uuidgen.cpp +++ b/Foundation/samples/uuidgen/src/uuidgen.cpp @@ -1,72 +1,72 @@ -// -// uuidgen.cpp -// -// $Id: //poco/1.2/Foundation/samples/uuidgen/src/uuidgen.cpp#1 $ -// -// This sample demonstrates the UUIDGenerator and UUID classes. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/UUID.h" -#include "Poco/UUIDGenerator.h" -#include "Poco/Exception.h" -#include - - -using Poco::UUID; -using Poco::UUIDGenerator; -using Poco::Exception; - - -int main(int argc, char** argv) -{ - UUID uuid; - - std::string arg; - if (argc > 1) - arg = argv[1]; - - try - { - if (arg == "-random") - uuid = UUIDGenerator::defaultGenerator().createRandom(); - else if (arg.empty()) - uuid = UUIDGenerator::defaultGenerator().create(); - else - uuid = UUIDGenerator::defaultGenerator().createFromName(UUID::uri(), arg); - - std::cout << uuid.toString() << std::endl; - } - catch (Exception& exc) - { - std::cerr << exc.displayText() << std::endl; - return 1; - } - - return 0; -} +// +// uuidgen.cpp +// +// $Id: //poco/1.2/Foundation/samples/uuidgen/src/uuidgen.cpp#1 $ +// +// This sample demonstrates the UUIDGenerator and UUID classes. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/UUID.h" +#include "Poco/UUIDGenerator.h" +#include "Poco/Exception.h" +#include + + +using Poco::UUID; +using Poco::UUIDGenerator; +using Poco::Exception; + + +int main(int argc, char** argv) +{ + UUID uuid; + + std::string arg; + if (argc > 1) + arg = argv[1]; + + try + { + if (arg == "-random") + uuid = UUIDGenerator::defaultGenerator().createRandom(); + else if (arg.empty()) + uuid = UUIDGenerator::defaultGenerator().create(); + else + uuid = UUIDGenerator::defaultGenerator().createFromName(UUID::uri(), arg); + + std::cout << uuid.toString() << std::endl; + } + catch (Exception& exc) + { + std::cerr << exc.displayText() << std::endl; + return 1; + } + + return 0; +} diff --git a/Foundation/samples/uuidgen/uuidgen.vmsbuild b/Foundation/samples/uuidgen/uuidgen.vmsbuild index 77046a204..022296820 100644 --- a/Foundation/samples/uuidgen/uuidgen.vmsbuild +++ b/Foundation/samples/uuidgen/uuidgen.vmsbuild @@ -1,8 +1,8 @@ -# -# sample.vmsbuild -# -# $Id: //poco/1.2/Foundation/samples/uuidgen/uuidgen.vmsbuild#1 $ -# -EXE=uuidgen -uuidgen - +# +# sample.vmsbuild +# +# $Id: //poco/1.2/Foundation/samples/uuidgen/uuidgen.vmsbuild#1 $ +# +EXE=uuidgen +uuidgen + diff --git a/Foundation/samples/uuidgen/uuidgen_vs71.vcproj b/Foundation/samples/uuidgen/uuidgen_vs71.vcproj index e0b665ea5..c4167256c 100644 --- a/Foundation/samples/uuidgen/uuidgen_vs71.vcproj +++ b/Foundation/samples/uuidgen/uuidgen_vs71.vcproj @@ -1,149 +1,149 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Foundation/samples/uuidgen/uuidgen_vs80.vcproj b/Foundation/samples/uuidgen/uuidgen_vs80.vcproj index f5979d474..370f78350 100644 --- a/Foundation/samples/uuidgen/uuidgen_vs80.vcproj +++ b/Foundation/samples/uuidgen/uuidgen_vs80.vcproj @@ -1,213 +1,213 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Foundation/src/ASCIIEncoding.cpp b/Foundation/src/ASCIIEncoding.cpp index 88f75c9fc..69ce6b1fb 100644 --- a/Foundation/src/ASCIIEncoding.cpp +++ b/Foundation/src/ASCIIEncoding.cpp @@ -1,97 +1,97 @@ -// -// ASCIIEncoding.cpp -// -// $Id: //poco/1.2/Foundation/src/ASCIIEncoding.cpp#1 $ -// -// Library: Foundation -// Package: Text -// Module: ASCIIEncoding -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/ASCIIEncoding.h" - - -namespace Poco { - - -const TextEncoding::CharacterMap ASCIIEncoding::_charMap = -{ - /* 00 */ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, - /* 10 */ 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, - /* 20 */ 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, - /* 30 */ 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, - /* 40 */ 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, - /* 50 */ 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, - /* 60 */ 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, - /* 70 */ 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, - /* 80 */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - /* 90 */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - /* a0 */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - /* b0 */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - /* c0 */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - /* d0 */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - /* e0 */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - /* f0 */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -}; - - -ASCIIEncoding::ASCIIEncoding() -{ -} - - -ASCIIEncoding::~ASCIIEncoding() -{ -} - - -const TextEncoding::CharacterMap& ASCIIEncoding::characterMap() const -{ - return _charMap; -} - - -int ASCIIEncoding::convert(const unsigned char* bytes) const -{ - return *bytes; -} - - -int ASCIIEncoding::convert(int ch, unsigned char* bytes, int length) const -{ - if (ch >= 0 && ch <= 127) - { - *bytes = (unsigned char) ch; - return 1; - } - else return 0; -} - - -} // namespace Poco +// +// ASCIIEncoding.cpp +// +// $Id: //poco/1.2/Foundation/src/ASCIIEncoding.cpp#1 $ +// +// Library: Foundation +// Package: Text +// Module: ASCIIEncoding +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/ASCIIEncoding.h" + + +namespace Poco { + + +const TextEncoding::CharacterMap ASCIIEncoding::_charMap = +{ + /* 00 */ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, + /* 10 */ 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, + /* 20 */ 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, + /* 30 */ 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, + /* 40 */ 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, + /* 50 */ 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, + /* 60 */ 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, + /* 70 */ 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, + /* 80 */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + /* 90 */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + /* a0 */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + /* b0 */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + /* c0 */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + /* d0 */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + /* e0 */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + /* f0 */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, +}; + + +ASCIIEncoding::ASCIIEncoding() +{ +} + + +ASCIIEncoding::~ASCIIEncoding() +{ +} + + +const TextEncoding::CharacterMap& ASCIIEncoding::characterMap() const +{ + return _charMap; +} + + +int ASCIIEncoding::convert(const unsigned char* bytes) const +{ + return *bytes; +} + + +int ASCIIEncoding::convert(int ch, unsigned char* bytes, int length) const +{ + if (ch >= 0 && ch <= 127) + { + *bytes = (unsigned char) ch; + return 1; + } + else return 0; +} + + +} // namespace Poco diff --git a/Foundation/src/AbstractObserver.cpp b/Foundation/src/AbstractObserver.cpp index 874453f8a..8cbe4b3d3 100644 --- a/Foundation/src/AbstractObserver.cpp +++ b/Foundation/src/AbstractObserver.cpp @@ -1,64 +1,64 @@ -// -// AbstractObserver.cpp -// -// $Id: //poco/1.2/Foundation/src/AbstractObserver.cpp#1 $ -// -// Library: Foundation -// Package: Notifications -// Module: NotificationCenter -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/AbstractObserver.h" - - -namespace Poco { - - -AbstractObserver::AbstractObserver() -{ -} - - -AbstractObserver::AbstractObserver(const AbstractObserver& observer) -{ -} - - -AbstractObserver::~AbstractObserver() -{ -} - - -AbstractObserver& AbstractObserver::operator = (const AbstractObserver& observer) -{ - return *this; -} - - -} // namespace Poco +// +// AbstractObserver.cpp +// +// $Id: //poco/1.2/Foundation/src/AbstractObserver.cpp#1 $ +// +// Library: Foundation +// Package: Notifications +// Module: NotificationCenter +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/AbstractObserver.h" + + +namespace Poco { + + +AbstractObserver::AbstractObserver() +{ +} + + +AbstractObserver::AbstractObserver(const AbstractObserver& observer) +{ +} + + +AbstractObserver::~AbstractObserver() +{ +} + + +AbstractObserver& AbstractObserver::operator = (const AbstractObserver& observer) +{ + return *this; +} + + +} // namespace Poco diff --git a/Foundation/src/ActiveDispatcher.cpp b/Foundation/src/ActiveDispatcher.cpp index f6dcde625..39b50364d 100644 --- a/Foundation/src/ActiveDispatcher.cpp +++ b/Foundation/src/ActiveDispatcher.cpp @@ -1,133 +1,133 @@ -// -// ActiveDispatcher.cpp -// -// $Id: //poco/1.2/Foundation/src/ActiveDispatcher.cpp#1 $ -// -// Library: Foundation -// Package: Threading -// Module: ActiveObjects -// -// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/ActiveDispatcher.h" -#include "Poco/Notification.h" -#include "Poco/AutoPtr.h" - - -namespace Poco { - - -namespace -{ - class MethodNotification: public Notification - { - public: - MethodNotification(Runnable* pRunnable): - _pRunnable(pRunnable) - { - } - - Runnable* runnable() const - { - return _pRunnable; - } - - private: - Runnable* _pRunnable; - }; - - class StopNotification: public Notification - { - }; -} - - -ActiveDispatcher::ActiveDispatcher() -{ - _thread.start(*this); -} - - -ActiveDispatcher::ActiveDispatcher(Thread::Priority prio) -{ - _thread.setPriority(prio); - _thread.start(*this); -} - - -ActiveDispatcher::~ActiveDispatcher() -{ - try - { - stop(); - } - catch (...) - { - } -} - - -void ActiveDispatcher::start(Runnable* pRunnable) -{ - poco_check_ptr (pRunnable); - - _queue.enqueueNotification(new MethodNotification(pRunnable)); -} - - -void ActiveDispatcher::cancel() -{ - _queue.clear(); -} - - -void ActiveDispatcher::run() -{ - AutoPtr pNf = _queue.waitDequeueNotification(); - while (pNf && !dynamic_cast(pNf.get())) - { - MethodNotification* pMethodNf = dynamic_cast(pNf.get()); - poco_check_ptr (pMethodNf); - Runnable* pRunnable = pMethodNf->runnable(); - poco_check_ptr (pRunnable); - pRunnable->run(); - pNf = _queue.waitDequeueNotification(); - } -} - - -void ActiveDispatcher::stop() -{ - _queue.clear(); - _queue.wakeUpAll(); - _queue.enqueueNotification(new StopNotification); - _thread.join(); -} - - -} // namespace Poco +// +// ActiveDispatcher.cpp +// +// $Id: //poco/1.2/Foundation/src/ActiveDispatcher.cpp#1 $ +// +// Library: Foundation +// Package: Threading +// Module: ActiveObjects +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/ActiveDispatcher.h" +#include "Poco/Notification.h" +#include "Poco/AutoPtr.h" + + +namespace Poco { + + +namespace +{ + class MethodNotification: public Notification + { + public: + MethodNotification(Runnable* pRunnable): + _pRunnable(pRunnable) + { + } + + Runnable* runnable() const + { + return _pRunnable; + } + + private: + Runnable* _pRunnable; + }; + + class StopNotification: public Notification + { + }; +} + + +ActiveDispatcher::ActiveDispatcher() +{ + _thread.start(*this); +} + + +ActiveDispatcher::ActiveDispatcher(Thread::Priority prio) +{ + _thread.setPriority(prio); + _thread.start(*this); +} + + +ActiveDispatcher::~ActiveDispatcher() +{ + try + { + stop(); + } + catch (...) + { + } +} + + +void ActiveDispatcher::start(Runnable* pRunnable) +{ + poco_check_ptr (pRunnable); + + _queue.enqueueNotification(new MethodNotification(pRunnable)); +} + + +void ActiveDispatcher::cancel() +{ + _queue.clear(); +} + + +void ActiveDispatcher::run() +{ + AutoPtr pNf = _queue.waitDequeueNotification(); + while (pNf && !dynamic_cast(pNf.get())) + { + MethodNotification* pMethodNf = dynamic_cast(pNf.get()); + poco_check_ptr (pMethodNf); + Runnable* pRunnable = pMethodNf->runnable(); + poco_check_ptr (pRunnable); + pRunnable->run(); + pNf = _queue.waitDequeueNotification(); + } +} + + +void ActiveDispatcher::stop() +{ + _queue.clear(); + _queue.wakeUpAll(); + _queue.enqueueNotification(new StopNotification); + _thread.join(); +} + + +} // namespace Poco diff --git a/Foundation/src/ArchiveStrategy.cpp b/Foundation/src/ArchiveStrategy.cpp index f84fdb35c..ffa27fa00 100644 --- a/Foundation/src/ArchiveStrategy.cpp +++ b/Foundation/src/ArchiveStrategy.cpp @@ -1,211 +1,211 @@ -// -// ArchiveStrategy.cpp -// -// $Id: //poco/1.2/Foundation/src/ArchiveStrategy.cpp#1 $ -// -// Library: Foundation -// Package: Logging -// Module: FileChannel -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/ArchiveStrategy.h" -#include "Poco/NumberFormatter.h" -#include "Poco/File.h" -#include "Poco/Path.h" -#include "Poco/DeflatingStream.h" -#include "Poco/StreamCopier.h" -#include "Poco/Exception.h" -#include "Poco/ActiveDispatcher.h" -#include "Poco/ActiveMethod.h" -#include "Poco/Void.h" -#include - - -namespace Poco { - - -// -// ArchiveCompressor -// - - -class ArchiveCompressor: public ActiveDispatcher -{ -public: - ArchiveCompressor(): - compress(this, &ArchiveCompressor::compressImpl) - { - } - - ~ArchiveCompressor() - { - } - - ActiveMethod > compress; - -protected: - Void compressImpl(const std::string& path) - { - std::string gzPath(path); - gzPath.append(".gz"); - std::ifstream istr(path.c_str(), std::ios::binary | std::ios::in); - if (!istr.good()) throw OpenFileException(path); - std::ofstream ostr(gzPath.c_str(), std::ios::binary | std::ios::out); - if (ostr.good()) - { - DeflatingOutputStream deflater(ostr, DeflatingStreamBuf::STREAM_GZIP); - StreamCopier::copyStream(istr, deflater); - deflater.close(); - ostr.close(); - istr.close(); - File f(path); - f.remove(); - } - else throw CreateFileException(gzPath); - return Void(); - } -}; - - -// -// ArchiveStrategy -// - - -ArchiveStrategy::ArchiveStrategy(): - _compress(false), - _pCompressor(0) -{ -} - - -ArchiveStrategy::~ArchiveStrategy() -{ - delete _pCompressor; -} - - -void ArchiveStrategy::compress(bool flag) -{ - _compress = flag; -} - - -void ArchiveStrategy::moveFile(const std::string& oldPath, const std::string& newPath) -{ - bool compressed = false; - Path p(oldPath); - File f(oldPath); - if (!f.exists()) - { - f = oldPath + ".gz"; - compressed = true; - } - std::string mvPath(newPath); - if (_compress || compressed) - mvPath.append(".gz"); - if (!_compress || compressed) - { - f.renameTo(mvPath); - } - else - { - f.renameTo(newPath); - if (!_pCompressor) _pCompressor = new ArchiveCompressor; - _pCompressor->compress(newPath); - } -} - - -bool ArchiveStrategy::exists(const std::string& name) -{ - File f(name); - if (f.exists()) - { - return true; - } - else if (_compress) - { - std::string gzName(name); - gzName.append(".gz"); - File gzf(gzName); - return gzf.exists(); - } - else return false; -} - - -// -// ArchiveByNumberStrategy -// - - -ArchiveByNumberStrategy::ArchiveByNumberStrategy() -{ -} - - -ArchiveByNumberStrategy::~ArchiveByNumberStrategy() -{ -} - - -LogFile* ArchiveByNumberStrategy::archive(LogFile* pFile) -{ - std::string basePath = pFile->path(); - delete pFile; - int n = -1; - std::string path; - do - { - path = basePath; - path.append("."); - path.append(NumberFormatter::format(++n)); - } - while (exists(path)); - - while (n >= 0) - { - std::string oldPath = basePath; - if (n > 0) - { - oldPath.append("."); - oldPath.append(NumberFormatter::format(n - 1)); - } - std::string newPath = basePath; - newPath.append("."); - newPath.append(NumberFormatter::format(n)); - moveFile(oldPath, newPath); - --n; - } - return new LogFile(basePath); -} - - -} // namespace Poco +// +// ArchiveStrategy.cpp +// +// $Id: //poco/1.2/Foundation/src/ArchiveStrategy.cpp#1 $ +// +// Library: Foundation +// Package: Logging +// Module: FileChannel +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/ArchiveStrategy.h" +#include "Poco/NumberFormatter.h" +#include "Poco/File.h" +#include "Poco/Path.h" +#include "Poco/DeflatingStream.h" +#include "Poco/StreamCopier.h" +#include "Poco/Exception.h" +#include "Poco/ActiveDispatcher.h" +#include "Poco/ActiveMethod.h" +#include "Poco/Void.h" +#include + + +namespace Poco { + + +// +// ArchiveCompressor +// + + +class ArchiveCompressor: public ActiveDispatcher +{ +public: + ArchiveCompressor(): + compress(this, &ArchiveCompressor::compressImpl) + { + } + + ~ArchiveCompressor() + { + } + + ActiveMethod > compress; + +protected: + Void compressImpl(const std::string& path) + { + std::string gzPath(path); + gzPath.append(".gz"); + std::ifstream istr(path.c_str(), std::ios::binary | std::ios::in); + if (!istr.good()) throw OpenFileException(path); + std::ofstream ostr(gzPath.c_str(), std::ios::binary | std::ios::out); + if (ostr.good()) + { + DeflatingOutputStream deflater(ostr, DeflatingStreamBuf::STREAM_GZIP); + StreamCopier::copyStream(istr, deflater); + deflater.close(); + ostr.close(); + istr.close(); + File f(path); + f.remove(); + } + else throw CreateFileException(gzPath); + return Void(); + } +}; + + +// +// ArchiveStrategy +// + + +ArchiveStrategy::ArchiveStrategy(): + _compress(false), + _pCompressor(0) +{ +} + + +ArchiveStrategy::~ArchiveStrategy() +{ + delete _pCompressor; +} + + +void ArchiveStrategy::compress(bool flag) +{ + _compress = flag; +} + + +void ArchiveStrategy::moveFile(const std::string& oldPath, const std::string& newPath) +{ + bool compressed = false; + Path p(oldPath); + File f(oldPath); + if (!f.exists()) + { + f = oldPath + ".gz"; + compressed = true; + } + std::string mvPath(newPath); + if (_compress || compressed) + mvPath.append(".gz"); + if (!_compress || compressed) + { + f.renameTo(mvPath); + } + else + { + f.renameTo(newPath); + if (!_pCompressor) _pCompressor = new ArchiveCompressor; + _pCompressor->compress(newPath); + } +} + + +bool ArchiveStrategy::exists(const std::string& name) +{ + File f(name); + if (f.exists()) + { + return true; + } + else if (_compress) + { + std::string gzName(name); + gzName.append(".gz"); + File gzf(gzName); + return gzf.exists(); + } + else return false; +} + + +// +// ArchiveByNumberStrategy +// + + +ArchiveByNumberStrategy::ArchiveByNumberStrategy() +{ +} + + +ArchiveByNumberStrategy::~ArchiveByNumberStrategy() +{ +} + + +LogFile* ArchiveByNumberStrategy::archive(LogFile* pFile) +{ + std::string basePath = pFile->path(); + delete pFile; + int n = -1; + std::string path; + do + { + path = basePath; + path.append("."); + path.append(NumberFormatter::format(++n)); + } + while (exists(path)); + + while (n >= 0) + { + std::string oldPath = basePath; + if (n > 0) + { + oldPath.append("."); + oldPath.append(NumberFormatter::format(n - 1)); + } + std::string newPath = basePath; + newPath.append("."); + newPath.append(NumberFormatter::format(n)); + moveFile(oldPath, newPath); + --n; + } + return new LogFile(basePath); +} + + +} // namespace Poco diff --git a/Foundation/src/AsyncChannel.cpp b/Foundation/src/AsyncChannel.cpp index 80ca6b50f..9d5d46b0d 100644 --- a/Foundation/src/AsyncChannel.cpp +++ b/Foundation/src/AsyncChannel.cpp @@ -1,147 +1,147 @@ -// -// AsyncChannel.cpp -// -// $Id: //poco/1.2/Foundation/src/AsyncChannel.cpp#1 $ -// -// Library: Foundation -// Package: Logging -// Module: AsyncChannel -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/AsyncChannel.h" -#include "Poco/Notification.h" -#include "Poco/Message.h" -#include "Poco/Formatter.h" -#include "Poco/AutoPtr.h" -#include "Poco/LoggingRegistry.h" - - -namespace Poco { - - -class MessageNotification: public Notification -{ -public: - MessageNotification(const Message& msg) - { - _msg = msg; - } - - ~MessageNotification() - { - } - - const Message& message() const - { - return _msg; - } - -private: - Message _msg; -}; - - -AsyncChannel::AsyncChannel(Channel* pChannel): _pChannel(pChannel), _thread("AsyncChannel") -{ - if (_pChannel) _pChannel->duplicate(); -} - - -AsyncChannel::~AsyncChannel() -{ - close(); - if (_pChannel) _pChannel->release(); -} - - -void AsyncChannel::setChannel(Channel* pChannel) -{ - FastMutex::ScopedLock lock(_mutex); - - if (_pChannel) _pChannel->release(); - _pChannel = pChannel; - if (_pChannel) _pChannel->duplicate(); -} - - -Channel* AsyncChannel::getChannel() const -{ - return _pChannel; -} - - -void AsyncChannel::open() -{ - _thread.start(*this); -} - - -void AsyncChannel::close() -{ - if (_thread.isRunning()) - { - while (!_queue.empty()) Thread::sleep(100); - _queue.wakeUpAll(); - _thread.join(); - } -} - - -void AsyncChannel::log(const Message& msg) -{ - _queue.enqueueNotification(new MessageNotification(msg)); -} - - -void AsyncChannel::setProperty(const std::string& name, const std::string& value) -{ - if (name == "channel") - setChannel(LoggingRegistry::defaultRegistry().channelForName(value)); - else - Channel::setProperty(name, value); -} - - -void AsyncChannel::run() -{ - AutoPtr nf = _queue.waitDequeueNotification(); - while (nf) - { - MessageNotification* pNf = dynamic_cast(nf.get()); - { - FastMutex::ScopedLock lock(_mutex); - - if (pNf && _pChannel) _pChannel->log(pNf->message()); - } - nf = _queue.waitDequeueNotification(); - } -} - - -} // namespace Poco +// +// AsyncChannel.cpp +// +// $Id: //poco/1.2/Foundation/src/AsyncChannel.cpp#1 $ +// +// Library: Foundation +// Package: Logging +// Module: AsyncChannel +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/AsyncChannel.h" +#include "Poco/Notification.h" +#include "Poco/Message.h" +#include "Poco/Formatter.h" +#include "Poco/AutoPtr.h" +#include "Poco/LoggingRegistry.h" + + +namespace Poco { + + +class MessageNotification: public Notification +{ +public: + MessageNotification(const Message& msg) + { + _msg = msg; + } + + ~MessageNotification() + { + } + + const Message& message() const + { + return _msg; + } + +private: + Message _msg; +}; + + +AsyncChannel::AsyncChannel(Channel* pChannel): _pChannel(pChannel), _thread("AsyncChannel") +{ + if (_pChannel) _pChannel->duplicate(); +} + + +AsyncChannel::~AsyncChannel() +{ + close(); + if (_pChannel) _pChannel->release(); +} + + +void AsyncChannel::setChannel(Channel* pChannel) +{ + FastMutex::ScopedLock lock(_mutex); + + if (_pChannel) _pChannel->release(); + _pChannel = pChannel; + if (_pChannel) _pChannel->duplicate(); +} + + +Channel* AsyncChannel::getChannel() const +{ + return _pChannel; +} + + +void AsyncChannel::open() +{ + _thread.start(*this); +} + + +void AsyncChannel::close() +{ + if (_thread.isRunning()) + { + while (!_queue.empty()) Thread::sleep(100); + _queue.wakeUpAll(); + _thread.join(); + } +} + + +void AsyncChannel::log(const Message& msg) +{ + _queue.enqueueNotification(new MessageNotification(msg)); +} + + +void AsyncChannel::setProperty(const std::string& name, const std::string& value) +{ + if (name == "channel") + setChannel(LoggingRegistry::defaultRegistry().channelForName(value)); + else + Channel::setProperty(name, value); +} + + +void AsyncChannel::run() +{ + AutoPtr nf = _queue.waitDequeueNotification(); + while (nf) + { + MessageNotification* pNf = dynamic_cast(nf.get()); + { + FastMutex::ScopedLock lock(_mutex); + + if (pNf && _pChannel) _pChannel->log(pNf->message()); + } + nf = _queue.waitDequeueNotification(); + } +} + + +} // namespace Poco diff --git a/Foundation/src/Base64Decoder.cpp b/Foundation/src/Base64Decoder.cpp index 17f4ef3d6..629f811eb 100644 --- a/Foundation/src/Base64Decoder.cpp +++ b/Foundation/src/Base64Decoder.cpp @@ -1,153 +1,153 @@ -// -// Base64Decoder.cpp -// -// $Id: //poco/1.2/Foundation/src/Base64Decoder.cpp#1 $ -// -// Library: Foundation -// Package: Streams -// Module: Base64 -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/Base64Decoder.h" -#include "Poco/Base64Encoder.h" -#include "Poco/Exception.h" -#include "Poco/Mutex.h" - - -namespace Poco { - - -unsigned char Base64DecoderBuf::IN_ENCODING[256]; -bool Base64DecoderBuf::IN_ENCODING_INIT = false; - - -Base64DecoderBuf::Base64DecoderBuf(std::istream& istr): - _groupLength(0), - _groupIndex(0), - _istr(istr) -{ - static FastMutex mutex; - FastMutex::ScopedLock lock(mutex); - if (!IN_ENCODING_INIT) - { - for (unsigned i = 0; i < sizeof(IN_ENCODING); i++) - { - IN_ENCODING[i] = 0xFF; - } - for (unsigned i = 0; i < sizeof(Base64EncoderBuf::OUT_ENCODING); i++) - { - IN_ENCODING[Base64EncoderBuf::OUT_ENCODING[i]] = i; - } - IN_ENCODING['='] = 0; - IN_ENCODING_INIT = true; - } -} - - -Base64DecoderBuf::~Base64DecoderBuf() -{ -} - - -int Base64DecoderBuf::readFromDevice() -{ - if (_groupIndex < _groupLength) - { - return _group[_groupIndex++]; - } - else - { - unsigned char buffer[4]; - int c; - if ((c = readOne()) == -1) return -1; - buffer[0] = (unsigned char) c; - if (IN_ENCODING[buffer[0]] == 0xFF) throw DataFormatException(); - if ((c = readOne()) == -1) return -1; - buffer[1] = (unsigned char) c; - if (IN_ENCODING[buffer[1]] == 0xFF) throw DataFormatException(); - if ((c = readOne()) == -1) return -1; - buffer[2] = c; - if (IN_ENCODING[buffer[2]] == 0xFF) throw DataFormatException(); - if ((c = readOne()) == -1) return -1; - buffer[3] = c; - if (IN_ENCODING[buffer[3]] == 0xFF) throw DataFormatException(); - - _group[0] = (IN_ENCODING[buffer[0]] << 2) | (IN_ENCODING[buffer[1]] >> 4); - _group[1] = ((IN_ENCODING[buffer[1]] & 0x0F) << 4) | (IN_ENCODING[buffer[2]] >> 2); - _group[2] = (IN_ENCODING[buffer[2]] << 6) | IN_ENCODING[buffer[3]]; - - if (buffer[2] == '=') - _groupLength = 1; - else if (buffer[3] == '=') - _groupLength = 2; - else - _groupLength = 3; - _groupIndex = 1; - return _group[0]; - } -} - - -int Base64DecoderBuf::readOne() -{ - int ch = _istr.get(); - while (ch == ' ' || ch == '\r' || ch == '\t' || ch == '\n') - ch = _istr.get(); - return ch; -} - - -Base64DecoderIOS::Base64DecoderIOS(std::istream& istr): _buf(istr) -{ - poco_ios_init(&_buf); -} - - -Base64DecoderIOS::~Base64DecoderIOS() -{ -} - - -Base64DecoderBuf* Base64DecoderIOS::rdbuf() -{ - return &_buf; -} - - -Base64Decoder::Base64Decoder(std::istream& istr): Base64DecoderIOS(istr), std::istream(&_buf) -{ -} - - -Base64Decoder::~Base64Decoder() -{ -} - - -} // namespace Poco +// +// Base64Decoder.cpp +// +// $Id: //poco/1.2/Foundation/src/Base64Decoder.cpp#1 $ +// +// Library: Foundation +// Package: Streams +// Module: Base64 +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/Base64Decoder.h" +#include "Poco/Base64Encoder.h" +#include "Poco/Exception.h" +#include "Poco/Mutex.h" + + +namespace Poco { + + +unsigned char Base64DecoderBuf::IN_ENCODING[256]; +bool Base64DecoderBuf::IN_ENCODING_INIT = false; + + +Base64DecoderBuf::Base64DecoderBuf(std::istream& istr): + _groupLength(0), + _groupIndex(0), + _istr(istr) +{ + static FastMutex mutex; + FastMutex::ScopedLock lock(mutex); + if (!IN_ENCODING_INIT) + { + for (unsigned i = 0; i < sizeof(IN_ENCODING); i++) + { + IN_ENCODING[i] = 0xFF; + } + for (unsigned i = 0; i < sizeof(Base64EncoderBuf::OUT_ENCODING); i++) + { + IN_ENCODING[Base64EncoderBuf::OUT_ENCODING[i]] = i; + } + IN_ENCODING['='] = 0; + IN_ENCODING_INIT = true; + } +} + + +Base64DecoderBuf::~Base64DecoderBuf() +{ +} + + +int Base64DecoderBuf::readFromDevice() +{ + if (_groupIndex < _groupLength) + { + return _group[_groupIndex++]; + } + else + { + unsigned char buffer[4]; + int c; + if ((c = readOne()) == -1) return -1; + buffer[0] = (unsigned char) c; + if (IN_ENCODING[buffer[0]] == 0xFF) throw DataFormatException(); + if ((c = readOne()) == -1) return -1; + buffer[1] = (unsigned char) c; + if (IN_ENCODING[buffer[1]] == 0xFF) throw DataFormatException(); + if ((c = readOne()) == -1) return -1; + buffer[2] = c; + if (IN_ENCODING[buffer[2]] == 0xFF) throw DataFormatException(); + if ((c = readOne()) == -1) return -1; + buffer[3] = c; + if (IN_ENCODING[buffer[3]] == 0xFF) throw DataFormatException(); + + _group[0] = (IN_ENCODING[buffer[0]] << 2) | (IN_ENCODING[buffer[1]] >> 4); + _group[1] = ((IN_ENCODING[buffer[1]] & 0x0F) << 4) | (IN_ENCODING[buffer[2]] >> 2); + _group[2] = (IN_ENCODING[buffer[2]] << 6) | IN_ENCODING[buffer[3]]; + + if (buffer[2] == '=') + _groupLength = 1; + else if (buffer[3] == '=') + _groupLength = 2; + else + _groupLength = 3; + _groupIndex = 1; + return _group[0]; + } +} + + +int Base64DecoderBuf::readOne() +{ + int ch = _istr.get(); + while (ch == ' ' || ch == '\r' || ch == '\t' || ch == '\n') + ch = _istr.get(); + return ch; +} + + +Base64DecoderIOS::Base64DecoderIOS(std::istream& istr): _buf(istr) +{ + poco_ios_init(&_buf); +} + + +Base64DecoderIOS::~Base64DecoderIOS() +{ +} + + +Base64DecoderBuf* Base64DecoderIOS::rdbuf() +{ + return &_buf; +} + + +Base64Decoder::Base64Decoder(std::istream& istr): Base64DecoderIOS(istr), std::istream(&_buf) +{ +} + + +Base64Decoder::~Base64Decoder() +{ +} + + +} // namespace Poco diff --git a/Foundation/src/Base64Encoder.cpp b/Foundation/src/Base64Encoder.cpp index 15c73d4f8..769ff8c16 100644 --- a/Foundation/src/Base64Encoder.cpp +++ b/Foundation/src/Base64Encoder.cpp @@ -1,181 +1,181 @@ -// -// Base64Encoder.cpp -// -// $Id: //poco/1.2/Foundation/src/Base64Encoder.cpp#1 $ -// -// Library: Foundation -// Package: Streams -// Module: Base64 -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/Base64Encoder.h" - - -namespace Poco { - - -const unsigned char Base64EncoderBuf::OUT_ENCODING[64] = -{ - 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', - 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', - 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', - 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', - 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', - 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', - 'w', 'x', 'y', 'z', '0', '1', '2', '3', - '4', '5', '6', '7', '8', '9', '+', '/' -}; - - -Base64EncoderBuf::Base64EncoderBuf(std::ostream& ostr): - _groupLength(0), - _pos(0), - _lineLength(72), - _ostr(ostr) -{ -} - - -Base64EncoderBuf::~Base64EncoderBuf() -{ - try - { - close(); - } - catch (...) - { - } -} - - -void Base64EncoderBuf::setLineLength(int lineLength) -{ - poco_assert (lineLength > 0); - - _lineLength = lineLength; -} - - -int Base64EncoderBuf::getLineLength() const -{ - return _lineLength; -} - - -int Base64EncoderBuf::writeToDevice(char c) -{ - _group[_groupLength++] = (unsigned char) c; - if (_groupLength == 3) - { - unsigned char idx; - idx = _group[0] >> 2; - _ostr.put(OUT_ENCODING[idx]); - idx = ((_group[0] & 0x03) << 4) | (_group[1] >> 4); - _ostr.put(OUT_ENCODING[idx]); - idx = ((_group[1] & 0x0F) << 2) | (_group[2] >> 6); - _ostr.put(OUT_ENCODING[idx]); - idx = _group[2] & 0x3F; - _ostr.put(OUT_ENCODING[idx]); - _pos += 4; - if (_pos >= _lineLength) - { - _ostr << "\r\n"; - _pos = 0; - } - _groupLength = 0; - } - return _ostr ? charToInt(c) : -1; -} - - -int Base64EncoderBuf::close() -{ - sync(); - if (_groupLength == 1) - { - _group[1] = 0; - unsigned char idx; - idx = _group[0] >> 2; - _ostr.put(OUT_ENCODING[idx]); - idx = ((_group[0] & 0x03) << 4) | (_group[1] >> 4); - _ostr.put(OUT_ENCODING[idx]); - _ostr << "=="; - } - else if (_groupLength == 2) - { - _group[2] = 0; - unsigned char idx; - idx = _group[0] >> 2; - _ostr.put(OUT_ENCODING[idx]); - idx = ((_group[0] & 0x03) << 4) | (_group[1] >> 4); - _ostr.put(OUT_ENCODING[idx]); - idx = ((_group[1] & 0x0F) << 2) | (_group[2] >> 6); - _ostr.put(OUT_ENCODING[idx]); - _ostr.put('='); - } - _ostr.flush(); - _groupLength = 0; - return _ostr ? 0 : -1; -} - - -Base64EncoderIOS::Base64EncoderIOS(std::ostream& ostr): _buf(ostr) -{ - poco_ios_init(&_buf); -} - - -Base64EncoderIOS::~Base64EncoderIOS() -{ -} - - -int Base64EncoderIOS::close() -{ - return _buf.close(); -} - - -Base64EncoderBuf* Base64EncoderIOS::rdbuf() -{ - return &_buf; -} - - -Base64Encoder::Base64Encoder(std::ostream& ostr): Base64EncoderIOS(ostr), std::ostream(&_buf) -{ -} - - -Base64Encoder::~Base64Encoder() -{ -} - - -} // namespace Poco +// +// Base64Encoder.cpp +// +// $Id: //poco/1.2/Foundation/src/Base64Encoder.cpp#1 $ +// +// Library: Foundation +// Package: Streams +// Module: Base64 +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/Base64Encoder.h" + + +namespace Poco { + + +const unsigned char Base64EncoderBuf::OUT_ENCODING[64] = +{ + 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', + 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', + 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', + 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', + 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', + 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', + 'w', 'x', 'y', 'z', '0', '1', '2', '3', + '4', '5', '6', '7', '8', '9', '+', '/' +}; + + +Base64EncoderBuf::Base64EncoderBuf(std::ostream& ostr): + _groupLength(0), + _pos(0), + _lineLength(72), + _ostr(ostr) +{ +} + + +Base64EncoderBuf::~Base64EncoderBuf() +{ + try + { + close(); + } + catch (...) + { + } +} + + +void Base64EncoderBuf::setLineLength(int lineLength) +{ + poco_assert (lineLength > 0); + + _lineLength = lineLength; +} + + +int Base64EncoderBuf::getLineLength() const +{ + return _lineLength; +} + + +int Base64EncoderBuf::writeToDevice(char c) +{ + _group[_groupLength++] = (unsigned char) c; + if (_groupLength == 3) + { + unsigned char idx; + idx = _group[0] >> 2; + _ostr.put(OUT_ENCODING[idx]); + idx = ((_group[0] & 0x03) << 4) | (_group[1] >> 4); + _ostr.put(OUT_ENCODING[idx]); + idx = ((_group[1] & 0x0F) << 2) | (_group[2] >> 6); + _ostr.put(OUT_ENCODING[idx]); + idx = _group[2] & 0x3F; + _ostr.put(OUT_ENCODING[idx]); + _pos += 4; + if (_pos >= _lineLength) + { + _ostr << "\r\n"; + _pos = 0; + } + _groupLength = 0; + } + return _ostr ? charToInt(c) : -1; +} + + +int Base64EncoderBuf::close() +{ + sync(); + if (_groupLength == 1) + { + _group[1] = 0; + unsigned char idx; + idx = _group[0] >> 2; + _ostr.put(OUT_ENCODING[idx]); + idx = ((_group[0] & 0x03) << 4) | (_group[1] >> 4); + _ostr.put(OUT_ENCODING[idx]); + _ostr << "=="; + } + else if (_groupLength == 2) + { + _group[2] = 0; + unsigned char idx; + idx = _group[0] >> 2; + _ostr.put(OUT_ENCODING[idx]); + idx = ((_group[0] & 0x03) << 4) | (_group[1] >> 4); + _ostr.put(OUT_ENCODING[idx]); + idx = ((_group[1] & 0x0F) << 2) | (_group[2] >> 6); + _ostr.put(OUT_ENCODING[idx]); + _ostr.put('='); + } + _ostr.flush(); + _groupLength = 0; + return _ostr ? 0 : -1; +} + + +Base64EncoderIOS::Base64EncoderIOS(std::ostream& ostr): _buf(ostr) +{ + poco_ios_init(&_buf); +} + + +Base64EncoderIOS::~Base64EncoderIOS() +{ +} + + +int Base64EncoderIOS::close() +{ + return _buf.close(); +} + + +Base64EncoderBuf* Base64EncoderIOS::rdbuf() +{ + return &_buf; +} + + +Base64Encoder::Base64Encoder(std::ostream& ostr): Base64EncoderIOS(ostr), std::ostream(&_buf) +{ +} + + +Base64Encoder::~Base64Encoder() +{ +} + + +} // namespace Poco diff --git a/Foundation/src/BinaryReader.cpp b/Foundation/src/BinaryReader.cpp index 45d3e665e..a20351e27 100644 --- a/Foundation/src/BinaryReader.cpp +++ b/Foundation/src/BinaryReader.cpp @@ -1,279 +1,279 @@ -// -// BinaryReader.cpp -// -// $Id: //poco/1.2/Foundation/src/BinaryReader.cpp#1 $ -// -// Library: Foundation -// Package: Streams -// Module: BinaryReaderWriter -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/BinaryReader.h" -#include "Poco/ByteOrder.h" - - -namespace Poco { - - -BinaryReader::BinaryReader(std::istream& istr, StreamByteOrder byteOrder): - _istr(istr) -{ -#if defined(POCO_ARCH_BIG_ENDIAN) - _flipBytes = (byteOrder == LITTLE_ENDIAN_BYTE_ORDER); -#else - _flipBytes = (byteOrder == BIG_ENDIAN_BYTE_ORDER); -#endif -} - - -BinaryReader::~BinaryReader() -{ -} - - -BinaryReader& BinaryReader::operator >> (bool& value) -{ - _istr.read((char*) &value, sizeof(value)); - return *this; -} - - -BinaryReader& BinaryReader::operator >> (char& value) -{ - _istr.read((char*) &value, sizeof(value)); - return *this; -} - - -BinaryReader& BinaryReader::operator >> (unsigned char& value) -{ - _istr.read((char*) &value, sizeof(value)); - return *this; -} - - -BinaryReader& BinaryReader::operator >> (signed char& value) -{ - _istr.read((char*) &value, sizeof(value)); - return *this; -} - - -BinaryReader& BinaryReader::operator >> (short& value) -{ - _istr.read((char*) &value, sizeof(value)); - if (_flipBytes) value = ByteOrder::flipBytes(value); - return *this; -} - - -BinaryReader& BinaryReader::operator >> (unsigned short& value) -{ - _istr.read((char*) &value, sizeof(value)); - if (_flipBytes) value = ByteOrder::flipBytes(value); - return *this; -} - - -BinaryReader& BinaryReader::operator >> (int& value) -{ - _istr.read((char*) &value, sizeof(value)); - if (_flipBytes) value = ByteOrder::flipBytes(value); - return *this; -} - - -BinaryReader& BinaryReader::operator >> (unsigned int& value) -{ - _istr.read((char*) &value, sizeof(value)); - if (_flipBytes) value = ByteOrder::flipBytes(value); - return *this; -} - - -BinaryReader& BinaryReader::operator >> (long& value) -{ - _istr.read((char*) &value, sizeof(value)); -#if defined(POCO_LONG_IS_64_BIT) - if (_flipBytes) value = ByteOrder::flipBytes((Int64) value); -#else - if (_flipBytes) value = ByteOrder::flipBytes((Int32) value); -#endif - return *this; -} - - -BinaryReader& BinaryReader::operator >> (unsigned long& value) -{ - _istr.read((char*) &value, sizeof(value)); -#if defined(POCO_LONG_IS_64_BIT) - if (_flipBytes) value = ByteOrder::flipBytes((UInt64) value); -#else - if (_flipBytes) value = ByteOrder::flipBytes((UInt32) value); -#endif - return *this; -} - - -BinaryReader& BinaryReader::operator >> (float& value) -{ - if (_flipBytes) - { - char* ptr = (char*) &value; - ptr += sizeof(value); - for (unsigned i = 0; i < sizeof(value); ++i) - _istr.read(--ptr, 1); - } - else - { - _istr.read((char*) &value, sizeof(value)); - } - return *this; -} - - -BinaryReader& BinaryReader::operator >> (double& value) -{ - if (_flipBytes) - { - char* ptr = (char*) &value; - ptr += sizeof(value); - for (unsigned i = 0; i < sizeof(value); ++i) - _istr.read(--ptr, 1); - } - else - { - _istr.read((char*) &value, sizeof(value)); - } - return *this; -} - - -#if defined(POCO_HAVE_INT64) && !defined(POCO_LONG_IS_64_BIT) - - -BinaryReader& BinaryReader::operator >> (Int64& value) -{ - _istr.read((char*) &value, sizeof(value)); - if (_flipBytes) value = ByteOrder::flipBytes(value); - return *this; -} - - -BinaryReader& BinaryReader::operator >> (UInt64& value) -{ - _istr.read((char*) &value, sizeof(value)); - if (_flipBytes) value = ByteOrder::flipBytes(value); - return *this; -} - - -#endif - - -BinaryReader& BinaryReader::operator >> (std::string& value) -{ - UInt32 size = 0; - read7BitEncoded(size); - value.clear(); - value.reserve(size); - while (size--) - { - char c; - _istr.read(&c, 1); - value += c; - } - return *this; -} - - -void BinaryReader::read7BitEncoded(UInt32& value) -{ - char c; - value = 0; - int s = 0; - do - { - c = 0; - _istr.read(&c, 1); - UInt32 x = (c & 0x7F); - x <<= s; - value += x; - s += 7; - } - while (c & 0x80); -} - - -#if defined(POCO_HAVE_INT64) - - -void BinaryReader::read7BitEncoded(UInt64& value) -{ - char c; - value = 0; - int s = 0; - do - { - c = 0; - _istr.read(&c, 1); - UInt64 x = (c & 0x7F); - x <<= s; - value += x; - s += 7; - } - while (c & 0x80); -} - - -#endif - - -void BinaryReader::readRaw(int length, std::string& value) -{ - value.clear(); - value.reserve(length); - while (length--) - { - char c; - _istr.read(&c, 1); - value += c; - } -} - - -void BinaryReader::readBOM() -{ - UInt16 bom; - _istr.read((char*) &bom, sizeof(bom)); - _flipBytes = bom != 0xFEFF; -} - - -} // namespace Poco +// +// BinaryReader.cpp +// +// $Id: //poco/1.2/Foundation/src/BinaryReader.cpp#1 $ +// +// Library: Foundation +// Package: Streams +// Module: BinaryReaderWriter +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/BinaryReader.h" +#include "Poco/ByteOrder.h" + + +namespace Poco { + + +BinaryReader::BinaryReader(std::istream& istr, StreamByteOrder byteOrder): + _istr(istr) +{ +#if defined(POCO_ARCH_BIG_ENDIAN) + _flipBytes = (byteOrder == LITTLE_ENDIAN_BYTE_ORDER); +#else + _flipBytes = (byteOrder == BIG_ENDIAN_BYTE_ORDER); +#endif +} + + +BinaryReader::~BinaryReader() +{ +} + + +BinaryReader& BinaryReader::operator >> (bool& value) +{ + _istr.read((char*) &value, sizeof(value)); + return *this; +} + + +BinaryReader& BinaryReader::operator >> (char& value) +{ + _istr.read((char*) &value, sizeof(value)); + return *this; +} + + +BinaryReader& BinaryReader::operator >> (unsigned char& value) +{ + _istr.read((char*) &value, sizeof(value)); + return *this; +} + + +BinaryReader& BinaryReader::operator >> (signed char& value) +{ + _istr.read((char*) &value, sizeof(value)); + return *this; +} + + +BinaryReader& BinaryReader::operator >> (short& value) +{ + _istr.read((char*) &value, sizeof(value)); + if (_flipBytes) value = ByteOrder::flipBytes(value); + return *this; +} + + +BinaryReader& BinaryReader::operator >> (unsigned short& value) +{ + _istr.read((char*) &value, sizeof(value)); + if (_flipBytes) value = ByteOrder::flipBytes(value); + return *this; +} + + +BinaryReader& BinaryReader::operator >> (int& value) +{ + _istr.read((char*) &value, sizeof(value)); + if (_flipBytes) value = ByteOrder::flipBytes(value); + return *this; +} + + +BinaryReader& BinaryReader::operator >> (unsigned int& value) +{ + _istr.read((char*) &value, sizeof(value)); + if (_flipBytes) value = ByteOrder::flipBytes(value); + return *this; +} + + +BinaryReader& BinaryReader::operator >> (long& value) +{ + _istr.read((char*) &value, sizeof(value)); +#if defined(POCO_LONG_IS_64_BIT) + if (_flipBytes) value = ByteOrder::flipBytes((Int64) value); +#else + if (_flipBytes) value = ByteOrder::flipBytes((Int32) value); +#endif + return *this; +} + + +BinaryReader& BinaryReader::operator >> (unsigned long& value) +{ + _istr.read((char*) &value, sizeof(value)); +#if defined(POCO_LONG_IS_64_BIT) + if (_flipBytes) value = ByteOrder::flipBytes((UInt64) value); +#else + if (_flipBytes) value = ByteOrder::flipBytes((UInt32) value); +#endif + return *this; +} + + +BinaryReader& BinaryReader::operator >> (float& value) +{ + if (_flipBytes) + { + char* ptr = (char*) &value; + ptr += sizeof(value); + for (unsigned i = 0; i < sizeof(value); ++i) + _istr.read(--ptr, 1); + } + else + { + _istr.read((char*) &value, sizeof(value)); + } + return *this; +} + + +BinaryReader& BinaryReader::operator >> (double& value) +{ + if (_flipBytes) + { + char* ptr = (char*) &value; + ptr += sizeof(value); + for (unsigned i = 0; i < sizeof(value); ++i) + _istr.read(--ptr, 1); + } + else + { + _istr.read((char*) &value, sizeof(value)); + } + return *this; +} + + +#if defined(POCO_HAVE_INT64) && !defined(POCO_LONG_IS_64_BIT) + + +BinaryReader& BinaryReader::operator >> (Int64& value) +{ + _istr.read((char*) &value, sizeof(value)); + if (_flipBytes) value = ByteOrder::flipBytes(value); + return *this; +} + + +BinaryReader& BinaryReader::operator >> (UInt64& value) +{ + _istr.read((char*) &value, sizeof(value)); + if (_flipBytes) value = ByteOrder::flipBytes(value); + return *this; +} + + +#endif + + +BinaryReader& BinaryReader::operator >> (std::string& value) +{ + UInt32 size = 0; + read7BitEncoded(size); + value.clear(); + value.reserve(size); + while (size--) + { + char c; + _istr.read(&c, 1); + value += c; + } + return *this; +} + + +void BinaryReader::read7BitEncoded(UInt32& value) +{ + char c; + value = 0; + int s = 0; + do + { + c = 0; + _istr.read(&c, 1); + UInt32 x = (c & 0x7F); + x <<= s; + value += x; + s += 7; + } + while (c & 0x80); +} + + +#if defined(POCO_HAVE_INT64) + + +void BinaryReader::read7BitEncoded(UInt64& value) +{ + char c; + value = 0; + int s = 0; + do + { + c = 0; + _istr.read(&c, 1); + UInt64 x = (c & 0x7F); + x <<= s; + value += x; + s += 7; + } + while (c & 0x80); +} + + +#endif + + +void BinaryReader::readRaw(int length, std::string& value) +{ + value.clear(); + value.reserve(length); + while (length--) + { + char c; + _istr.read(&c, 1); + value += c; + } +} + + +void BinaryReader::readBOM() +{ + UInt16 bom; + _istr.read((char*) &bom, sizeof(bom)); + _flipBytes = bom != 0xFEFF; +} + + +} // namespace Poco diff --git a/Foundation/src/BinaryWriter.cpp b/Foundation/src/BinaryWriter.cpp index 5286d5221..66828021d 100644 --- a/Foundation/src/BinaryWriter.cpp +++ b/Foundation/src/BinaryWriter.cpp @@ -1,328 +1,328 @@ -// -// BinaryWriter.cpp -// -// $Id: //poco/1.2/Foundation/src/BinaryWriter.cpp#1 $ -// -// Library: Foundation -// Package: Streams -// Module: BinaryReaderWriter -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/BinaryWriter.h" -#include "Poco/ByteOrder.h" -#include - - -namespace Poco { - - -BinaryWriter::BinaryWriter(std::ostream& ostr, StreamByteOrder byteOrder): - _ostr(ostr) -{ -#if defined(POCO_ARCH_BIG_ENDIAN) - _flipBytes = (byteOrder == LITTLE_ENDIAN_BYTE_ORDER); -#else - _flipBytes = (byteOrder == BIG_ENDIAN_BYTE_ORDER); -#endif -} - - -BinaryWriter::~BinaryWriter() -{ -} - - -BinaryWriter& BinaryWriter::operator << (bool value) -{ - _ostr.write((const char*) &value, sizeof(value)); - return *this; -} - - -BinaryWriter& BinaryWriter::operator << (char value) -{ - _ostr.write((const char*) &value, sizeof(value)); - return *this; -} - - -BinaryWriter& BinaryWriter::operator << (unsigned char value) -{ - _ostr.write((const char*) &value, sizeof(value)); - return *this; -} - - -BinaryWriter& BinaryWriter::operator << (signed char value) -{ - _ostr.write((const char*) &value, sizeof(value)); - return *this; -} - - -BinaryWriter& BinaryWriter::operator << (short value) -{ - if (_flipBytes) - { - short fValue = ByteOrder::flipBytes(value); - _ostr.write((const char*) &fValue, sizeof(fValue)); - } - else - { - _ostr.write((const char*) &value, sizeof(value)); - } - return *this; -} - - -BinaryWriter& BinaryWriter::operator << (unsigned short value) -{ - if (_flipBytes) - { - unsigned short fValue = ByteOrder::flipBytes(value); - _ostr.write((const char*) &fValue, sizeof(fValue)); - } - else - { - _ostr.write((const char*) &value, sizeof(value)); - } - return *this; -} - - -BinaryWriter& BinaryWriter::operator << (int value) -{ - if (_flipBytes) - { - int fValue = ByteOrder::flipBytes(value); - _ostr.write((const char*) &fValue, sizeof(fValue)); - } - else - { - _ostr.write((const char*) &value, sizeof(value)); - } - return *this; -} - - -BinaryWriter& BinaryWriter::operator << (unsigned int value) -{ - if (_flipBytes) - { - unsigned int fValue = ByteOrder::flipBytes(value); - _ostr.write((const char*) &fValue, sizeof(fValue)); - } - else - { - _ostr.write((const char*) &value, sizeof(value)); - } - return *this; -} - - -BinaryWriter& BinaryWriter::operator << (long value) -{ - if (_flipBytes) - { -#if defined(POCO_LONG_IS_64_BIT) - long fValue = ByteOrder::flipBytes((Int64) value); -#else - long fValue = ByteOrder::flipBytes((Int32) value); -#endif - _ostr.write((const char*) &fValue, sizeof(fValue)); - } - else - { - _ostr.write((const char*) &value, sizeof(value)); - } - return *this; -} - - -BinaryWriter& BinaryWriter::operator << (unsigned long value) -{ - if (_flipBytes) - { -#if defined(POCO_LONG_IS_64_BIT) - long fValue = ByteOrder::flipBytes((UInt64) value); -#else - long fValue = ByteOrder::flipBytes((UInt32) value); -#endif - _ostr.write((const char*) &fValue, sizeof(fValue)); - } - else - { - _ostr.write((const char*) &value, sizeof(value)); - } - return *this; -} - - -BinaryWriter& BinaryWriter::operator << (float value) -{ - if (_flipBytes) - { - const char* ptr = (const char*) &value; - ptr += sizeof(value); - for (unsigned i = 0; i < sizeof(value); ++i) - _ostr.write(--ptr, 1); - } - else - { - _ostr.write((const char*) &value, sizeof(value)); - } - return *this; -} - - -BinaryWriter& BinaryWriter::operator << (double value) -{ - if (_flipBytes) - { - const char* ptr = (const char*) &value; - ptr += sizeof(value); - for (unsigned i = 0; i < sizeof(value); ++i) - _ostr.write(--ptr, 1); - } - else - { - _ostr.write((const char*) &value, sizeof(value)); - } - return *this; -} - - -#if defined(POCO_HAVE_INT64) && !defined(POCO_LONG_IS_64_BIT) - - -BinaryWriter& BinaryWriter::operator << (Int64 value) -{ - if (_flipBytes) - { - Int64 fValue = ByteOrder::flipBytes(value); - _ostr.write((const char*) &fValue, sizeof(fValue)); - } - else - { - _ostr.write((const char*) &value, sizeof(value)); - } - return *this; -} - - -BinaryWriter& BinaryWriter::operator << (UInt64 value) -{ - if (_flipBytes) - { - UInt64 fValue = ByteOrder::flipBytes(value); - _ostr.write((const char*) &fValue, sizeof(fValue)); - } - else - { - _ostr.write((const char*) &value, sizeof(value)); - } - return *this; -} - - -#endif - - -BinaryWriter& BinaryWriter::operator << (const std::string& value) -{ - UInt32 length = (UInt32) value.size(); - write7BitEncoded(length); - _ostr.write(value.data(), length); - return *this; -} - - -BinaryWriter& BinaryWriter::operator << (const char* value) -{ - poco_check_ptr (value); - UInt32 length = (UInt32) strlen(value); - write7BitEncoded(length); - _ostr.write(value, length); - return *this; -} - - -void BinaryWriter::write7BitEncoded(UInt32 value) -{ - do - { - unsigned char c = (unsigned char) (value & 0x7F); - value >>= 7; - if (value) c |= 0x80; - _ostr.write((const char*) &c, 1); - } - while (value); -} - - -#if defined(POCO_HAVE_INT64) - - -void BinaryWriter::write7BitEncoded(UInt64 value) -{ - do - { - unsigned char c = (unsigned char) (value & 0x7F); - value >>= 7; - if (value) c |= 0x80; - _ostr.write((const char*) &c, 1); - } - while (value); -} - - -#endif - - -void BinaryWriter::writeRaw(const std::string& rawData) -{ - _ostr.write(rawData.data(), (std::streamsize) rawData.length()); -} - - -void BinaryWriter::writeBOM() -{ - UInt16 value = 0xFEFF; - if (_flipBytes) value = ByteOrder::flipBytes(value); - _ostr.write((const char*) &value, sizeof(value)); -} - - -void BinaryWriter::flush() -{ - _ostr.flush(); -} - - -} // namespace Poco +// +// BinaryWriter.cpp +// +// $Id: //poco/1.2/Foundation/src/BinaryWriter.cpp#1 $ +// +// Library: Foundation +// Package: Streams +// Module: BinaryReaderWriter +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/BinaryWriter.h" +#include "Poco/ByteOrder.h" +#include + + +namespace Poco { + + +BinaryWriter::BinaryWriter(std::ostream& ostr, StreamByteOrder byteOrder): + _ostr(ostr) +{ +#if defined(POCO_ARCH_BIG_ENDIAN) + _flipBytes = (byteOrder == LITTLE_ENDIAN_BYTE_ORDER); +#else + _flipBytes = (byteOrder == BIG_ENDIAN_BYTE_ORDER); +#endif +} + + +BinaryWriter::~BinaryWriter() +{ +} + + +BinaryWriter& BinaryWriter::operator << (bool value) +{ + _ostr.write((const char*) &value, sizeof(value)); + return *this; +} + + +BinaryWriter& BinaryWriter::operator << (char value) +{ + _ostr.write((const char*) &value, sizeof(value)); + return *this; +} + + +BinaryWriter& BinaryWriter::operator << (unsigned char value) +{ + _ostr.write((const char*) &value, sizeof(value)); + return *this; +} + + +BinaryWriter& BinaryWriter::operator << (signed char value) +{ + _ostr.write((const char*) &value, sizeof(value)); + return *this; +} + + +BinaryWriter& BinaryWriter::operator << (short value) +{ + if (_flipBytes) + { + short fValue = ByteOrder::flipBytes(value); + _ostr.write((const char*) &fValue, sizeof(fValue)); + } + else + { + _ostr.write((const char*) &value, sizeof(value)); + } + return *this; +} + + +BinaryWriter& BinaryWriter::operator << (unsigned short value) +{ + if (_flipBytes) + { + unsigned short fValue = ByteOrder::flipBytes(value); + _ostr.write((const char*) &fValue, sizeof(fValue)); + } + else + { + _ostr.write((const char*) &value, sizeof(value)); + } + return *this; +} + + +BinaryWriter& BinaryWriter::operator << (int value) +{ + if (_flipBytes) + { + int fValue = ByteOrder::flipBytes(value); + _ostr.write((const char*) &fValue, sizeof(fValue)); + } + else + { + _ostr.write((const char*) &value, sizeof(value)); + } + return *this; +} + + +BinaryWriter& BinaryWriter::operator << (unsigned int value) +{ + if (_flipBytes) + { + unsigned int fValue = ByteOrder::flipBytes(value); + _ostr.write((const char*) &fValue, sizeof(fValue)); + } + else + { + _ostr.write((const char*) &value, sizeof(value)); + } + return *this; +} + + +BinaryWriter& BinaryWriter::operator << (long value) +{ + if (_flipBytes) + { +#if defined(POCO_LONG_IS_64_BIT) + long fValue = ByteOrder::flipBytes((Int64) value); +#else + long fValue = ByteOrder::flipBytes((Int32) value); +#endif + _ostr.write((const char*) &fValue, sizeof(fValue)); + } + else + { + _ostr.write((const char*) &value, sizeof(value)); + } + return *this; +} + + +BinaryWriter& BinaryWriter::operator << (unsigned long value) +{ + if (_flipBytes) + { +#if defined(POCO_LONG_IS_64_BIT) + long fValue = ByteOrder::flipBytes((UInt64) value); +#else + long fValue = ByteOrder::flipBytes((UInt32) value); +#endif + _ostr.write((const char*) &fValue, sizeof(fValue)); + } + else + { + _ostr.write((const char*) &value, sizeof(value)); + } + return *this; +} + + +BinaryWriter& BinaryWriter::operator << (float value) +{ + if (_flipBytes) + { + const char* ptr = (const char*) &value; + ptr += sizeof(value); + for (unsigned i = 0; i < sizeof(value); ++i) + _ostr.write(--ptr, 1); + } + else + { + _ostr.write((const char*) &value, sizeof(value)); + } + return *this; +} + + +BinaryWriter& BinaryWriter::operator << (double value) +{ + if (_flipBytes) + { + const char* ptr = (const char*) &value; + ptr += sizeof(value); + for (unsigned i = 0; i < sizeof(value); ++i) + _ostr.write(--ptr, 1); + } + else + { + _ostr.write((const char*) &value, sizeof(value)); + } + return *this; +} + + +#if defined(POCO_HAVE_INT64) && !defined(POCO_LONG_IS_64_BIT) + + +BinaryWriter& BinaryWriter::operator << (Int64 value) +{ + if (_flipBytes) + { + Int64 fValue = ByteOrder::flipBytes(value); + _ostr.write((const char*) &fValue, sizeof(fValue)); + } + else + { + _ostr.write((const char*) &value, sizeof(value)); + } + return *this; +} + + +BinaryWriter& BinaryWriter::operator << (UInt64 value) +{ + if (_flipBytes) + { + UInt64 fValue = ByteOrder::flipBytes(value); + _ostr.write((const char*) &fValue, sizeof(fValue)); + } + else + { + _ostr.write((const char*) &value, sizeof(value)); + } + return *this; +} + + +#endif + + +BinaryWriter& BinaryWriter::operator << (const std::string& value) +{ + UInt32 length = (UInt32) value.size(); + write7BitEncoded(length); + _ostr.write(value.data(), length); + return *this; +} + + +BinaryWriter& BinaryWriter::operator << (const char* value) +{ + poco_check_ptr (value); + UInt32 length = (UInt32) strlen(value); + write7BitEncoded(length); + _ostr.write(value, length); + return *this; +} + + +void BinaryWriter::write7BitEncoded(UInt32 value) +{ + do + { + unsigned char c = (unsigned char) (value & 0x7F); + value >>= 7; + if (value) c |= 0x80; + _ostr.write((const char*) &c, 1); + } + while (value); +} + + +#if defined(POCO_HAVE_INT64) + + +void BinaryWriter::write7BitEncoded(UInt64 value) +{ + do + { + unsigned char c = (unsigned char) (value & 0x7F); + value >>= 7; + if (value) c |= 0x80; + _ostr.write((const char*) &c, 1); + } + while (value); +} + + +#endif + + +void BinaryWriter::writeRaw(const std::string& rawData) +{ + _ostr.write(rawData.data(), (std::streamsize) rawData.length()); +} + + +void BinaryWriter::writeBOM() +{ + UInt16 value = 0xFEFF; + if (_flipBytes) value = ByteOrder::flipBytes(value); + _ostr.write((const char*) &value, sizeof(value)); +} + + +void BinaryWriter::flush() +{ + _ostr.flush(); +} + + +} // namespace Poco diff --git a/Foundation/src/Bugcheck.cpp b/Foundation/src/Bugcheck.cpp index 208a03ca4..c2ace7d0c 100644 --- a/Foundation/src/Bugcheck.cpp +++ b/Foundation/src/Bugcheck.cpp @@ -1,103 +1,103 @@ -// -// Bugcheck.cpp -// -// $Id: //poco/1.2/Foundation/src/Bugcheck.cpp#1 $ -// -// Library: Foundation -// Package: Core -// Module: Bugcheck -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/Bugcheck.h" -#include "Poco/Debugger.h" -#include "Poco/Exception.h" -#include - - -namespace Poco { - - -void Bugcheck::assertion(const char* cond, const char* file, int line) -{ - Debugger::enter(std::string("Assertion violation: ") + cond, file, line); - throw AssertionViolationException(what(cond, file, line)); -} - - -void Bugcheck::nullPointer(const char* ptr, const char* file, int line) -{ - Debugger::enter(std::string("NULL pointer: ") + ptr, file, line); - throw NullPointerException(what(ptr, file, line)); -} - - -void Bugcheck::bugcheck(const char* file, int line) -{ - Debugger::enter("Bugcheck", file, line); - throw BugcheckException(what(0, file, line)); -} - - -void Bugcheck::bugcheck(const char* msg, const char* file, int line) -{ - std::string m("Bugcheck"); - if (msg) - { - m.append(": "); - m.append(msg); - } - Debugger::enter(m, file, line); - throw BugcheckException(what(msg, file, line)); -} - - -void Bugcheck::debugger(const char* file, int line) -{ - Debugger::enter(file, line); -} - - -void Bugcheck::debugger(const char* msg, const char* file, int line) -{ - Debugger::enter(msg, file, line); -} - - -std::string Bugcheck::what(const char* msg, const char* file, int line) -{ - std::ostringstream str; - if (msg) str << msg << " "; - str << "in file \"" << file << "\", line " << line; - return str.str(); -} - - - - -} // namespace Poco +// +// Bugcheck.cpp +// +// $Id: //poco/1.2/Foundation/src/Bugcheck.cpp#1 $ +// +// Library: Foundation +// Package: Core +// Module: Bugcheck +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/Bugcheck.h" +#include "Poco/Debugger.h" +#include "Poco/Exception.h" +#include + + +namespace Poco { + + +void Bugcheck::assertion(const char* cond, const char* file, int line) +{ + Debugger::enter(std::string("Assertion violation: ") + cond, file, line); + throw AssertionViolationException(what(cond, file, line)); +} + + +void Bugcheck::nullPointer(const char* ptr, const char* file, int line) +{ + Debugger::enter(std::string("NULL pointer: ") + ptr, file, line); + throw NullPointerException(what(ptr, file, line)); +} + + +void Bugcheck::bugcheck(const char* file, int line) +{ + Debugger::enter("Bugcheck", file, line); + throw BugcheckException(what(0, file, line)); +} + + +void Bugcheck::bugcheck(const char* msg, const char* file, int line) +{ + std::string m("Bugcheck"); + if (msg) + { + m.append(": "); + m.append(msg); + } + Debugger::enter(m, file, line); + throw BugcheckException(what(msg, file, line)); +} + + +void Bugcheck::debugger(const char* file, int line) +{ + Debugger::enter(file, line); +} + + +void Bugcheck::debugger(const char* msg, const char* file, int line) +{ + Debugger::enter(msg, file, line); +} + + +std::string Bugcheck::what(const char* msg, const char* file, int line) +{ + std::ostringstream str; + if (msg) str << msg << " "; + str << "in file \"" << file << "\", line " << line; + return str.str(); +} + + + + +} // namespace Poco diff --git a/Foundation/src/ByteOrder.cpp b/Foundation/src/ByteOrder.cpp index f2ad75010..b4c4545f4 100644 --- a/Foundation/src/ByteOrder.cpp +++ b/Foundation/src/ByteOrder.cpp @@ -1,37 +1,37 @@ -// -// ByteOrder.cpp -// -// $Id: //poco/1.2/Foundation/src/ByteOrder.cpp#1 $ -// -// Library: Foundation -// Package: Core -// Module: ByteOrder -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/ByteOrder.h" +// +// ByteOrder.cpp +// +// $Id: //poco/1.2/Foundation/src/ByteOrder.cpp#1 $ +// +// Library: Foundation +// Package: Core +// Module: ByteOrder +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/ByteOrder.h" diff --git a/Foundation/src/Channel.cpp b/Foundation/src/Channel.cpp index 763a98f42..91bd2ad72 100644 --- a/Foundation/src/Channel.cpp +++ b/Foundation/src/Channel.cpp @@ -1,75 +1,75 @@ -// -// Channel.cpp -// -// $Id: //poco/1.2/Foundation/src/Channel.cpp#1 $ -// -// Library: Foundation -// Package: Logging -// Module: Channel -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/Channel.h" - - -namespace Poco { - - -Channel::Channel() -{ -} - - -Channel::~Channel() -{ -} - - -void Channel::open() -{ -} - - -void Channel::close() -{ -} - - -void Channel::setProperty(const std::string& name, const std::string& value) -{ - throw PropertyNotSupportedException(name); -} - - -std::string Channel::getProperty(const std::string& name) const -{ - throw PropertyNotSupportedException(name); -} - - -} // namespace Poco +// +// Channel.cpp +// +// $Id: //poco/1.2/Foundation/src/Channel.cpp#1 $ +// +// Library: Foundation +// Package: Logging +// Module: Channel +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/Channel.h" + + +namespace Poco { + + +Channel::Channel() +{ +} + + +Channel::~Channel() +{ +} + + +void Channel::open() +{ +} + + +void Channel::close() +{ +} + + +void Channel::setProperty(const std::string& name, const std::string& value) +{ + throw PropertyNotSupportedException(name); +} + + +std::string Channel::getProperty(const std::string& name) const +{ + throw PropertyNotSupportedException(name); +} + + +} // namespace Poco diff --git a/Foundation/src/Configurable.cpp b/Foundation/src/Configurable.cpp index b74872dee..5dad1be7e 100644 --- a/Foundation/src/Configurable.cpp +++ b/Foundation/src/Configurable.cpp @@ -1,53 +1,53 @@ -// -// Configurable.cpp -// -// $Id: //poco/1.2/Foundation/src/Configurable.cpp#1 $ -// -// Library: Foundation -// Package: Logging -// Module: Configurable -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/Configurable.h" - - -namespace Poco { - - -Configurable::Configurable() -{ -} - - -Configurable::~Configurable() -{ -} - - -} // namespace Poco +// +// Configurable.cpp +// +// $Id: //poco/1.2/Foundation/src/Configurable.cpp#1 $ +// +// Library: Foundation +// Package: Logging +// Module: Configurable +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/Configurable.h" + + +namespace Poco { + + +Configurable::Configurable() +{ +} + + +Configurable::~Configurable() +{ +} + + +} // namespace Poco diff --git a/Foundation/src/ConsoleChannel.cpp b/Foundation/src/ConsoleChannel.cpp index 1919fb372..fed02bce7 100644 --- a/Foundation/src/ConsoleChannel.cpp +++ b/Foundation/src/ConsoleChannel.cpp @@ -1,71 +1,71 @@ -// -// ConsoleChannel.cpp -// -// $Id: //poco/1.2/Foundation/src/ConsoleChannel.cpp#1 $ -// -// Library: Foundation -// Package: Logging -// Module: ConsoleChannel -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/ConsoleChannel.h" -#include "Poco/Message.h" -#include - - -namespace Poco { - - -FastMutex ConsoleChannel::_mutex; - - -ConsoleChannel::ConsoleChannel(): _str(std::clog) -{ -} - - -ConsoleChannel::ConsoleChannel(std::ostream& str): _str(str) -{ -} - - -ConsoleChannel::~ConsoleChannel() -{ -} - - -void ConsoleChannel::log(const Message& msg) -{ - FastMutex::ScopedLock lock(_mutex); - - _str << msg.getText() << std::endl; -} - - -} // namespace Poco +// +// ConsoleChannel.cpp +// +// $Id: //poco/1.2/Foundation/src/ConsoleChannel.cpp#1 $ +// +// Library: Foundation +// Package: Logging +// Module: ConsoleChannel +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/ConsoleChannel.h" +#include "Poco/Message.h" +#include + + +namespace Poco { + + +FastMutex ConsoleChannel::_mutex; + + +ConsoleChannel::ConsoleChannel(): _str(std::clog) +{ +} + + +ConsoleChannel::ConsoleChannel(std::ostream& str): _str(str) +{ +} + + +ConsoleChannel::~ConsoleChannel() +{ +} + + +void ConsoleChannel::log(const Message& msg) +{ + FastMutex::ScopedLock lock(_mutex); + + _str << msg.getText() << std::endl; +} + + +} // namespace Poco diff --git a/Foundation/src/CountingStream.cpp b/Foundation/src/CountingStream.cpp index 6e25d0211..685fa4f79 100644 --- a/Foundation/src/CountingStream.cpp +++ b/Foundation/src/CountingStream.cpp @@ -1,185 +1,185 @@ -// -// CountingStream.cpp -// -// $Id: //poco/1.2/Foundation/src/CountingStream.cpp#1 $ -// -// Library: Foundation -// Package: Streams -// Module: CountingStream -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/CountingStream.h" - - -namespace Poco { - - -CountingStreamBuf::CountingStreamBuf(): - _pIstr(0), - _pOstr(0), - _chars(0), - _lines(0), - _pos(0) -{ -} - - -CountingStreamBuf::CountingStreamBuf(std::istream& istr): - _pIstr(&istr), - _pOstr(0), - _chars(0), - _lines(0), - _pos(0) -{ -} - - -CountingStreamBuf::CountingStreamBuf(std::ostream& ostr): - _pIstr(0), - _pOstr(&ostr), - _chars(0), - _lines(0), - _pos(0) -{ -} - - -CountingStreamBuf::~CountingStreamBuf() -{ -} - - -int CountingStreamBuf::readFromDevice() -{ - if (_pIstr) - { - int c = _pIstr->get(); - if (c != -1) - { - ++_chars; - if (_pos++ == 0) ++_lines; - if (c == '\n') _pos = 0; - } - return c; - } - return -1; -} - - -int CountingStreamBuf::writeToDevice(char c) -{ - ++_chars; - if (_pos++ == 0) ++_lines; - if (c == '\n') _pos = 0; - if (_pOstr) _pOstr->put(c); - return charToInt(c); -} - - -void CountingStreamBuf::reset() -{ - _chars = 0; - _lines = 0; - _pos = 0; -} - - -void CountingStreamBuf::setCurrentLineNumber(int line) -{ - _lines = line; -} - - -CountingIOS::CountingIOS() -{ - poco_ios_init(&_buf); -} - - -CountingIOS::CountingIOS(std::istream& istr): _buf(istr) -{ - poco_ios_init(&_buf); -} - - -CountingIOS::CountingIOS(std::ostream& ostr): _buf(ostr) -{ - poco_ios_init(&_buf); -} - - -CountingIOS::~CountingIOS() -{ -} - - -void CountingIOS::reset() -{ - _buf.reset(); -} - - -void CountingIOS::setCurrentLineNumber(int line) -{ - _buf.setCurrentLineNumber(line); -} - - -CountingStreamBuf* CountingIOS::rdbuf() -{ - return &_buf; -} - - -CountingInputStream::CountingInputStream(std::istream& istr): CountingIOS(istr), std::istream(&_buf) -{ -} - - -CountingInputStream::~CountingInputStream() -{ -} - - -CountingOutputStream::CountingOutputStream(): std::ostream(&_buf) -{ -} - - -CountingOutputStream::CountingOutputStream(std::ostream& ostr): CountingIOS(ostr), std::ostream(&_buf) -{ -} - - -CountingOutputStream::~CountingOutputStream() -{ -} - - -} // namespace Poco +// +// CountingStream.cpp +// +// $Id: //poco/1.2/Foundation/src/CountingStream.cpp#1 $ +// +// Library: Foundation +// Package: Streams +// Module: CountingStream +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/CountingStream.h" + + +namespace Poco { + + +CountingStreamBuf::CountingStreamBuf(): + _pIstr(0), + _pOstr(0), + _chars(0), + _lines(0), + _pos(0) +{ +} + + +CountingStreamBuf::CountingStreamBuf(std::istream& istr): + _pIstr(&istr), + _pOstr(0), + _chars(0), + _lines(0), + _pos(0) +{ +} + + +CountingStreamBuf::CountingStreamBuf(std::ostream& ostr): + _pIstr(0), + _pOstr(&ostr), + _chars(0), + _lines(0), + _pos(0) +{ +} + + +CountingStreamBuf::~CountingStreamBuf() +{ +} + + +int CountingStreamBuf::readFromDevice() +{ + if (_pIstr) + { + int c = _pIstr->get(); + if (c != -1) + { + ++_chars; + if (_pos++ == 0) ++_lines; + if (c == '\n') _pos = 0; + } + return c; + } + return -1; +} + + +int CountingStreamBuf::writeToDevice(char c) +{ + ++_chars; + if (_pos++ == 0) ++_lines; + if (c == '\n') _pos = 0; + if (_pOstr) _pOstr->put(c); + return charToInt(c); +} + + +void CountingStreamBuf::reset() +{ + _chars = 0; + _lines = 0; + _pos = 0; +} + + +void CountingStreamBuf::setCurrentLineNumber(int line) +{ + _lines = line; +} + + +CountingIOS::CountingIOS() +{ + poco_ios_init(&_buf); +} + + +CountingIOS::CountingIOS(std::istream& istr): _buf(istr) +{ + poco_ios_init(&_buf); +} + + +CountingIOS::CountingIOS(std::ostream& ostr): _buf(ostr) +{ + poco_ios_init(&_buf); +} + + +CountingIOS::~CountingIOS() +{ +} + + +void CountingIOS::reset() +{ + _buf.reset(); +} + + +void CountingIOS::setCurrentLineNumber(int line) +{ + _buf.setCurrentLineNumber(line); +} + + +CountingStreamBuf* CountingIOS::rdbuf() +{ + return &_buf; +} + + +CountingInputStream::CountingInputStream(std::istream& istr): CountingIOS(istr), std::istream(&_buf) +{ +} + + +CountingInputStream::~CountingInputStream() +{ +} + + +CountingOutputStream::CountingOutputStream(): std::ostream(&_buf) +{ +} + + +CountingOutputStream::CountingOutputStream(std::ostream& ostr): CountingIOS(ostr), std::ostream(&_buf) +{ +} + + +CountingOutputStream::~CountingOutputStream() +{ +} + + +} // namespace Poco diff --git a/Foundation/src/DateTime.cpp b/Foundation/src/DateTime.cpp index 7a0aed35c..28e35172e 100644 --- a/Foundation/src/DateTime.cpp +++ b/Foundation/src/DateTime.cpp @@ -1,410 +1,410 @@ -// -// DateTime.cpp -// -// $Id: //poco/1.2/Foundation/src/DateTime.cpp#1 $ -// -// Library: Foundation -// Package: DateTime -// Module: DateTime -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/DateTime.h" -#include -#include - - -namespace Poco { - - -inline double DateTime::toJulianDay(Timestamp::UtcTimeVal utcTime) -{ - double utcDays = double(utcTime)/864000000000.0; - return utcDays + 2299160.5; // first day of Gregorian reform (Oct 15 1582) -} - - -inline Timestamp::UtcTimeVal DateTime::toUtcTime(double julianDay) -{ - return Timestamp::UtcTimeVal((julianDay - 2299160.5)*864000000000.0); -} - - -DateTime::DateTime() -{ - Timestamp now; - _utcTime = now.utcTime(); - computeGregorian(julianDay()); - computeDaytime(); -} - - -DateTime::DateTime(const Timestamp& timestamp): - _utcTime(timestamp.utcTime()) -{ - computeGregorian(julianDay()); - computeDaytime(); -} - - -DateTime::DateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int microsecond): - _year(year), - _month(month), - _day(day), - _hour(hour), - _minute(minute), - _second(second), - _millisecond(millisecond), - _microsecond(microsecond) -{ - poco_assert (year >= 0 && year <= 9999); - poco_assert (month >= 1 && month <= 12); - poco_assert (day >= 1 && day <= daysOfMonth(year, month)); - poco_assert (hour >= 0 && hour <= 23); - poco_assert (minute >= 0 && minute <= 59); - poco_assert (second >= 0 && second <= 59); - poco_assert (millisecond >= 0 && millisecond <= 999); - poco_assert (microsecond >= 0 && microsecond <= 999); - - _utcTime = toUtcTime(toJulianDay(year, month, day)) + 10*(hour*Timespan::HOURS + minute*Timespan::MINUTES + second*Timespan::SECONDS + millisecond*Timespan::MILLISECONDS + microsecond); -} - - -DateTime::DateTime(double julianDay): - _utcTime(toUtcTime(julianDay)) -{ - computeGregorian(julianDay); -} - - -DateTime::DateTime(Timestamp::UtcTimeVal utcTime, Timestamp::TimeDiff diff): - _utcTime(utcTime + diff*10) -{ - computeGregorian(julianDay()); - computeDaytime(); -} - - -DateTime::DateTime(const DateTime& dateTime): - _utcTime(dateTime._utcTime), - _year(dateTime._year), - _month(dateTime._month), - _day(dateTime._day), - _hour(dateTime._hour), - _minute(dateTime._minute), - _second(dateTime._second), - _millisecond(dateTime._millisecond), - _microsecond(dateTime._microsecond) -{ -} - - -DateTime::~DateTime() -{ -} - - -DateTime& DateTime::operator = (const DateTime& dateTime) -{ - if (&dateTime != this) - { - _utcTime = dateTime._utcTime; - _year = dateTime._year; - _month = dateTime._month; - _day = dateTime._day; - _hour = dateTime._hour; - _minute = dateTime._minute; - _second = dateTime._second; - _millisecond = dateTime._millisecond; - _microsecond = dateTime._microsecond; - } - return *this; -} - - -DateTime& DateTime::operator = (const Timestamp& timestamp) -{ - _utcTime = timestamp.utcTime(); - computeGregorian(julianDay()); - computeDaytime(); - return *this; -} - - -DateTime& DateTime::operator = (double julianDay) -{ - _utcTime = toUtcTime(julianDay); - computeGregorian(julianDay); - return *this; -} - - -DateTime& DateTime::assign(int year, int month, int day, int hour, int minute, int second, int millisecond, int microsecond) -{ - poco_assert (year >= 0 && year <= 9999); - poco_assert (month >= 1 && month <= 12); - poco_assert (day >= 1 && day <= daysOfMonth(year, month)); - poco_assert (hour >= 0 && hour <= 23); - poco_assert (minute >= 0 && minute <= 59); - poco_assert (second >= 0 && second <= 59); - poco_assert (millisecond >= 0 && millisecond <= 999); - poco_assert (microsecond >= 0 && microsecond <= 999); - - _utcTime = toUtcTime(toJulianDay(year, month, day)) + 10*(hour*Timespan::HOURS + minute*Timespan::MINUTES + second*Timespan::SECONDS + millisecond*Timespan::MILLISECONDS + microsecond); - _year = year; - _month = month; - _day = day; - _hour = hour; - _minute = minute; - _second = second; - _millisecond = millisecond; - _microsecond = microsecond; - - return *this; -} - - -void DateTime::swap(DateTime& dateTime) -{ - std::swap(_utcTime, dateTime._utcTime); - std::swap(_year, dateTime._year); - std::swap(_month, dateTime._month); - std::swap(_day, dateTime._day); - std::swap(_hour, dateTime._hour); - std::swap(_minute, dateTime._minute); - std::swap(_second, dateTime._second); - std::swap(_millisecond, dateTime._millisecond); - std::swap(_microsecond, dateTime._microsecond); -} - - -int DateTime::dayOfWeek() const -{ - return int((floor(julianDay() + 1.5))) % 7; -} - - -int DateTime::dayOfYear() const -{ - int doy = 0; - for (int month = 1; month < _month; ++month) - doy += daysOfMonth(_year, month); - doy += _day; - return doy; -} - - -int DateTime::daysOfMonth(int year, int month) -{ - poco_assert (month >= 1 && month <= 12); - - static int daysOfMonthTable[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; - - if (month == 2 && isLeapYear(year)) - return 29; - else - return daysOfMonthTable[month]; -} - - -bool DateTime::isValid(int year, int month, int day, int hour, int minute, int second, int millisecond, int microsecond) -{ - return - (year >= 0 && year <= 9999) && - (month >= 1 && month <= 12) && - (day >= 1 && day <= daysOfMonth(year, month)) && - (hour >= 0 && hour <= 23) && - (minute >= 0 && minute <= 59) && - (second >= 0 && second <= 59) && - (millisecond >= 0 && millisecond <= 999) && - (microsecond >= 0 && microsecond <= 999); -} - - -int DateTime::week(int firstDayOfWeek) const -{ - poco_assert (firstDayOfWeek >= 0 && firstDayOfWeek <= 6); - - /// find the first firstDayOfWeek. - int baseDay = 1; - while (DateTime(_year, 1, baseDay).dayOfWeek() != firstDayOfWeek) ++baseDay; - - int doy = dayOfYear(); - int offs = baseDay <= 4 ? 0 : 1; - if (doy < baseDay) - return offs; - else - return (doy - baseDay)/7 + 1 + offs; -} - - -double DateTime::julianDay() const -{ - return toJulianDay(_utcTime); -} - - -DateTime DateTime::operator + (const Timespan& span) const -{ - return DateTime(_utcTime, span.totalMicroseconds()); -} - - -DateTime DateTime::operator - (const Timespan& span) const -{ - return DateTime(_utcTime, -span.totalMicroseconds()); -} - - -Timespan DateTime::operator - (const DateTime& dateTime) const -{ - return Timespan((_utcTime - dateTime._utcTime)/10); -} - - -DateTime& DateTime::operator += (const Timespan& span) -{ - _utcTime += span.totalMicroseconds()*10; - computeGregorian(julianDay()); - computeDaytime(); - return *this; -} - - -DateTime& DateTime::operator -= (const Timespan& span) -{ - _utcTime -= span.totalMicroseconds()*10; - computeGregorian(julianDay()); - computeDaytime(); - return *this; -} - - -double DateTime::toJulianDay(int year, int month, int day, int hour, int minute, int second, int millisecond, int microsecond) -{ - // lookup table for (153*month - 457)/5 - note that 3 <= month <= 14. - static int lookup[] = {-91, -60, -30, 0, 31, 61, 92, 122, 153, 184, 214, 245, 275, 306, 337}; - - // day to double - double dday = double(day) + ((double((hour*60 + minute)*60 + second)*1000 + millisecond)*1000 + microsecond)/86400000000.0; - if (month < 3) - { - month += 12; - --year; - } - double dyear = double(year); - return dday + lookup[month] + 365*year + floor(dyear/4) - floor(dyear/100) + floor(dyear/400) + 1721118.5; -} - - -void DateTime::checkLimit(short& lower, short& higher, short limit) -{ - if (lower > limit) - { - higher += short(lower / limit); - lower = short(lower % limit); - } -} - - -void DateTime::normalize() -{ - checkLimit(_microsecond, _millisecond, 999); - checkLimit(_millisecond, _second, 999); - checkLimit(_second, _minute, 59); - checkLimit(_minute, _hour, 59); - checkLimit(_hour, _day, 23); - - if (_day > daysOfMonth(_year, _month)) - { - _day -= daysOfMonth(_year, _month); - if (++_month > 12) - { - ++_year; - _month -= 12; - } - } -} - - -void DateTime::computeGregorian(double julianDay) -{ - double z = floor(julianDay - 1721118.5); - double r = julianDay - 1721118.5 - z; - double g = z - 0.25; - double a = floor(g / 36524.25); - double b = a - floor(a/4); - _year = short(floor((b + g)/365.25)); - double c = b + z - floor(365.25*_year); - _month = short(floor((5*c + 456)/153)); - double dday = c - floor((153.0*_month - 457)/5) + r; - _day = short(dday); - if (_month > 12) - { - ++_year; - _month -= 12; - } - r *= 24; - _hour = short(floor(r)); - r -= floor(r); - r *= 60; - _minute = short(floor(r)); - r -= floor(r); - r *= 60; - _second = short(floor(r)); - r -= floor(r); - r *= 1000; - _millisecond = short(floor(r)); - r -= floor(r); - r *= 1000; - _microsecond = short(r + 0.5); - - normalize(); - - poco_assert_dbg (_month >= 1 && _month <= 12); - poco_assert_dbg (_day >= 1 && _day <= daysOfMonth(_year, _month)); - poco_assert_dbg (_hour >= 0 && _hour <= 23); - poco_assert_dbg (_minute >= 0 && _minute <= 59); - poco_assert_dbg (_second >= 0 && _second <= 59); - poco_assert_dbg (_millisecond >= 0 && _millisecond <= 999); - poco_assert_dbg (_microsecond >= 0 && _microsecond <= 999); -} - - -void DateTime::computeDaytime() -{ - Timespan span(_utcTime/10); - _hour = span.hours(); - _minute = span.minutes(); - _second = span.seconds(); - _millisecond = span.milliseconds(); - _microsecond = span.microseconds(); -} - - -} // namespace Poco +// +// DateTime.cpp +// +// $Id: //poco/1.2/Foundation/src/DateTime.cpp#1 $ +// +// Library: Foundation +// Package: DateTime +// Module: DateTime +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/DateTime.h" +#include +#include + + +namespace Poco { + + +inline double DateTime::toJulianDay(Timestamp::UtcTimeVal utcTime) +{ + double utcDays = double(utcTime)/864000000000.0; + return utcDays + 2299160.5; // first day of Gregorian reform (Oct 15 1582) +} + + +inline Timestamp::UtcTimeVal DateTime::toUtcTime(double julianDay) +{ + return Timestamp::UtcTimeVal((julianDay - 2299160.5)*864000000000.0); +} + + +DateTime::DateTime() +{ + Timestamp now; + _utcTime = now.utcTime(); + computeGregorian(julianDay()); + computeDaytime(); +} + + +DateTime::DateTime(const Timestamp& timestamp): + _utcTime(timestamp.utcTime()) +{ + computeGregorian(julianDay()); + computeDaytime(); +} + + +DateTime::DateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int microsecond): + _year(year), + _month(month), + _day(day), + _hour(hour), + _minute(minute), + _second(second), + _millisecond(millisecond), + _microsecond(microsecond) +{ + poco_assert (year >= 0 && year <= 9999); + poco_assert (month >= 1 && month <= 12); + poco_assert (day >= 1 && day <= daysOfMonth(year, month)); + poco_assert (hour >= 0 && hour <= 23); + poco_assert (minute >= 0 && minute <= 59); + poco_assert (second >= 0 && second <= 59); + poco_assert (millisecond >= 0 && millisecond <= 999); + poco_assert (microsecond >= 0 && microsecond <= 999); + + _utcTime = toUtcTime(toJulianDay(year, month, day)) + 10*(hour*Timespan::HOURS + minute*Timespan::MINUTES + second*Timespan::SECONDS + millisecond*Timespan::MILLISECONDS + microsecond); +} + + +DateTime::DateTime(double julianDay): + _utcTime(toUtcTime(julianDay)) +{ + computeGregorian(julianDay); +} + + +DateTime::DateTime(Timestamp::UtcTimeVal utcTime, Timestamp::TimeDiff diff): + _utcTime(utcTime + diff*10) +{ + computeGregorian(julianDay()); + computeDaytime(); +} + + +DateTime::DateTime(const DateTime& dateTime): + _utcTime(dateTime._utcTime), + _year(dateTime._year), + _month(dateTime._month), + _day(dateTime._day), + _hour(dateTime._hour), + _minute(dateTime._minute), + _second(dateTime._second), + _millisecond(dateTime._millisecond), + _microsecond(dateTime._microsecond) +{ +} + + +DateTime::~DateTime() +{ +} + + +DateTime& DateTime::operator = (const DateTime& dateTime) +{ + if (&dateTime != this) + { + _utcTime = dateTime._utcTime; + _year = dateTime._year; + _month = dateTime._month; + _day = dateTime._day; + _hour = dateTime._hour; + _minute = dateTime._minute; + _second = dateTime._second; + _millisecond = dateTime._millisecond; + _microsecond = dateTime._microsecond; + } + return *this; +} + + +DateTime& DateTime::operator = (const Timestamp& timestamp) +{ + _utcTime = timestamp.utcTime(); + computeGregorian(julianDay()); + computeDaytime(); + return *this; +} + + +DateTime& DateTime::operator = (double julianDay) +{ + _utcTime = toUtcTime(julianDay); + computeGregorian(julianDay); + return *this; +} + + +DateTime& DateTime::assign(int year, int month, int day, int hour, int minute, int second, int millisecond, int microsecond) +{ + poco_assert (year >= 0 && year <= 9999); + poco_assert (month >= 1 && month <= 12); + poco_assert (day >= 1 && day <= daysOfMonth(year, month)); + poco_assert (hour >= 0 && hour <= 23); + poco_assert (minute >= 0 && minute <= 59); + poco_assert (second >= 0 && second <= 59); + poco_assert (millisecond >= 0 && millisecond <= 999); + poco_assert (microsecond >= 0 && microsecond <= 999); + + _utcTime = toUtcTime(toJulianDay(year, month, day)) + 10*(hour*Timespan::HOURS + minute*Timespan::MINUTES + second*Timespan::SECONDS + millisecond*Timespan::MILLISECONDS + microsecond); + _year = year; + _month = month; + _day = day; + _hour = hour; + _minute = minute; + _second = second; + _millisecond = millisecond; + _microsecond = microsecond; + + return *this; +} + + +void DateTime::swap(DateTime& dateTime) +{ + std::swap(_utcTime, dateTime._utcTime); + std::swap(_year, dateTime._year); + std::swap(_month, dateTime._month); + std::swap(_day, dateTime._day); + std::swap(_hour, dateTime._hour); + std::swap(_minute, dateTime._minute); + std::swap(_second, dateTime._second); + std::swap(_millisecond, dateTime._millisecond); + std::swap(_microsecond, dateTime._microsecond); +} + + +int DateTime::dayOfWeek() const +{ + return int((floor(julianDay() + 1.5))) % 7; +} + + +int DateTime::dayOfYear() const +{ + int doy = 0; + for (int month = 1; month < _month; ++month) + doy += daysOfMonth(_year, month); + doy += _day; + return doy; +} + + +int DateTime::daysOfMonth(int year, int month) +{ + poco_assert (month >= 1 && month <= 12); + + static int daysOfMonthTable[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; + + if (month == 2 && isLeapYear(year)) + return 29; + else + return daysOfMonthTable[month]; +} + + +bool DateTime::isValid(int year, int month, int day, int hour, int minute, int second, int millisecond, int microsecond) +{ + return + (year >= 0 && year <= 9999) && + (month >= 1 && month <= 12) && + (day >= 1 && day <= daysOfMonth(year, month)) && + (hour >= 0 && hour <= 23) && + (minute >= 0 && minute <= 59) && + (second >= 0 && second <= 59) && + (millisecond >= 0 && millisecond <= 999) && + (microsecond >= 0 && microsecond <= 999); +} + + +int DateTime::week(int firstDayOfWeek) const +{ + poco_assert (firstDayOfWeek >= 0 && firstDayOfWeek <= 6); + + /// find the first firstDayOfWeek. + int baseDay = 1; + while (DateTime(_year, 1, baseDay).dayOfWeek() != firstDayOfWeek) ++baseDay; + + int doy = dayOfYear(); + int offs = baseDay <= 4 ? 0 : 1; + if (doy < baseDay) + return offs; + else + return (doy - baseDay)/7 + 1 + offs; +} + + +double DateTime::julianDay() const +{ + return toJulianDay(_utcTime); +} + + +DateTime DateTime::operator + (const Timespan& span) const +{ + return DateTime(_utcTime, span.totalMicroseconds()); +} + + +DateTime DateTime::operator - (const Timespan& span) const +{ + return DateTime(_utcTime, -span.totalMicroseconds()); +} + + +Timespan DateTime::operator - (const DateTime& dateTime) const +{ + return Timespan((_utcTime - dateTime._utcTime)/10); +} + + +DateTime& DateTime::operator += (const Timespan& span) +{ + _utcTime += span.totalMicroseconds()*10; + computeGregorian(julianDay()); + computeDaytime(); + return *this; +} + + +DateTime& DateTime::operator -= (const Timespan& span) +{ + _utcTime -= span.totalMicroseconds()*10; + computeGregorian(julianDay()); + computeDaytime(); + return *this; +} + + +double DateTime::toJulianDay(int year, int month, int day, int hour, int minute, int second, int millisecond, int microsecond) +{ + // lookup table for (153*month - 457)/5 - note that 3 <= month <= 14. + static int lookup[] = {-91, -60, -30, 0, 31, 61, 92, 122, 153, 184, 214, 245, 275, 306, 337}; + + // day to double + double dday = double(day) + ((double((hour*60 + minute)*60 + second)*1000 + millisecond)*1000 + microsecond)/86400000000.0; + if (month < 3) + { + month += 12; + --year; + } + double dyear = double(year); + return dday + lookup[month] + 365*year + floor(dyear/4) - floor(dyear/100) + floor(dyear/400) + 1721118.5; +} + + +void DateTime::checkLimit(short& lower, short& higher, short limit) +{ + if (lower > limit) + { + higher += short(lower / limit); + lower = short(lower % limit); + } +} + + +void DateTime::normalize() +{ + checkLimit(_microsecond, _millisecond, 999); + checkLimit(_millisecond, _second, 999); + checkLimit(_second, _minute, 59); + checkLimit(_minute, _hour, 59); + checkLimit(_hour, _day, 23); + + if (_day > daysOfMonth(_year, _month)) + { + _day -= daysOfMonth(_year, _month); + if (++_month > 12) + { + ++_year; + _month -= 12; + } + } +} + + +void DateTime::computeGregorian(double julianDay) +{ + double z = floor(julianDay - 1721118.5); + double r = julianDay - 1721118.5 - z; + double g = z - 0.25; + double a = floor(g / 36524.25); + double b = a - floor(a/4); + _year = short(floor((b + g)/365.25)); + double c = b + z - floor(365.25*_year); + _month = short(floor((5*c + 456)/153)); + double dday = c - floor((153.0*_month - 457)/5) + r; + _day = short(dday); + if (_month > 12) + { + ++_year; + _month -= 12; + } + r *= 24; + _hour = short(floor(r)); + r -= floor(r); + r *= 60; + _minute = short(floor(r)); + r -= floor(r); + r *= 60; + _second = short(floor(r)); + r -= floor(r); + r *= 1000; + _millisecond = short(floor(r)); + r -= floor(r); + r *= 1000; + _microsecond = short(r + 0.5); + + normalize(); + + poco_assert_dbg (_month >= 1 && _month <= 12); + poco_assert_dbg (_day >= 1 && _day <= daysOfMonth(_year, _month)); + poco_assert_dbg (_hour >= 0 && _hour <= 23); + poco_assert_dbg (_minute >= 0 && _minute <= 59); + poco_assert_dbg (_second >= 0 && _second <= 59); + poco_assert_dbg (_millisecond >= 0 && _millisecond <= 999); + poco_assert_dbg (_microsecond >= 0 && _microsecond <= 999); +} + + +void DateTime::computeDaytime() +{ + Timespan span(_utcTime/10); + _hour = span.hours(); + _minute = span.minutes(); + _second = span.seconds(); + _millisecond = span.milliseconds(); + _microsecond = span.microseconds(); +} + + +} // namespace Poco diff --git a/Foundation/src/DateTimeFormat.cpp b/Foundation/src/DateTimeFormat.cpp index 62da01fc3..6189a1630 100644 --- a/Foundation/src/DateTimeFormat.cpp +++ b/Foundation/src/DateTimeFormat.cpp @@ -1,82 +1,82 @@ -// -// DateTimeFormat.cpp -// -// $Id: //poco/1.2/Foundation/src/DateTimeFormat.cpp#1 $ -// -// Library: Foundation -// Package: DateTime -// Module: DateTimeFormat -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/DateTimeFormat.h" - - -namespace Poco { - - -const std::string DateTimeFormat::ISO8601_FORMAT = "%Y-%m-%dT%H:%M:%S%z"; -const std::string DateTimeFormat::RFC822_FORMAT = "%w, %e %b %y %H:%M:%S %Z"; -const std::string DateTimeFormat::RFC1123_FORMAT = "%w, %e %b %Y %H:%M:%S %Z"; -const std::string DateTimeFormat::HTTP_FORMAT = "%w, %d %b %Y %H:%M:%S %Z"; -const std::string DateTimeFormat::RFC850_FORMAT = "%W, %e-%b-%y %H:%M:%S %Z"; -const std::string DateTimeFormat::RFC1036_FORMAT = "%W, %e %b %y %H:%M:%S %Z"; -const std::string DateTimeFormat::ASCTIME_FORMAT = "%w %b %f %H:%M:%S %Y"; -const std::string DateTimeFormat::SORTABLE_FORMAT = "%Y-%m-%d %H:%M:%S"; - - -const std::string DateTimeFormat::WEEKDAY_NAMES[] = -{ - "Sunday", - "Monday", - "Tuesday", - "Wednesday", - "Thursday", - "Friday", - "Saturday" -}; - - -const std::string DateTimeFormat::MONTH_NAMES[] = -{ - "January", - "February", - "March", - "April", - "May", - "June", - "July", - "August", - "September", - "October", - "November", - "December" -}; - - -} // namespace Poco +// +// DateTimeFormat.cpp +// +// $Id: //poco/1.2/Foundation/src/DateTimeFormat.cpp#1 $ +// +// Library: Foundation +// Package: DateTime +// Module: DateTimeFormat +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/DateTimeFormat.h" + + +namespace Poco { + + +const std::string DateTimeFormat::ISO8601_FORMAT = "%Y-%m-%dT%H:%M:%S%z"; +const std::string DateTimeFormat::RFC822_FORMAT = "%w, %e %b %y %H:%M:%S %Z"; +const std::string DateTimeFormat::RFC1123_FORMAT = "%w, %e %b %Y %H:%M:%S %Z"; +const std::string DateTimeFormat::HTTP_FORMAT = "%w, %d %b %Y %H:%M:%S %Z"; +const std::string DateTimeFormat::RFC850_FORMAT = "%W, %e-%b-%y %H:%M:%S %Z"; +const std::string DateTimeFormat::RFC1036_FORMAT = "%W, %e %b %y %H:%M:%S %Z"; +const std::string DateTimeFormat::ASCTIME_FORMAT = "%w %b %f %H:%M:%S %Y"; +const std::string DateTimeFormat::SORTABLE_FORMAT = "%Y-%m-%d %H:%M:%S"; + + +const std::string DateTimeFormat::WEEKDAY_NAMES[] = +{ + "Sunday", + "Monday", + "Tuesday", + "Wednesday", + "Thursday", + "Friday", + "Saturday" +}; + + +const std::string DateTimeFormat::MONTH_NAMES[] = +{ + "January", + "February", + "March", + "April", + "May", + "June", + "July", + "August", + "September", + "October", + "November", + "December" +}; + + +} // namespace Poco diff --git a/Foundation/src/DateTimeFormatter.cpp b/Foundation/src/DateTimeFormatter.cpp index d2010cf5b..2c5f0533c 100644 --- a/Foundation/src/DateTimeFormatter.cpp +++ b/Foundation/src/DateTimeFormatter.cpp @@ -1,188 +1,188 @@ -// -// DateTimeFormatter.cpp -// -// $Id: //poco/1.2/Foundation/src/DateTimeFormatter.cpp#1 $ -// -// Library: Foundation -// Package: DateTime -// Module: DateTimeFormatter -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/DateTimeFormatter.h" -#include "Poco/DateTimeFormat.h" -#include "Poco/DateTime.h" -#include "Poco/LocalDateTime.h" -#include "Poco/Timestamp.h" -#include "Poco/NumberFormatter.h" - - -namespace Poco { - - -std::string DateTimeFormatter::format(const Timestamp& timestamp, const std::string& fmt, int timeZoneDifferential) -{ - DateTime dateTime(timestamp); - return format(dateTime, fmt, timeZoneDifferential); -} - - -std::string DateTimeFormatter::format(const DateTime& dateTime, const std::string& fmt, int timeZoneDifferential) -{ - std::string result; - std::string::const_iterator it = fmt.begin(); - std::string::const_iterator end = fmt.end(); - while (it != end) - { - if (*it == '%') - { - if (++it != end) - { - switch (*it) - { - case 'w': result.append(DateTimeFormat::WEEKDAY_NAMES[dateTime.dayOfWeek()], 0, 3); break; - case 'W': result.append(DateTimeFormat::WEEKDAY_NAMES[dateTime.dayOfWeek()]); break; - case 'b': result.append(DateTimeFormat::MONTH_NAMES[dateTime.month() - 1], 0, 3); break; - case 'B': result.append(DateTimeFormat::MONTH_NAMES[dateTime.month() - 1]); break; - case 'd': result.append(NumberFormatter::format0(dateTime.day(), 2)); break; - case 'e': result.append(NumberFormatter::format(dateTime.day())); break; - case 'f': result.append(NumberFormatter::format(dateTime.day(), 2)); break; - case 'm': result.append(NumberFormatter::format0(dateTime.month(), 2)); break; - case 'n': result.append(NumberFormatter::format(dateTime.month())); break; - case 'o': result.append(NumberFormatter::format(dateTime.month(), 2)); break; - case 'y': result.append(NumberFormatter::format0(dateTime.year() % 100, 2)); break; - case 'Y': result.append(NumberFormatter::format0(dateTime.year(), 4)); break; - case 'H': result.append(NumberFormatter::format0(dateTime.hour(), 2)); break; - case 'h': result.append(NumberFormatter::format0(dateTime.hourAMPM(), 2)); break; - case 'a': result.append(dateTime.isAM() ? "am" : "pm"); break; - case 'A': result.append(dateTime.isAM() ? "AM" : "PM"); break; - case 'M': result.append(NumberFormatter::format0(dateTime.minute(), 2)); break; - case 'S': result.append(NumberFormatter::format0(dateTime.second(), 2)); break; - case 'i': result.append(NumberFormatter::format0(dateTime.millisecond(), 3)); break; - case 'c': result.append(NumberFormatter::format(dateTime.millisecond()/100)); break; - case 'z': result.append(tzdISO(timeZoneDifferential)); break; - case 'Z': result.append(tzdRFC(timeZoneDifferential)); break; - default: result += *it; - } - ++it; - } - } - else result += *it++; - } - return result; -} - - -std::string DateTimeFormatter::format(const LocalDateTime& dateTime, const std::string& fmt) -{ - return format(dateTime._dateTime, fmt, dateTime._tzd); -} - - -std::string DateTimeFormatter::format(const Timespan& timespan, const std::string& fmt) -{ - std::string result; - std::string::const_iterator it = fmt.begin(); - std::string::const_iterator end = fmt.end(); - while (it != end) - { - if (*it == '%') - { - if (++it != end) - { - switch (*it) - { - case 'd': result.append(NumberFormatter::format(timespan.days())); break; - case 'H': result.append(NumberFormatter::format0(timespan.hours(), 2)); break; - case 'h': result.append(NumberFormatter::format(timespan.totalHours())); break; - case 'M': result.append(NumberFormatter::format0(timespan.minutes(), 2)); break; - case 'm': result.append(NumberFormatter::format(timespan.totalMinutes())); break; - case 'S': result.append(NumberFormatter::format0(timespan.seconds(), 2)); break; - case 's': result.append(NumberFormatter::format(timespan.totalSeconds())); break; - case 'i': result.append(NumberFormatter::format0(timespan.milliseconds(), 3)); break; - case 'c': result.append(NumberFormatter::format(timespan.milliseconds()/100)); break; - default: result += *it; - } - ++it; - } - } - else result += *it++; - } - return result; -} - - -std::string DateTimeFormatter::tzdISO(int timeZoneDifferential) -{ - std::string tzd; - if (timeZoneDifferential != UTC) - { - if (timeZoneDifferential >= 0) - { - tzd += '+'; - tzd += NumberFormatter::format0(timeZoneDifferential/3600, 2); - tzd += ':'; - tzd += NumberFormatter::format0((timeZoneDifferential%3600)/60, 2); - } - else - { - tzd += '-'; - tzd += NumberFormatter::format0(-timeZoneDifferential/3600, 2); - tzd += ':'; - tzd += NumberFormatter::format0((-timeZoneDifferential%3600)/60, 2); - } - } - else tzd = "Z"; - return tzd; -} - - -std::string DateTimeFormatter::tzdRFC(int timeZoneDifferential) -{ - std::string tzd; - if (timeZoneDifferential != UTC) - { - if (timeZoneDifferential >= 0) - { - tzd += '+'; - tzd += NumberFormatter::format0(timeZoneDifferential/3600, 2); - tzd += NumberFormatter::format0((timeZoneDifferential%3600)/60, 2); - } - else - { - tzd += '-'; - tzd += NumberFormatter::format0(-timeZoneDifferential/3600, 2); - tzd += NumberFormatter::format0((-timeZoneDifferential%3600)/60, 2); - } - } - else tzd = "GMT"; - return tzd; -} - - -} // namespace Poco +// +// DateTimeFormatter.cpp +// +// $Id: //poco/1.2/Foundation/src/DateTimeFormatter.cpp#1 $ +// +// Library: Foundation +// Package: DateTime +// Module: DateTimeFormatter +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/DateTimeFormatter.h" +#include "Poco/DateTimeFormat.h" +#include "Poco/DateTime.h" +#include "Poco/LocalDateTime.h" +#include "Poco/Timestamp.h" +#include "Poco/NumberFormatter.h" + + +namespace Poco { + + +std::string DateTimeFormatter::format(const Timestamp& timestamp, const std::string& fmt, int timeZoneDifferential) +{ + DateTime dateTime(timestamp); + return format(dateTime, fmt, timeZoneDifferential); +} + + +std::string DateTimeFormatter::format(const DateTime& dateTime, const std::string& fmt, int timeZoneDifferential) +{ + std::string result; + std::string::const_iterator it = fmt.begin(); + std::string::const_iterator end = fmt.end(); + while (it != end) + { + if (*it == '%') + { + if (++it != end) + { + switch (*it) + { + case 'w': result.append(DateTimeFormat::WEEKDAY_NAMES[dateTime.dayOfWeek()], 0, 3); break; + case 'W': result.append(DateTimeFormat::WEEKDAY_NAMES[dateTime.dayOfWeek()]); break; + case 'b': result.append(DateTimeFormat::MONTH_NAMES[dateTime.month() - 1], 0, 3); break; + case 'B': result.append(DateTimeFormat::MONTH_NAMES[dateTime.month() - 1]); break; + case 'd': result.append(NumberFormatter::format0(dateTime.day(), 2)); break; + case 'e': result.append(NumberFormatter::format(dateTime.day())); break; + case 'f': result.append(NumberFormatter::format(dateTime.day(), 2)); break; + case 'm': result.append(NumberFormatter::format0(dateTime.month(), 2)); break; + case 'n': result.append(NumberFormatter::format(dateTime.month())); break; + case 'o': result.append(NumberFormatter::format(dateTime.month(), 2)); break; + case 'y': result.append(NumberFormatter::format0(dateTime.year() % 100, 2)); break; + case 'Y': result.append(NumberFormatter::format0(dateTime.year(), 4)); break; + case 'H': result.append(NumberFormatter::format0(dateTime.hour(), 2)); break; + case 'h': result.append(NumberFormatter::format0(dateTime.hourAMPM(), 2)); break; + case 'a': result.append(dateTime.isAM() ? "am" : "pm"); break; + case 'A': result.append(dateTime.isAM() ? "AM" : "PM"); break; + case 'M': result.append(NumberFormatter::format0(dateTime.minute(), 2)); break; + case 'S': result.append(NumberFormatter::format0(dateTime.second(), 2)); break; + case 'i': result.append(NumberFormatter::format0(dateTime.millisecond(), 3)); break; + case 'c': result.append(NumberFormatter::format(dateTime.millisecond()/100)); break; + case 'z': result.append(tzdISO(timeZoneDifferential)); break; + case 'Z': result.append(tzdRFC(timeZoneDifferential)); break; + default: result += *it; + } + ++it; + } + } + else result += *it++; + } + return result; +} + + +std::string DateTimeFormatter::format(const LocalDateTime& dateTime, const std::string& fmt) +{ + return format(dateTime._dateTime, fmt, dateTime._tzd); +} + + +std::string DateTimeFormatter::format(const Timespan& timespan, const std::string& fmt) +{ + std::string result; + std::string::const_iterator it = fmt.begin(); + std::string::const_iterator end = fmt.end(); + while (it != end) + { + if (*it == '%') + { + if (++it != end) + { + switch (*it) + { + case 'd': result.append(NumberFormatter::format(timespan.days())); break; + case 'H': result.append(NumberFormatter::format0(timespan.hours(), 2)); break; + case 'h': result.append(NumberFormatter::format(timespan.totalHours())); break; + case 'M': result.append(NumberFormatter::format0(timespan.minutes(), 2)); break; + case 'm': result.append(NumberFormatter::format(timespan.totalMinutes())); break; + case 'S': result.append(NumberFormatter::format0(timespan.seconds(), 2)); break; + case 's': result.append(NumberFormatter::format(timespan.totalSeconds())); break; + case 'i': result.append(NumberFormatter::format0(timespan.milliseconds(), 3)); break; + case 'c': result.append(NumberFormatter::format(timespan.milliseconds()/100)); break; + default: result += *it; + } + ++it; + } + } + else result += *it++; + } + return result; +} + + +std::string DateTimeFormatter::tzdISO(int timeZoneDifferential) +{ + std::string tzd; + if (timeZoneDifferential != UTC) + { + if (timeZoneDifferential >= 0) + { + tzd += '+'; + tzd += NumberFormatter::format0(timeZoneDifferential/3600, 2); + tzd += ':'; + tzd += NumberFormatter::format0((timeZoneDifferential%3600)/60, 2); + } + else + { + tzd += '-'; + tzd += NumberFormatter::format0(-timeZoneDifferential/3600, 2); + tzd += ':'; + tzd += NumberFormatter::format0((-timeZoneDifferential%3600)/60, 2); + } + } + else tzd = "Z"; + return tzd; +} + + +std::string DateTimeFormatter::tzdRFC(int timeZoneDifferential) +{ + std::string tzd; + if (timeZoneDifferential != UTC) + { + if (timeZoneDifferential >= 0) + { + tzd += '+'; + tzd += NumberFormatter::format0(timeZoneDifferential/3600, 2); + tzd += NumberFormatter::format0((timeZoneDifferential%3600)/60, 2); + } + else + { + tzd += '-'; + tzd += NumberFormatter::format0(-timeZoneDifferential/3600, 2); + tzd += NumberFormatter::format0((-timeZoneDifferential%3600)/60, 2); + } + } + else tzd = "GMT"; + return tzd; +} + + +} // namespace Poco diff --git a/Foundation/src/DateTimeParser.cpp b/Foundation/src/DateTimeParser.cpp index 7ff3604e4..c31047ae2 100644 --- a/Foundation/src/DateTimeParser.cpp +++ b/Foundation/src/DateTimeParser.cpp @@ -1,369 +1,369 @@ -// -// DateTimeParser.cpp -// -// $Id: //poco/1.2/Foundation/src/DateTimeParser.cpp#1 $ -// -// Library: Foundation -// Package: DateTime -// Module: DateTimeParser -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/DateTimeParser.h" -#include "Poco/DateTimeFormat.h" -#include "Poco/DateTime.h" -#include "Poco/Exception.h" -#include - - -namespace Poco { - - -#define SKIP_JUNK() \ - while (it != end && !isdigit(*it)) ++it - - -#define PARSE_NUMBER(var) \ - while (it != end && isdigit(*it)) var = var*10 + ((*it++) - '0') - - -#define PARSE_NUMBER_N(var, n) \ - { int i = 0; while (i++ < n && it != end && isdigit(*it)) var = var*10 + ((*it++) - '0'); } - - -void DateTimeParser::parse(const std::string& fmt, const std::string& str, DateTime& dateTime, int& timeZoneDifferential) -{ - int year = 0; - int month = 0; - int day = 0; - int hour = 0; - int minute = 0; - int second = 0; - int millis = 0; - int tzd = 0; - - std::string::const_iterator it = str.begin(); - std::string::const_iterator end = str.end(); - std::string::const_iterator itf = fmt.begin(); - std::string::const_iterator endf = fmt.end(); - - while (itf != endf && it != end) - { - if (*itf == '%') - { - if (++itf != endf) - { - switch (*itf) - { - case 'w': - case 'W': - while (it != end && isspace(*it)) ++it; - while (it != end && isalpha(*it)) ++it; - break; - case 'b': - case 'B': - month = parseMonth(it, end); - break; - case 'd': - case 'e': - case 'f': - SKIP_JUNK(); - PARSE_NUMBER_N(day, 2); - break; - case 'm': - case 'n': - case 'o': - SKIP_JUNK(); - PARSE_NUMBER_N(month, 2); - break; - case 'y': - SKIP_JUNK(); - PARSE_NUMBER(year); - if (year < 1000) - { - if (year >= 70) - year += 1900; - else - year += 2000; - } - break; - case 'Y': - SKIP_JUNK(); - PARSE_NUMBER_N(year, 4); - break; - case 'H': - case 'h': - SKIP_JUNK(); - PARSE_NUMBER_N(hour, 2); - break; - case 'a': - case 'A': - hour = parseAMPM(it, end, hour); - break; - case 'M': - SKIP_JUNK(); - PARSE_NUMBER_N(minute, 2); - break; - case 'S': - SKIP_JUNK(); - PARSE_NUMBER_N(second, 2); - break; - case 'i': - SKIP_JUNK(); - PARSE_NUMBER_N(millis, 3); - break; - case 'c': - SKIP_JUNK(); - PARSE_NUMBER_N(millis, 1); - millis *= 100; - break; - case 'z': - case 'Z': - tzd = parseTZD(it, end); - break; - } - ++itf; - } - } - else ++itf; - } - if (month == 0) month = 1; - if (day == 0) day = 1; - dateTime.assign(year, month, day, hour, minute, second, millis); - timeZoneDifferential = tzd; -} - - -DateTime DateTimeParser::parse(const std::string& fmt, const std::string& str, int& timeZoneDifferential) -{ - DateTime result; - parse(fmt, str, result, timeZoneDifferential); - return result; -} - - -bool DateTimeParser::tryParse(const std::string& fmt, const std::string& str, DateTime& dateTime, int& timeZoneDifferential) -{ - try - { - parse(fmt, str, dateTime, timeZoneDifferential); - } - catch (Exception&) - { - return false; - } - return true; -} - - -void DateTimeParser::parse(const std::string& str, DateTime& dateTime, int& timeZoneDifferential) -{ - if (!tryParse(str, dateTime, timeZoneDifferential)) - throw SyntaxException("Unsupported or invalid date/time format"); -} - - -DateTime DateTimeParser::parse(const std::string& str, int& timeZoneDifferential) -{ - DateTime result; - if (tryParse(str, result, timeZoneDifferential)) - return result; - else - throw SyntaxException("Unsupported or invalid date/time format"); -} - - -bool DateTimeParser::tryParse(const std::string& str, DateTime& dateTime, int& timeZoneDifferential) -{ - if (str.length() < 4) return false; - - if (str[3] == ',') - return tryParse(DateTimeFormat::RFC822_FORMAT, str, dateTime, timeZoneDifferential); - else if (str[3] == ' ') - return tryParse(DateTimeFormat::ASCTIME_FORMAT, str, dateTime, timeZoneDifferential); - else if (str.find(',') != std::string::npos) - return tryParse(DateTimeFormat::RFC850_FORMAT, str, dateTime, timeZoneDifferential); - else if (isdigit(str[0])) - { - if (str.find(' ') != std::string::npos || str.length() == 10) - return tryParse(DateTimeFormat::SORTABLE_FORMAT, str, dateTime, timeZoneDifferential); - else - return tryParse(DateTimeFormat::ISO8601_FORMAT, str, dateTime, timeZoneDifferential); - } - else return false; -} - - -int DateTimeParser::parseTZD(std::string::const_iterator& it, const std::string::const_iterator& end) -{ - struct Zone - { - const char* designator; - int timeZoneDifferential; - }; - - static Zone zones[] = - { - {"Z", 0}, - {"UT", 0}, - {"GMT", 0}, - {"BST", 1*3600}, - {"IST", 1*3600}, - {"WET", 0}, - {"WEST", 1*3600}, - {"CET", 1*3600}, - {"CEST", 2*3600}, - {"EET", 2*3600}, - {"EEST", 3*3600}, - {"MSK", 3*3600}, - {"MSD", 4*3600}, - {"NST", -3*3600-1800}, - {"NDT", -2*3600-1800}, - {"AST", -4*3600}, - {"ADT", -3*3600}, - {"EST", -5*3600}, - {"EDT", -4*3600}, - {"CST", -6*3600}, - {"CDT", -5*3600}, - {"MST", -7*3600}, - {"MDT", -6*3600}, - {"PST", -8*3600}, - {"PDT", -7*3600}, - {"AKST", -9*3600}, - {"AKDT", -8*3600}, - {"HST", -10*3600}, - {"AEST", 10*3600}, - {"AEDT", 11*3600}, - {"ACST", 9*3600+1800}, - {"ACDT", 10*3600+1800}, - {"AWST", 8*3600}, - {"AWDT", 9*3600} - }; - - while (it != end && isspace(*it)) ++it; - if (it != end) - { - if (isalpha(*it)) - { - std::string designator; - designator += *it++; - if (it != end && isalpha(*it)) designator += *it++; - if (it != end && isalpha(*it)) designator += *it++; - if (it != end && isalpha(*it)) designator += *it++; - for (unsigned i = 0; i < sizeof(zones)/sizeof(Zone); ++i) - { - if (designator == zones[i].designator) - return zones[i].timeZoneDifferential; - } - } - else if (*it == '+' || *it == '-') - { - int sign = *it == '+' ? 1 : -1; - ++it; - int hours = 0; - PARSE_NUMBER_N(hours, 2); - if (it != end && *it == ':') ++it; - int minutes = 0; - PARSE_NUMBER_N(minutes, 2); - return sign*(hours*3600 + minutes*60); - } - } - return 0; -} - - -int DateTimeParser::parseMonth(std::string::const_iterator& it, const std::string::const_iterator& end) -{ - std::string month; - while (it != end && isspace(*it) || ispunct(*it)) ++it; - bool isFirst = true; - while (it != end && isalpha(*it)) - { - char ch = (*it++); - if (isFirst) { month += toupper(ch); isFirst = false; } - else month += tolower(ch); - } - if (month.length() < 3) throw SyntaxException("Month name must be at least three characters long", month); - for (int i = 0; i < 12; ++i) - { - if (DateTimeFormat::MONTH_NAMES[i].find(month) == 0) - return i + 1; - } - throw SyntaxException("Not a valid month name", month); -} - - -int DateTimeParser::parseDayOfWeek(std::string::const_iterator& it, const std::string::const_iterator& end) -{ - std::string dow; - while (it != end && isspace(*it) || ispunct(*it)) ++it; - bool isFirst = true; - while (it != end && isalpha(*it)) - { - char ch = (*it++); - if (isFirst) { dow += toupper(ch); isFirst = false; } - else dow += tolower(ch); - } - if (dow.length() < 3) throw SyntaxException("Weekday name must be at least three characters long", dow); - for (int i = 0; i < 7; ++i) - { - if (DateTimeFormat::WEEKDAY_NAMES[i].find(dow) == 0) - return i; - } - throw SyntaxException("Not a valid weekday name", dow); -} - - -int DateTimeParser::parseAMPM(std::string::const_iterator& it, const std::string::const_iterator& end, int hour) -{ - std::string ampm; - while (it != end && isspace(*it) || ispunct(*it)) ++it; - while (it != end && isalpha(*it)) - { - char ch = (*it++); - ampm += toupper(ch); - } - if (ampm == "AM") - { - if (hour == 12) - return 0; - else - return hour; - } - else if (ampm == "PM") - { - if (hour < 12) - return hour + 12; - else - return hour; - } - else throw SyntaxException("Not a valid AM/PM designator", ampm); -} - - -} // namespace Poco +// +// DateTimeParser.cpp +// +// $Id: //poco/1.2/Foundation/src/DateTimeParser.cpp#1 $ +// +// Library: Foundation +// Package: DateTime +// Module: DateTimeParser +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/DateTimeParser.h" +#include "Poco/DateTimeFormat.h" +#include "Poco/DateTime.h" +#include "Poco/Exception.h" +#include + + +namespace Poco { + + +#define SKIP_JUNK() \ + while (it != end && !isdigit(*it)) ++it + + +#define PARSE_NUMBER(var) \ + while (it != end && isdigit(*it)) var = var*10 + ((*it++) - '0') + + +#define PARSE_NUMBER_N(var, n) \ + { int i = 0; while (i++ < n && it != end && isdigit(*it)) var = var*10 + ((*it++) - '0'); } + + +void DateTimeParser::parse(const std::string& fmt, const std::string& str, DateTime& dateTime, int& timeZoneDifferential) +{ + int year = 0; + int month = 0; + int day = 0; + int hour = 0; + int minute = 0; + int second = 0; + int millis = 0; + int tzd = 0; + + std::string::const_iterator it = str.begin(); + std::string::const_iterator end = str.end(); + std::string::const_iterator itf = fmt.begin(); + std::string::const_iterator endf = fmt.end(); + + while (itf != endf && it != end) + { + if (*itf == '%') + { + if (++itf != endf) + { + switch (*itf) + { + case 'w': + case 'W': + while (it != end && isspace(*it)) ++it; + while (it != end && isalpha(*it)) ++it; + break; + case 'b': + case 'B': + month = parseMonth(it, end); + break; + case 'd': + case 'e': + case 'f': + SKIP_JUNK(); + PARSE_NUMBER_N(day, 2); + break; + case 'm': + case 'n': + case 'o': + SKIP_JUNK(); + PARSE_NUMBER_N(month, 2); + break; + case 'y': + SKIP_JUNK(); + PARSE_NUMBER(year); + if (year < 1000) + { + if (year >= 70) + year += 1900; + else + year += 2000; + } + break; + case 'Y': + SKIP_JUNK(); + PARSE_NUMBER_N(year, 4); + break; + case 'H': + case 'h': + SKIP_JUNK(); + PARSE_NUMBER_N(hour, 2); + break; + case 'a': + case 'A': + hour = parseAMPM(it, end, hour); + break; + case 'M': + SKIP_JUNK(); + PARSE_NUMBER_N(minute, 2); + break; + case 'S': + SKIP_JUNK(); + PARSE_NUMBER_N(second, 2); + break; + case 'i': + SKIP_JUNK(); + PARSE_NUMBER_N(millis, 3); + break; + case 'c': + SKIP_JUNK(); + PARSE_NUMBER_N(millis, 1); + millis *= 100; + break; + case 'z': + case 'Z': + tzd = parseTZD(it, end); + break; + } + ++itf; + } + } + else ++itf; + } + if (month == 0) month = 1; + if (day == 0) day = 1; + dateTime.assign(year, month, day, hour, minute, second, millis); + timeZoneDifferential = tzd; +} + + +DateTime DateTimeParser::parse(const std::string& fmt, const std::string& str, int& timeZoneDifferential) +{ + DateTime result; + parse(fmt, str, result, timeZoneDifferential); + return result; +} + + +bool DateTimeParser::tryParse(const std::string& fmt, const std::string& str, DateTime& dateTime, int& timeZoneDifferential) +{ + try + { + parse(fmt, str, dateTime, timeZoneDifferential); + } + catch (Exception&) + { + return false; + } + return true; +} + + +void DateTimeParser::parse(const std::string& str, DateTime& dateTime, int& timeZoneDifferential) +{ + if (!tryParse(str, dateTime, timeZoneDifferential)) + throw SyntaxException("Unsupported or invalid date/time format"); +} + + +DateTime DateTimeParser::parse(const std::string& str, int& timeZoneDifferential) +{ + DateTime result; + if (tryParse(str, result, timeZoneDifferential)) + return result; + else + throw SyntaxException("Unsupported or invalid date/time format"); +} + + +bool DateTimeParser::tryParse(const std::string& str, DateTime& dateTime, int& timeZoneDifferential) +{ + if (str.length() < 4) return false; + + if (str[3] == ',') + return tryParse(DateTimeFormat::RFC822_FORMAT, str, dateTime, timeZoneDifferential); + else if (str[3] == ' ') + return tryParse(DateTimeFormat::ASCTIME_FORMAT, str, dateTime, timeZoneDifferential); + else if (str.find(',') != std::string::npos) + return tryParse(DateTimeFormat::RFC850_FORMAT, str, dateTime, timeZoneDifferential); + else if (isdigit(str[0])) + { + if (str.find(' ') != std::string::npos || str.length() == 10) + return tryParse(DateTimeFormat::SORTABLE_FORMAT, str, dateTime, timeZoneDifferential); + else + return tryParse(DateTimeFormat::ISO8601_FORMAT, str, dateTime, timeZoneDifferential); + } + else return false; +} + + +int DateTimeParser::parseTZD(std::string::const_iterator& it, const std::string::const_iterator& end) +{ + struct Zone + { + const char* designator; + int timeZoneDifferential; + }; + + static Zone zones[] = + { + {"Z", 0}, + {"UT", 0}, + {"GMT", 0}, + {"BST", 1*3600}, + {"IST", 1*3600}, + {"WET", 0}, + {"WEST", 1*3600}, + {"CET", 1*3600}, + {"CEST", 2*3600}, + {"EET", 2*3600}, + {"EEST", 3*3600}, + {"MSK", 3*3600}, + {"MSD", 4*3600}, + {"NST", -3*3600-1800}, + {"NDT", -2*3600-1800}, + {"AST", -4*3600}, + {"ADT", -3*3600}, + {"EST", -5*3600}, + {"EDT", -4*3600}, + {"CST", -6*3600}, + {"CDT", -5*3600}, + {"MST", -7*3600}, + {"MDT", -6*3600}, + {"PST", -8*3600}, + {"PDT", -7*3600}, + {"AKST", -9*3600}, + {"AKDT", -8*3600}, + {"HST", -10*3600}, + {"AEST", 10*3600}, + {"AEDT", 11*3600}, + {"ACST", 9*3600+1800}, + {"ACDT", 10*3600+1800}, + {"AWST", 8*3600}, + {"AWDT", 9*3600} + }; + + while (it != end && isspace(*it)) ++it; + if (it != end) + { + if (isalpha(*it)) + { + std::string designator; + designator += *it++; + if (it != end && isalpha(*it)) designator += *it++; + if (it != end && isalpha(*it)) designator += *it++; + if (it != end && isalpha(*it)) designator += *it++; + for (unsigned i = 0; i < sizeof(zones)/sizeof(Zone); ++i) + { + if (designator == zones[i].designator) + return zones[i].timeZoneDifferential; + } + } + else if (*it == '+' || *it == '-') + { + int sign = *it == '+' ? 1 : -1; + ++it; + int hours = 0; + PARSE_NUMBER_N(hours, 2); + if (it != end && *it == ':') ++it; + int minutes = 0; + PARSE_NUMBER_N(minutes, 2); + return sign*(hours*3600 + minutes*60); + } + } + return 0; +} + + +int DateTimeParser::parseMonth(std::string::const_iterator& it, const std::string::const_iterator& end) +{ + std::string month; + while (it != end && isspace(*it) || ispunct(*it)) ++it; + bool isFirst = true; + while (it != end && isalpha(*it)) + { + char ch = (*it++); + if (isFirst) { month += toupper(ch); isFirst = false; } + else month += tolower(ch); + } + if (month.length() < 3) throw SyntaxException("Month name must be at least three characters long", month); + for (int i = 0; i < 12; ++i) + { + if (DateTimeFormat::MONTH_NAMES[i].find(month) == 0) + return i + 1; + } + throw SyntaxException("Not a valid month name", month); +} + + +int DateTimeParser::parseDayOfWeek(std::string::const_iterator& it, const std::string::const_iterator& end) +{ + std::string dow; + while (it != end && isspace(*it) || ispunct(*it)) ++it; + bool isFirst = true; + while (it != end && isalpha(*it)) + { + char ch = (*it++); + if (isFirst) { dow += toupper(ch); isFirst = false; } + else dow += tolower(ch); + } + if (dow.length() < 3) throw SyntaxException("Weekday name must be at least three characters long", dow); + for (int i = 0; i < 7; ++i) + { + if (DateTimeFormat::WEEKDAY_NAMES[i].find(dow) == 0) + return i; + } + throw SyntaxException("Not a valid weekday name", dow); +} + + +int DateTimeParser::parseAMPM(std::string::const_iterator& it, const std::string::const_iterator& end, int hour) +{ + std::string ampm; + while (it != end && isspace(*it) || ispunct(*it)) ++it; + while (it != end && isalpha(*it)) + { + char ch = (*it++); + ampm += toupper(ch); + } + if (ampm == "AM") + { + if (hour == 12) + return 0; + else + return hour; + } + else if (ampm == "PM") + { + if (hour < 12) + return hour + 12; + else + return hour; + } + else throw SyntaxException("Not a valid AM/PM designator", ampm); +} + + +} // namespace Poco diff --git a/Foundation/src/Debugger.cpp b/Foundation/src/Debugger.cpp index 876e9ac7d..486bf2480 100644 --- a/Foundation/src/Debugger.cpp +++ b/Foundation/src/Debugger.cpp @@ -1,165 +1,165 @@ -// -// Debugger.cpp -// -// $Id: //poco/1.2/Foundation/src/Debugger.cpp#1 $ -// -// Library: Foundation -// Package: Core -// Module: Debugger -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/Debugger.h" -#include -#include -#include -#if defined(POCO_OS_FAMILY_WINDOWS) - #include -#elif defined(POCO_OS_FAMILY_UNIX) - #include - #include -#elif defined(POCO_OS_FAMILY_VMS) - #include - #include -#endif -#if defined(POCO_WIN32_UTF8) -#include "Poco/UnicodeConverter.h" -#endif - - -// NOTE: In this module, we use the C library functions (fputs) for, -// output since, at the time we're called, the C++ iostream objects std::cout, etc. -// might not have been initialized yet. - - -namespace Poco { - - -bool Debugger::isAvailable() -{ -#if defined(_DEBUG) - #if defined(POCO_OS_FAMILY_WINDOWS) - return IsDebuggerPresent() ? true : false; - #elif defined(POCO_OS_FAMILY_UNIX) - return getenv("POCO_ENABLE_DEBUGGER") ? true : false; - #elif defined(POCO_OS_FAMILY_VMS) - return true; - #endif -#else - return false; -#endif -} - - -void Debugger::message(const std::string& msg) -{ -#if defined(_DEBUG) - fputs("\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n", stderr); - fputs(msg.c_str(), stderr); - fputs("\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n", stderr); - #if defined(POCO_OS_FAMILY_WINDOWS) - if (IsDebuggerPresent()) - { -#if defined(POCO_WIN32_UTF8) - std::wstring umsg; - UnicodeConverter::toUTF16(msg, umsg); - umsg += '\n'; - OutputDebugStringW(umsg.c_str()); -#else - OutputDebugString(msg.c_str()); - OutputDebugString("\n"); -#endif - } - #elif defined(POCO_OS_FAMILY_UNIX) - #elif defined(POCO_OS_FAMILY_VMS) - #endif -#endif -} - - -void Debugger::message(const std::string& msg, const char* file, int line) -{ -#if defined(_DEBUG) - std::ostringstream str; - str << msg << " [in file \"" << file << "\", line " << line << "]"; - message(str.str()); -#endif -} - - -void Debugger::enter() -{ -#if defined(_DEBUG) - #if defined(POCO_OS_FAMILY_WINDOWS) - if (IsDebuggerPresent()) - { - DebugBreak(); - } - #elif defined(POCO_OS_FAMILY_UNIX) - if (isAvailable()) - { - kill(getpid(), SIGINT); - } - #elif defined(POCO_OS_FAMILY_VMS) - { - const char* cmd = "\012SHOW CALLS"; - lib$signal(SS$_DEBUG, 1, cmd); - } - #endif -#endif -} - - -void Debugger::enter(const std::string& msg) -{ -#if defined(_DEBUG) - message(msg); - enter(); -#endif -} - - -void Debugger::enter(const std::string& msg, const char* file, int line) -{ -#if defined(_DEBUG) - message(msg, file, line); - enter(); -#endif -} - - -void Debugger::enter(const char* file, int line) -{ -#if defined(_DEBUG) - message("BREAK", file, line); - enter(); -#endif -} - - -} // namespace Poco +// +// Debugger.cpp +// +// $Id: //poco/1.2/Foundation/src/Debugger.cpp#1 $ +// +// Library: Foundation +// Package: Core +// Module: Debugger +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/Debugger.h" +#include +#include +#include +#if defined(POCO_OS_FAMILY_WINDOWS) + #include +#elif defined(POCO_OS_FAMILY_UNIX) + #include + #include +#elif defined(POCO_OS_FAMILY_VMS) + #include + #include +#endif +#if defined(POCO_WIN32_UTF8) +#include "Poco/UnicodeConverter.h" +#endif + + +// NOTE: In this module, we use the C library functions (fputs) for, +// output since, at the time we're called, the C++ iostream objects std::cout, etc. +// might not have been initialized yet. + + +namespace Poco { + + +bool Debugger::isAvailable() +{ +#if defined(_DEBUG) + #if defined(POCO_OS_FAMILY_WINDOWS) + return IsDebuggerPresent() ? true : false; + #elif defined(POCO_OS_FAMILY_UNIX) + return getenv("POCO_ENABLE_DEBUGGER") ? true : false; + #elif defined(POCO_OS_FAMILY_VMS) + return true; + #endif +#else + return false; +#endif +} + + +void Debugger::message(const std::string& msg) +{ +#if defined(_DEBUG) + fputs("\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n", stderr); + fputs(msg.c_str(), stderr); + fputs("\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n", stderr); + #if defined(POCO_OS_FAMILY_WINDOWS) + if (IsDebuggerPresent()) + { +#if defined(POCO_WIN32_UTF8) + std::wstring umsg; + UnicodeConverter::toUTF16(msg, umsg); + umsg += '\n'; + OutputDebugStringW(umsg.c_str()); +#else + OutputDebugString(msg.c_str()); + OutputDebugString("\n"); +#endif + } + #elif defined(POCO_OS_FAMILY_UNIX) + #elif defined(POCO_OS_FAMILY_VMS) + #endif +#endif +} + + +void Debugger::message(const std::string& msg, const char* file, int line) +{ +#if defined(_DEBUG) + std::ostringstream str; + str << msg << " [in file \"" << file << "\", line " << line << "]"; + message(str.str()); +#endif +} + + +void Debugger::enter() +{ +#if defined(_DEBUG) + #if defined(POCO_OS_FAMILY_WINDOWS) + if (IsDebuggerPresent()) + { + DebugBreak(); + } + #elif defined(POCO_OS_FAMILY_UNIX) + if (isAvailable()) + { + kill(getpid(), SIGINT); + } + #elif defined(POCO_OS_FAMILY_VMS) + { + const char* cmd = "\012SHOW CALLS"; + lib$signal(SS$_DEBUG, 1, cmd); + } + #endif +#endif +} + + +void Debugger::enter(const std::string& msg) +{ +#if defined(_DEBUG) + message(msg); + enter(); +#endif +} + + +void Debugger::enter(const std::string& msg, const char* file, int line) +{ +#if defined(_DEBUG) + message(msg, file, line); + enter(); +#endif +} + + +void Debugger::enter(const char* file, int line) +{ +#if defined(_DEBUG) + message("BREAK", file, line); + enter(); +#endif +} + + +} // namespace Poco diff --git a/Foundation/src/DeflatingStream.cpp b/Foundation/src/DeflatingStream.cpp index 5bc78a06b..adc7be852 100644 --- a/Foundation/src/DeflatingStream.cpp +++ b/Foundation/src/DeflatingStream.cpp @@ -1,287 +1,287 @@ -// -// DeflatingStream.cpp -// -// $Id: //poco/1.2/Foundation/src/DeflatingStream.cpp#1 $ -// -// Library: Foundation -// Package: Streams -// Module: ZLibStream -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/DeflatingStream.h" -#include "Poco/Exception.h" - - -namespace Poco { - - -DeflatingStreamBuf::DeflatingStreamBuf(std::istream& istr, StreamType type, int level): - BufferedStreamBuf(STREAM_BUFFER_SIZE, std::ios::in), - _pIstr(&istr), - _pOstr(0), - _eof(false) -{ - _zstr.zalloc = Z_NULL; - _zstr.zfree = Z_NULL; - _zstr.opaque = Z_NULL; - _zstr.next_in = 0; - _zstr.avail_in = 0; - _zstr.next_out = 0; - _zstr.avail_out = 0; - - int rc = deflateInit2(&_zstr, level, Z_DEFLATED, 15 + (type == STREAM_GZIP ? 16 : 0), 8, Z_DEFAULT_STRATEGY); - if (rc != Z_OK) throw IOException(zError(rc)); - - _buffer = new char[DEFLATE_BUFFER_SIZE]; -} - - -DeflatingStreamBuf::DeflatingStreamBuf(std::ostream& ostr, StreamType type, int level): - BufferedStreamBuf(STREAM_BUFFER_SIZE, std::ios::out), - _pIstr(0), - _pOstr(&ostr), - _eof(false) -{ - _zstr.zalloc = Z_NULL; - _zstr.zfree = Z_NULL; - _zstr.opaque = Z_NULL; - _zstr.next_in = 0; - _zstr.avail_in = 0; - _zstr.next_out = 0; - _zstr.avail_out = 0; - - int rc = deflateInit2(&_zstr, level, Z_DEFLATED, 15 + (type == STREAM_GZIP ? 16 : 0), 8, Z_DEFAULT_STRATEGY); - if (rc != Z_OK) throw IOException(zError(rc)); - - _buffer = new char[DEFLATE_BUFFER_SIZE]; -} - - -DeflatingStreamBuf::~DeflatingStreamBuf() -{ - try - { - close(); - } - catch (...) - { - } - delete [] _buffer; -} - - -int DeflatingStreamBuf::close() -{ - sync(); - if (_pIstr) - { - int rc = deflateEnd(&_zstr); - if (rc != Z_OK) throw IOException(zError(rc)); - _pIstr = 0; - } - else if (_pOstr) - { - if (_zstr.next_out) - { - int rc = deflate(&_zstr, Z_FINISH); - if (rc != Z_OK && rc != Z_STREAM_END) throw IOException(zError(rc)); - _pOstr->write(_buffer, DEFLATE_BUFFER_SIZE - _zstr.avail_out); - if (!_pOstr->good()) throw IOException(zError(rc)); - _zstr.next_out = (unsigned char*) _buffer; - _zstr.avail_out = DEFLATE_BUFFER_SIZE; - while (rc != Z_STREAM_END) - { - rc = deflate(&_zstr, Z_FINISH); - if (rc != Z_OK && rc != Z_STREAM_END) throw IOException(zError(rc)); - _pOstr->write(_buffer, DEFLATE_BUFFER_SIZE - _zstr.avail_out); - if (!_pOstr->good()) throw IOException(zError(rc)); - _zstr.next_out = (unsigned char*) _buffer; - _zstr.avail_out = DEFLATE_BUFFER_SIZE; - } - rc = deflateEnd(&_zstr); - if (rc != Z_OK) throw IOException(zError(rc)); - } - _pOstr = 0; - } - return 0; -} - - -int DeflatingStreamBuf::readFromDevice(char* buffer, std::streamsize length) -{ - if (!_pIstr) return 0; - if (_zstr.avail_in == 0 && !_eof) - { - int n = 0; - if (_pIstr->good()) - { - _pIstr->read(_buffer, DEFLATE_BUFFER_SIZE); - n = _pIstr->gcount(); - } - if (n > 0) - { - _zstr.next_in = (unsigned char*) _buffer; - _zstr.avail_in = n; - } - else - { - _zstr.next_in = 0; - _zstr.avail_in = 0; - _eof = true; - } - } - _zstr.next_out = (unsigned char*) buffer; - _zstr.avail_out = length; - for (;;) - { - int rc = deflate(&_zstr, _eof ? Z_FINISH : Z_NO_FLUSH); - if (_eof && rc == Z_STREAM_END) - { - rc = deflateEnd(&_zstr); - if (rc != Z_OK) throw IOException(zError(rc)); - _pIstr = 0; - return length - _zstr.avail_out; - } - if (rc != Z_OK) throw IOException(zError(rc)); - if (_zstr.avail_out == 0) - { - return length; - } - if (_zstr.avail_in == 0) - { - int n = 0; - if (_pIstr->good()) - { - _pIstr->read(_buffer, DEFLATE_BUFFER_SIZE); - n = _pIstr->gcount(); - } - if (n > 0) - { - _zstr.next_in = (unsigned char*) _buffer; - _zstr.avail_in = n; - } - else - { - _zstr.next_in = 0; - _zstr.avail_in = 0; - _eof = true; - } - } - } -} - - -int DeflatingStreamBuf::writeToDevice(const char* buffer, std::streamsize length) -{ - if (length == 0 || !_pOstr) return 0; - - _zstr.next_in = (unsigned char*) buffer; - _zstr.avail_in = length; - _zstr.next_out = (unsigned char*) _buffer; - _zstr.avail_out = DEFLATE_BUFFER_SIZE; - for (;;) - { - int rc = deflate(&_zstr, Z_NO_FLUSH); - if (rc != Z_OK) throw IOException(zError(rc)); - if (_zstr.avail_out == 0) - { - _pOstr->write(_buffer, DEFLATE_BUFFER_SIZE); - if (!_pOstr->good()) throw IOException(zError(rc)); - _zstr.next_out = (unsigned char*) _buffer; - _zstr.avail_out = DEFLATE_BUFFER_SIZE; - } - if (_zstr.avail_in == 0) - { - _pOstr->write(_buffer, DEFLATE_BUFFER_SIZE - _zstr.avail_out); - if (!_pOstr->good()) throw IOException(zError(rc)); - _zstr.next_out = (unsigned char*) _buffer; - _zstr.avail_out = DEFLATE_BUFFER_SIZE; - break; - } - } - return length; -} - - -DeflatingIOS::DeflatingIOS(std::ostream& ostr, DeflatingStreamBuf::StreamType type, int level): - _buf(ostr, type, level) -{ - poco_ios_init(&_buf); -} - - -DeflatingIOS::DeflatingIOS(std::istream& istr, DeflatingStreamBuf::StreamType type, int level): - _buf(istr, type, level) -{ - poco_ios_init(&_buf); -} - - -DeflatingIOS::~DeflatingIOS() -{ -} - - -DeflatingStreamBuf* DeflatingIOS::rdbuf() -{ - return &_buf; -} - - -DeflatingOutputStream::DeflatingOutputStream(std::ostream& ostr, DeflatingStreamBuf::StreamType type, int level): - DeflatingIOS(ostr, type, level), - std::ostream(&_buf) -{ -} - - -DeflatingOutputStream::~DeflatingOutputStream() -{ -} - - -int DeflatingOutputStream::close() -{ - return _buf.close(); -} - - -DeflatingInputStream::DeflatingInputStream(std::istream& istr, DeflatingStreamBuf::StreamType type, int level): - DeflatingIOS(istr, type, level), - std::istream(&_buf) -{ -} - - -DeflatingInputStream::~DeflatingInputStream() -{ -} - - -} // namespace Poco +// +// DeflatingStream.cpp +// +// $Id: //poco/1.2/Foundation/src/DeflatingStream.cpp#1 $ +// +// Library: Foundation +// Package: Streams +// Module: ZLibStream +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/DeflatingStream.h" +#include "Poco/Exception.h" + + +namespace Poco { + + +DeflatingStreamBuf::DeflatingStreamBuf(std::istream& istr, StreamType type, int level): + BufferedStreamBuf(STREAM_BUFFER_SIZE, std::ios::in), + _pIstr(&istr), + _pOstr(0), + _eof(false) +{ + _zstr.zalloc = Z_NULL; + _zstr.zfree = Z_NULL; + _zstr.opaque = Z_NULL; + _zstr.next_in = 0; + _zstr.avail_in = 0; + _zstr.next_out = 0; + _zstr.avail_out = 0; + + int rc = deflateInit2(&_zstr, level, Z_DEFLATED, 15 + (type == STREAM_GZIP ? 16 : 0), 8, Z_DEFAULT_STRATEGY); + if (rc != Z_OK) throw IOException(zError(rc)); + + _buffer = new char[DEFLATE_BUFFER_SIZE]; +} + + +DeflatingStreamBuf::DeflatingStreamBuf(std::ostream& ostr, StreamType type, int level): + BufferedStreamBuf(STREAM_BUFFER_SIZE, std::ios::out), + _pIstr(0), + _pOstr(&ostr), + _eof(false) +{ + _zstr.zalloc = Z_NULL; + _zstr.zfree = Z_NULL; + _zstr.opaque = Z_NULL; + _zstr.next_in = 0; + _zstr.avail_in = 0; + _zstr.next_out = 0; + _zstr.avail_out = 0; + + int rc = deflateInit2(&_zstr, level, Z_DEFLATED, 15 + (type == STREAM_GZIP ? 16 : 0), 8, Z_DEFAULT_STRATEGY); + if (rc != Z_OK) throw IOException(zError(rc)); + + _buffer = new char[DEFLATE_BUFFER_SIZE]; +} + + +DeflatingStreamBuf::~DeflatingStreamBuf() +{ + try + { + close(); + } + catch (...) + { + } + delete [] _buffer; +} + + +int DeflatingStreamBuf::close() +{ + sync(); + if (_pIstr) + { + int rc = deflateEnd(&_zstr); + if (rc != Z_OK) throw IOException(zError(rc)); + _pIstr = 0; + } + else if (_pOstr) + { + if (_zstr.next_out) + { + int rc = deflate(&_zstr, Z_FINISH); + if (rc != Z_OK && rc != Z_STREAM_END) throw IOException(zError(rc)); + _pOstr->write(_buffer, DEFLATE_BUFFER_SIZE - _zstr.avail_out); + if (!_pOstr->good()) throw IOException(zError(rc)); + _zstr.next_out = (unsigned char*) _buffer; + _zstr.avail_out = DEFLATE_BUFFER_SIZE; + while (rc != Z_STREAM_END) + { + rc = deflate(&_zstr, Z_FINISH); + if (rc != Z_OK && rc != Z_STREAM_END) throw IOException(zError(rc)); + _pOstr->write(_buffer, DEFLATE_BUFFER_SIZE - _zstr.avail_out); + if (!_pOstr->good()) throw IOException(zError(rc)); + _zstr.next_out = (unsigned char*) _buffer; + _zstr.avail_out = DEFLATE_BUFFER_SIZE; + } + rc = deflateEnd(&_zstr); + if (rc != Z_OK) throw IOException(zError(rc)); + } + _pOstr = 0; + } + return 0; +} + + +int DeflatingStreamBuf::readFromDevice(char* buffer, std::streamsize length) +{ + if (!_pIstr) return 0; + if (_zstr.avail_in == 0 && !_eof) + { + int n = 0; + if (_pIstr->good()) + { + _pIstr->read(_buffer, DEFLATE_BUFFER_SIZE); + n = _pIstr->gcount(); + } + if (n > 0) + { + _zstr.next_in = (unsigned char*) _buffer; + _zstr.avail_in = n; + } + else + { + _zstr.next_in = 0; + _zstr.avail_in = 0; + _eof = true; + } + } + _zstr.next_out = (unsigned char*) buffer; + _zstr.avail_out = length; + for (;;) + { + int rc = deflate(&_zstr, _eof ? Z_FINISH : Z_NO_FLUSH); + if (_eof && rc == Z_STREAM_END) + { + rc = deflateEnd(&_zstr); + if (rc != Z_OK) throw IOException(zError(rc)); + _pIstr = 0; + return length - _zstr.avail_out; + } + if (rc != Z_OK) throw IOException(zError(rc)); + if (_zstr.avail_out == 0) + { + return length; + } + if (_zstr.avail_in == 0) + { + int n = 0; + if (_pIstr->good()) + { + _pIstr->read(_buffer, DEFLATE_BUFFER_SIZE); + n = _pIstr->gcount(); + } + if (n > 0) + { + _zstr.next_in = (unsigned char*) _buffer; + _zstr.avail_in = n; + } + else + { + _zstr.next_in = 0; + _zstr.avail_in = 0; + _eof = true; + } + } + } +} + + +int DeflatingStreamBuf::writeToDevice(const char* buffer, std::streamsize length) +{ + if (length == 0 || !_pOstr) return 0; + + _zstr.next_in = (unsigned char*) buffer; + _zstr.avail_in = length; + _zstr.next_out = (unsigned char*) _buffer; + _zstr.avail_out = DEFLATE_BUFFER_SIZE; + for (;;) + { + int rc = deflate(&_zstr, Z_NO_FLUSH); + if (rc != Z_OK) throw IOException(zError(rc)); + if (_zstr.avail_out == 0) + { + _pOstr->write(_buffer, DEFLATE_BUFFER_SIZE); + if (!_pOstr->good()) throw IOException(zError(rc)); + _zstr.next_out = (unsigned char*) _buffer; + _zstr.avail_out = DEFLATE_BUFFER_SIZE; + } + if (_zstr.avail_in == 0) + { + _pOstr->write(_buffer, DEFLATE_BUFFER_SIZE - _zstr.avail_out); + if (!_pOstr->good()) throw IOException(zError(rc)); + _zstr.next_out = (unsigned char*) _buffer; + _zstr.avail_out = DEFLATE_BUFFER_SIZE; + break; + } + } + return length; +} + + +DeflatingIOS::DeflatingIOS(std::ostream& ostr, DeflatingStreamBuf::StreamType type, int level): + _buf(ostr, type, level) +{ + poco_ios_init(&_buf); +} + + +DeflatingIOS::DeflatingIOS(std::istream& istr, DeflatingStreamBuf::StreamType type, int level): + _buf(istr, type, level) +{ + poco_ios_init(&_buf); +} + + +DeflatingIOS::~DeflatingIOS() +{ +} + + +DeflatingStreamBuf* DeflatingIOS::rdbuf() +{ + return &_buf; +} + + +DeflatingOutputStream::DeflatingOutputStream(std::ostream& ostr, DeflatingStreamBuf::StreamType type, int level): + DeflatingIOS(ostr, type, level), + std::ostream(&_buf) +{ +} + + +DeflatingOutputStream::~DeflatingOutputStream() +{ +} + + +int DeflatingOutputStream::close() +{ + return _buf.close(); +} + + +DeflatingInputStream::DeflatingInputStream(std::istream& istr, DeflatingStreamBuf::StreamType type, int level): + DeflatingIOS(istr, type, level), + std::istream(&_buf) +{ +} + + +DeflatingInputStream::~DeflatingInputStream() +{ +} + + +} // namespace Poco diff --git a/Foundation/src/DigestEngine.cpp b/Foundation/src/DigestEngine.cpp index 91c881461..f5f93b657 100644 --- a/Foundation/src/DigestEngine.cpp +++ b/Foundation/src/DigestEngine.cpp @@ -1,68 +1,68 @@ -// -// DigestEngine.cpp -// -// $Id: //poco/1.2/Foundation/src/DigestEngine.cpp#1 $ -// -// Library: Foundation -// Package: Crypt -// Module: DigestEngine -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/DigestEngine.h" - - -namespace Poco { - - -DigestEngine::DigestEngine() -{ -} - - -DigestEngine::~DigestEngine() -{ -} - - -std::string DigestEngine::digestToHex(const Digest& bytes) -{ - static const char digits[] = "0123456789abcdef"; - std::string result; - result.reserve(bytes.size()*2); - for (Digest::const_iterator it = bytes.begin(); it != bytes.end(); ++it) - { - unsigned char c = *it; - result += digits[(c >> 4) & 0xF]; - result += digits[c & 0xF]; - } - return result; -} - - -} // namespace Poco +// +// DigestEngine.cpp +// +// $Id: //poco/1.2/Foundation/src/DigestEngine.cpp#1 $ +// +// Library: Foundation +// Package: Crypt +// Module: DigestEngine +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/DigestEngine.h" + + +namespace Poco { + + +DigestEngine::DigestEngine() +{ +} + + +DigestEngine::~DigestEngine() +{ +} + + +std::string DigestEngine::digestToHex(const Digest& bytes) +{ + static const char digits[] = "0123456789abcdef"; + std::string result; + result.reserve(bytes.size()*2); + for (Digest::const_iterator it = bytes.begin(); it != bytes.end(); ++it) + { + unsigned char c = *it; + result += digits[(c >> 4) & 0xF]; + result += digits[c & 0xF]; + } + return result; +} + + +} // namespace Poco diff --git a/Foundation/src/DigestStream.cpp b/Foundation/src/DigestStream.cpp index 4fe3092e4..ada25f51a 100644 --- a/Foundation/src/DigestStream.cpp +++ b/Foundation/src/DigestStream.cpp @@ -1,172 +1,172 @@ -// -// DigestStream.cpp -// -// $Id: //poco/1.2/Foundation/src/DigestStream.cpp#1 $ -// -// Library: Foundation -// Package: Crypt -// Module: DigestStream -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/DigestStream.h" - - -namespace Poco { - - -const int DigestBuf::BUFFER_SIZE = 256; - - -DigestBuf::DigestBuf(DigestEngine& eng): - BufferedStreamBuf(BUFFER_SIZE, std::ios::out), - _eng(eng), - _pIstr(0), - _pOstr(0) -{ -} - - -DigestBuf::DigestBuf(DigestEngine& eng, std::istream& istr): - BufferedStreamBuf(BUFFER_SIZE, std::ios::in), - _eng(eng), - _pIstr(&istr), - _pOstr(0) -{ -} - - -DigestBuf::DigestBuf(DigestEngine& eng, std::ostream& ostr): - BufferedStreamBuf(BUFFER_SIZE, std::ios::in), - _eng(eng), - _pIstr(0), - _pOstr(&ostr) -{ -} - - -DigestBuf::~DigestBuf() -{ -} - - -int DigestBuf::readFromDevice(char* buffer, std::streamsize length) -{ - if (_pIstr && _pIstr->good()) - { - _pIstr->read(buffer, length); - std::streamsize n = _pIstr->gcount(); - if (n > 0) _eng.update(buffer, n); - return n; - } - return -1; -} - - -int DigestBuf::writeToDevice(const char* buffer, std::streamsize length) -{ - _eng.update(buffer, (unsigned) length); - if (_pOstr) _pOstr->write(buffer, length); - return length; -} - - -void DigestBuf::close() -{ - sync(); - if (_pOstr) _pOstr->flush(); -} - - -DigestIOS::DigestIOS(DigestEngine& eng): _buf(eng) -{ - poco_ios_init(&_buf); -} - - -DigestIOS::DigestIOS(DigestEngine& eng, std::istream& istr): _buf(eng, istr) -{ - poco_ios_init(&_buf); -} - - -DigestIOS::DigestIOS(DigestEngine& eng, std::ostream& ostr): _buf(eng, ostr) -{ - poco_ios_init(&_buf); -} - - -DigestIOS::~DigestIOS() -{ -} - - -DigestBuf* DigestIOS::rdbuf() -{ - return &_buf; -} - - -DigestInputStream::DigestInputStream(DigestEngine& eng, std::istream& istr): - DigestIOS(eng, istr), - std::istream(&_buf) -{ -} - - -DigestInputStream::~DigestInputStream() -{ -} - - -DigestOutputStream::DigestOutputStream(DigestEngine& eng): - DigestIOS(eng), - std::ostream(&_buf) -{ -} - - -DigestOutputStream::DigestOutputStream(DigestEngine& eng, std::ostream& ostr): - DigestIOS(eng, ostr), - std::ostream(&_buf) -{ -} - - -DigestOutputStream::~DigestOutputStream() -{ -} - - -void DigestOutputStream::close() -{ - _buf.close(); -} - - -} // namespace Poco +// +// DigestStream.cpp +// +// $Id: //poco/1.2/Foundation/src/DigestStream.cpp#1 $ +// +// Library: Foundation +// Package: Crypt +// Module: DigestStream +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/DigestStream.h" + + +namespace Poco { + + +const int DigestBuf::BUFFER_SIZE = 256; + + +DigestBuf::DigestBuf(DigestEngine& eng): + BufferedStreamBuf(BUFFER_SIZE, std::ios::out), + _eng(eng), + _pIstr(0), + _pOstr(0) +{ +} + + +DigestBuf::DigestBuf(DigestEngine& eng, std::istream& istr): + BufferedStreamBuf(BUFFER_SIZE, std::ios::in), + _eng(eng), + _pIstr(&istr), + _pOstr(0) +{ +} + + +DigestBuf::DigestBuf(DigestEngine& eng, std::ostream& ostr): + BufferedStreamBuf(BUFFER_SIZE, std::ios::in), + _eng(eng), + _pIstr(0), + _pOstr(&ostr) +{ +} + + +DigestBuf::~DigestBuf() +{ +} + + +int DigestBuf::readFromDevice(char* buffer, std::streamsize length) +{ + if (_pIstr && _pIstr->good()) + { + _pIstr->read(buffer, length); + std::streamsize n = _pIstr->gcount(); + if (n > 0) _eng.update(buffer, n); + return n; + } + return -1; +} + + +int DigestBuf::writeToDevice(const char* buffer, std::streamsize length) +{ + _eng.update(buffer, (unsigned) length); + if (_pOstr) _pOstr->write(buffer, length); + return length; +} + + +void DigestBuf::close() +{ + sync(); + if (_pOstr) _pOstr->flush(); +} + + +DigestIOS::DigestIOS(DigestEngine& eng): _buf(eng) +{ + poco_ios_init(&_buf); +} + + +DigestIOS::DigestIOS(DigestEngine& eng, std::istream& istr): _buf(eng, istr) +{ + poco_ios_init(&_buf); +} + + +DigestIOS::DigestIOS(DigestEngine& eng, std::ostream& ostr): _buf(eng, ostr) +{ + poco_ios_init(&_buf); +} + + +DigestIOS::~DigestIOS() +{ +} + + +DigestBuf* DigestIOS::rdbuf() +{ + return &_buf; +} + + +DigestInputStream::DigestInputStream(DigestEngine& eng, std::istream& istr): + DigestIOS(eng, istr), + std::istream(&_buf) +{ +} + + +DigestInputStream::~DigestInputStream() +{ +} + + +DigestOutputStream::DigestOutputStream(DigestEngine& eng): + DigestIOS(eng), + std::ostream(&_buf) +{ +} + + +DigestOutputStream::DigestOutputStream(DigestEngine& eng, std::ostream& ostr): + DigestIOS(eng, ostr), + std::ostream(&_buf) +{ +} + + +DigestOutputStream::~DigestOutputStream() +{ +} + + +void DigestOutputStream::close() +{ + _buf.close(); +} + + +} // namespace Poco diff --git a/Foundation/src/DirectoryIterator.cpp b/Foundation/src/DirectoryIterator.cpp index 7ebc831c7..413c46e1d 100644 --- a/Foundation/src/DirectoryIterator.cpp +++ b/Foundation/src/DirectoryIterator.cpp @@ -1,171 +1,171 @@ -// -// DirectoryIterator.cpp -// -// $Id: //poco/1.2/Foundation/src/DirectoryIterator.cpp#1 $ -// -// Library: Foundation -// Package: Filesystem -// Module: DirectoryIterator -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/DirectoryIterator.h" - - -#if defined(POCO_OS_FAMILY_WINDOWS) && defined(POCO_WIN32_UTF8) -#include "DirectoryIterator_WIN32U.cpp" -#elif defined(POCO_OS_FAMILY_WINDOWS) -#include "DirectoryIterator_WIN32.cpp" -#elif defined(POCO_OS_FAMILY_UNIX) -#include "DirectoryIterator_UNIX.cpp" -#else -#include "DirectoryIterator_VMS.cpp" -#endif - - -namespace Poco { - - -DirectoryIterator::DirectoryIterator(): _pImpl(0) -{ -} - - -DirectoryIterator::DirectoryIterator(const std::string& path): _path(path), _pImpl(new DirectoryIteratorImpl(path)) -{ - _path.makeDirectory(); - _path.setFileName(_pImpl->get()); - _file = _path; -} - - -DirectoryIterator::DirectoryIterator(const DirectoryIterator& iterator): _path(iterator._path), _pImpl(iterator._pImpl) -{ - _path.makeDirectory(); - if (_pImpl) - { - _pImpl->duplicate(); - _path.setFileName(_pImpl->get()); - _file = _path; - } -} - - -DirectoryIterator::DirectoryIterator(const File& file): _path(file.path()), _pImpl(new DirectoryIteratorImpl(file.path())) -{ - _path.makeDirectory(); - _path.setFileName(_pImpl->get()); - _file = _path; -} - - -DirectoryIterator::DirectoryIterator(const Path& path): _path(path), _pImpl(new DirectoryIteratorImpl(path.toString())) -{ - _path.makeDirectory(); - _path.setFileName(_pImpl->get()); - _file = _path; -} - - -DirectoryIterator::~DirectoryIterator() -{ - if (_pImpl) _pImpl->release(); -} - - -DirectoryIterator& DirectoryIterator::operator = (const DirectoryIterator& it) -{ - if (_pImpl) _pImpl->release(); - _pImpl = it._pImpl; - if (_pImpl) - { - _pImpl->duplicate(); - _path = it._path; - _file = _path; - } - return *this; -} - - -DirectoryIterator& DirectoryIterator::operator = (const File& file) -{ - if (_pImpl) _pImpl->release(); - _pImpl = new DirectoryIteratorImpl(file.path()); - _path.parseDirectory(file.path()); - _path.setFileName(_pImpl->get()); - _file = _path; - return *this; -} - - -DirectoryIterator& DirectoryIterator::operator = (const Path& path) -{ - if (_pImpl) _pImpl->release(); - _pImpl = new DirectoryIteratorImpl(path.toString()); - _path = path; - _path.makeDirectory(); - _path.setFileName(_pImpl->get()); - _file = _path; - return *this; -} - - -DirectoryIterator& DirectoryIterator::operator = (const std::string& path) -{ - if (_pImpl) _pImpl->release(); - _pImpl = new DirectoryIteratorImpl(path); - _path.parseDirectory(path); - _path.setFileName(_pImpl->get()); - _file = _path; - return *this; -} - - -DirectoryIterator& DirectoryIterator::operator ++ () -{ - if (_pImpl) - { - _path.setFileName(_pImpl->next()); - _file = _path; - } - return *this; -} - - -DirectoryIterator DirectoryIterator::operator ++ (int dummy) -{ - if (_pImpl) - { - _path.setFileName(_pImpl->next()); - _file = _path; - } - return *this; -} - - -} // namespace Poco +// +// DirectoryIterator.cpp +// +// $Id: //poco/1.2/Foundation/src/DirectoryIterator.cpp#1 $ +// +// Library: Foundation +// Package: Filesystem +// Module: DirectoryIterator +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/DirectoryIterator.h" + + +#if defined(POCO_OS_FAMILY_WINDOWS) && defined(POCO_WIN32_UTF8) +#include "DirectoryIterator_WIN32U.cpp" +#elif defined(POCO_OS_FAMILY_WINDOWS) +#include "DirectoryIterator_WIN32.cpp" +#elif defined(POCO_OS_FAMILY_UNIX) +#include "DirectoryIterator_UNIX.cpp" +#else +#include "DirectoryIterator_VMS.cpp" +#endif + + +namespace Poco { + + +DirectoryIterator::DirectoryIterator(): _pImpl(0) +{ +} + + +DirectoryIterator::DirectoryIterator(const std::string& path): _path(path), _pImpl(new DirectoryIteratorImpl(path)) +{ + _path.makeDirectory(); + _path.setFileName(_pImpl->get()); + _file = _path; +} + + +DirectoryIterator::DirectoryIterator(const DirectoryIterator& iterator): _path(iterator._path), _pImpl(iterator._pImpl) +{ + _path.makeDirectory(); + if (_pImpl) + { + _pImpl->duplicate(); + _path.setFileName(_pImpl->get()); + _file = _path; + } +} + + +DirectoryIterator::DirectoryIterator(const File& file): _path(file.path()), _pImpl(new DirectoryIteratorImpl(file.path())) +{ + _path.makeDirectory(); + _path.setFileName(_pImpl->get()); + _file = _path; +} + + +DirectoryIterator::DirectoryIterator(const Path& path): _path(path), _pImpl(new DirectoryIteratorImpl(path.toString())) +{ + _path.makeDirectory(); + _path.setFileName(_pImpl->get()); + _file = _path; +} + + +DirectoryIterator::~DirectoryIterator() +{ + if (_pImpl) _pImpl->release(); +} + + +DirectoryIterator& DirectoryIterator::operator = (const DirectoryIterator& it) +{ + if (_pImpl) _pImpl->release(); + _pImpl = it._pImpl; + if (_pImpl) + { + _pImpl->duplicate(); + _path = it._path; + _file = _path; + } + return *this; +} + + +DirectoryIterator& DirectoryIterator::operator = (const File& file) +{ + if (_pImpl) _pImpl->release(); + _pImpl = new DirectoryIteratorImpl(file.path()); + _path.parseDirectory(file.path()); + _path.setFileName(_pImpl->get()); + _file = _path; + return *this; +} + + +DirectoryIterator& DirectoryIterator::operator = (const Path& path) +{ + if (_pImpl) _pImpl->release(); + _pImpl = new DirectoryIteratorImpl(path.toString()); + _path = path; + _path.makeDirectory(); + _path.setFileName(_pImpl->get()); + _file = _path; + return *this; +} + + +DirectoryIterator& DirectoryIterator::operator = (const std::string& path) +{ + if (_pImpl) _pImpl->release(); + _pImpl = new DirectoryIteratorImpl(path); + _path.parseDirectory(path); + _path.setFileName(_pImpl->get()); + _file = _path; + return *this; +} + + +DirectoryIterator& DirectoryIterator::operator ++ () +{ + if (_pImpl) + { + _path.setFileName(_pImpl->next()); + _file = _path; + } + return *this; +} + + +DirectoryIterator DirectoryIterator::operator ++ (int dummy) +{ + if (_pImpl) + { + _path.setFileName(_pImpl->next()); + _file = _path; + } + return *this; +} + + +} // namespace Poco diff --git a/Foundation/src/DirectoryIterator_UNIX.cpp b/Foundation/src/DirectoryIterator_UNIX.cpp index b50f27abc..1853959aa 100644 --- a/Foundation/src/DirectoryIterator_UNIX.cpp +++ b/Foundation/src/DirectoryIterator_UNIX.cpp @@ -1,78 +1,78 @@ -// -// DirectoryIterator_UNIX.cpp -// -// $Id: //poco/1.2/Foundation/src/DirectoryIterator_UNIX.cpp#1 $ -// -// Library: Foundation -// Package: Filesystem -// Module: DirectoryIterator -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/DirectoryIterator_UNIX.h" -#include "Poco/File_UNIX.h" -#include "Poco/Path.h" - - -namespace Poco { - - -DirectoryIteratorImpl::DirectoryIteratorImpl(const std::string& path): _pDir(0), _rc(1) -{ - Path p(path); - p.makeFile(); - - _pDir = opendir(p.toString().c_str()); - if (!_pDir) FileImpl::handleError(path); - - next(); -} - - -DirectoryIteratorImpl::~DirectoryIteratorImpl() -{ - if (_pDir) closedir(_pDir); -} - - -const std::string& DirectoryIteratorImpl::next() -{ - do - { - struct dirent* pEntry = readdir(_pDir); - if (pEntry) - _current = pEntry->d_name; - else - _current.clear(); - } - while (_current == "." || _current == ".."); - return _current; -} - - -} // namespace Poco +// +// DirectoryIterator_UNIX.cpp +// +// $Id: //poco/1.2/Foundation/src/DirectoryIterator_UNIX.cpp#1 $ +// +// Library: Foundation +// Package: Filesystem +// Module: DirectoryIterator +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/DirectoryIterator_UNIX.h" +#include "Poco/File_UNIX.h" +#include "Poco/Path.h" + + +namespace Poco { + + +DirectoryIteratorImpl::DirectoryIteratorImpl(const std::string& path): _pDir(0), _rc(1) +{ + Path p(path); + p.makeFile(); + + _pDir = opendir(p.toString().c_str()); + if (!_pDir) FileImpl::handleError(path); + + next(); +} + + +DirectoryIteratorImpl::~DirectoryIteratorImpl() +{ + if (_pDir) closedir(_pDir); +} + + +const std::string& DirectoryIteratorImpl::next() +{ + do + { + struct dirent* pEntry = readdir(_pDir); + if (pEntry) + _current = pEntry->d_name; + else + _current.clear(); + } + while (_current == "." || _current == ".."); + return _current; +} + + +} // namespace Poco diff --git a/Foundation/src/DirectoryIterator_VMS.cpp b/Foundation/src/DirectoryIterator_VMS.cpp index a4d9176ae..c9f47bcfd 100644 --- a/Foundation/src/DirectoryIterator_VMS.cpp +++ b/Foundation/src/DirectoryIterator_VMS.cpp @@ -1,87 +1,87 @@ -// -// DirectoryIterator_VMS.cpp -// -// $Id: //poco/1.2/Foundation/src/DirectoryIterator_VMS.cpp#1 $ -// -// Library: Foundation -// Package: Filesystem -// Module: DirectoryIterator -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/DirectoryIterator_VMS.h" -#include "Poco/Path.h" -#include "Poco/Exception.h" -#include -#include -#include -#include - - -namespace Poco { - - -DirectoryIteratorImpl::DirectoryIteratorImpl(const std::string& path): _rc(1) -{ - Path p(path); - p.makeDirectory(); - _search = p.toString(); - _search.append("*.*;*"); - - _fab = cc$rms_fab; - _fab.fab$l_fna = (char*) _search.c_str(); - _fab.fab$b_fns = _search.size(); - _fab.fab$l_nam = &_nam; - - _nam = cc$rms_nam; - _nam.nam$l_esa = _spec; - _nam.nam$b_ess = sizeof(_spec); - - if (sys$parse(&_fab) & 1) - throw OpenFileException(path); - - next(); -} - - -DirectoryIteratorImpl::~DirectoryIteratorImpl() -{ -} - - -const std::string& DirectoryIteratorImpl::next() -{ - if (sys$search(&_fab) & 1) - _current.clear(); - else - _current.assign(_fab.fab$l_nam->nam$l_name, _fab.fab$l_nam->nam$b_name + _fab.fab$l_nam->nam$b_type); - return _current; -} - - -} // namespace Poco +// +// DirectoryIterator_VMS.cpp +// +// $Id: //poco/1.2/Foundation/src/DirectoryIterator_VMS.cpp#1 $ +// +// Library: Foundation +// Package: Filesystem +// Module: DirectoryIterator +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/DirectoryIterator_VMS.h" +#include "Poco/Path.h" +#include "Poco/Exception.h" +#include +#include +#include +#include + + +namespace Poco { + + +DirectoryIteratorImpl::DirectoryIteratorImpl(const std::string& path): _rc(1) +{ + Path p(path); + p.makeDirectory(); + _search = p.toString(); + _search.append("*.*;*"); + + _fab = cc$rms_fab; + _fab.fab$l_fna = (char*) _search.c_str(); + _fab.fab$b_fns = _search.size(); + _fab.fab$l_nam = &_nam; + + _nam = cc$rms_nam; + _nam.nam$l_esa = _spec; + _nam.nam$b_ess = sizeof(_spec); + + if (sys$parse(&_fab) & 1) + throw OpenFileException(path); + + next(); +} + + +DirectoryIteratorImpl::~DirectoryIteratorImpl() +{ +} + + +const std::string& DirectoryIteratorImpl::next() +{ + if (sys$search(&_fab) & 1) + _current.clear(); + else + _current.assign(_fab.fab$l_nam->nam$l_name, _fab.fab$l_nam->nam$b_name + _fab.fab$l_nam->nam$b_type); + return _current; +} + + +} // namespace Poco diff --git a/Foundation/src/DirectoryIterator_WIN32.cpp b/Foundation/src/DirectoryIterator_WIN32.cpp index 863f78ca6..b1eaec2bf 100644 --- a/Foundation/src/DirectoryIterator_WIN32.cpp +++ b/Foundation/src/DirectoryIterator_WIN32.cpp @@ -1,85 +1,85 @@ -// -// DirectoryIterator_WIN32.cpp -// -// $Id: //poco/1.2/Foundation/src/DirectoryIterator_WIN32.cpp#1 $ -// -// Library: Foundation -// Package: Filesystem -// Module: DirectoryIterator -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/DirectoryIterator_WIN32.h" -#include "Poco/File_WIN32.h" -#include "Poco/Path.h" - - -namespace Poco { - - -DirectoryIteratorImpl::DirectoryIteratorImpl(const std::string& path): _fh(INVALID_HANDLE_VALUE), _rc(1) -{ - Path p(path); - p.makeDirectory(); - std::string findPath = p.toString(); - findPath.append("*"); - - _fh = FindFirstFile(findPath.c_str(), &_fd); - if (_fh == INVALID_HANDLE_VALUE) - { - if (GetLastError() != ERROR_NO_MORE_FILES) - FileImpl::handleError(path); - } - _current = _fd.cFileName; - if (_current == "." || _current == "..") - next(); -} - - -DirectoryIteratorImpl::~DirectoryIteratorImpl() -{ - if (_fh != INVALID_HANDLE_VALUE) - FindClose(_fh); -} - - -const std::string& DirectoryIteratorImpl::next() -{ - do - { - if (FindNextFile(_fh, &_fd) != 0) - _current = _fd.cFileName; - else - _current.clear(); - } - while (_current == "." || _current == ".."); - return _current; -} - - -} // namespace Poco +// +// DirectoryIterator_WIN32.cpp +// +// $Id: //poco/1.2/Foundation/src/DirectoryIterator_WIN32.cpp#1 $ +// +// Library: Foundation +// Package: Filesystem +// Module: DirectoryIterator +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/DirectoryIterator_WIN32.h" +#include "Poco/File_WIN32.h" +#include "Poco/Path.h" + + +namespace Poco { + + +DirectoryIteratorImpl::DirectoryIteratorImpl(const std::string& path): _fh(INVALID_HANDLE_VALUE), _rc(1) +{ + Path p(path); + p.makeDirectory(); + std::string findPath = p.toString(); + findPath.append("*"); + + _fh = FindFirstFile(findPath.c_str(), &_fd); + if (_fh == INVALID_HANDLE_VALUE) + { + if (GetLastError() != ERROR_NO_MORE_FILES) + FileImpl::handleError(path); + } + _current = _fd.cFileName; + if (_current == "." || _current == "..") + next(); +} + + +DirectoryIteratorImpl::~DirectoryIteratorImpl() +{ + if (_fh != INVALID_HANDLE_VALUE) + FindClose(_fh); +} + + +const std::string& DirectoryIteratorImpl::next() +{ + do + { + if (FindNextFile(_fh, &_fd) != 0) + _current = _fd.cFileName; + else + _current.clear(); + } + while (_current == "." || _current == ".."); + return _current; +} + + +} // namespace Poco diff --git a/Foundation/src/DirectoryIterator_WIN32U.cpp b/Foundation/src/DirectoryIterator_WIN32U.cpp index 03b5063e4..f848e6226 100644 --- a/Foundation/src/DirectoryIterator_WIN32U.cpp +++ b/Foundation/src/DirectoryIterator_WIN32U.cpp @@ -1,90 +1,90 @@ -// -// DirectoryIterator_WIN32U.cpp -// -// $Id: //poco/1.2/Foundation/src/DirectoryIterator_WIN32U.cpp#1 $ -// -// Library: Foundation -// Package: Filesystem -// Module: DirectoryIterator -// -// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/DirectoryIterator_WIN32U.h" -#include "Poco/File_WIN32U.h" -#include "Poco/Path.h" -#include "Poco/UnicodeConverter.h" -#include - - -namespace Poco { - - -DirectoryIteratorImpl::DirectoryIteratorImpl(const std::string& path): _fh(INVALID_HANDLE_VALUE), _rc(1) -{ - Path p(path); - p.makeDirectory(); - std::string findPath = p.toString(); - findPath.append("*"); - std::wstring uFindPath; - UnicodeConverter::toUTF16(findPath, uFindPath); - - _fh = FindFirstFileW(uFindPath.c_str(), &_fd); - if (_fh == INVALID_HANDLE_VALUE) - { - if (GetLastError() != ERROR_NO_MORE_FILES) - FileImpl::handleError(path); - } - UnicodeConverter::toUTF8(_fd.cFileName, _current); - if (_current == "." || _current == "..") - next(); -} - - -DirectoryIteratorImpl::~DirectoryIteratorImpl() -{ - if (_fh != INVALID_HANDLE_VALUE) - FindClose(_fh); -} - - -const std::string& DirectoryIteratorImpl::next() -{ - do - { - _current.clear(); - if (FindNextFileW(_fh, &_fd) != 0) - { - UnicodeConverter::toUTF8(_fd.cFileName, _current); - } - } - while (_current == "." || _current == ".."); - return _current; -} - - -} // namespace Poco +// +// DirectoryIterator_WIN32U.cpp +// +// $Id: //poco/1.2/Foundation/src/DirectoryIterator_WIN32U.cpp#1 $ +// +// Library: Foundation +// Package: Filesystem +// Module: DirectoryIterator +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/DirectoryIterator_WIN32U.h" +#include "Poco/File_WIN32U.h" +#include "Poco/Path.h" +#include "Poco/UnicodeConverter.h" +#include + + +namespace Poco { + + +DirectoryIteratorImpl::DirectoryIteratorImpl(const std::string& path): _fh(INVALID_HANDLE_VALUE), _rc(1) +{ + Path p(path); + p.makeDirectory(); + std::string findPath = p.toString(); + findPath.append("*"); + std::wstring uFindPath; + UnicodeConverter::toUTF16(findPath, uFindPath); + + _fh = FindFirstFileW(uFindPath.c_str(), &_fd); + if (_fh == INVALID_HANDLE_VALUE) + { + if (GetLastError() != ERROR_NO_MORE_FILES) + FileImpl::handleError(path); + } + UnicodeConverter::toUTF8(_fd.cFileName, _current); + if (_current == "." || _current == "..") + next(); +} + + +DirectoryIteratorImpl::~DirectoryIteratorImpl() +{ + if (_fh != INVALID_HANDLE_VALUE) + FindClose(_fh); +} + + +const std::string& DirectoryIteratorImpl::next() +{ + do + { + _current.clear(); + if (FindNextFileW(_fh, &_fd) != 0) + { + UnicodeConverter::toUTF8(_fd.cFileName, _current); + } + } + while (_current == "." || _current == ".."); + return _current; +} + + +} // namespace Poco diff --git a/Foundation/src/Environment.cpp b/Foundation/src/Environment.cpp index a4209a9c3..3650ce854 100644 --- a/Foundation/src/Environment.cpp +++ b/Foundation/src/Environment.cpp @@ -1,96 +1,96 @@ -// -// Environment.cpp -// -// $Id: //poco/1.2/Foundation/src/Environment.cpp#1 $ -// -// Library: Foundation -// Package: Core -// Module: Environment -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/Environment.h" - - -#if defined(POCO_OS_FAMILY_VMS) -#include "Environment_VMS.cpp" -#elif defined(POCO_OS_FAMILY_UNIX) -#include "Environment_UNIX.cpp" -#elif defined(POCO_OS_FAMILY_WINDOWS) && defined(POCO_WIN32_UTF8) -#include "Environment_WIN32U.cpp" -#elif defined(POCO_OS_FAMILY_WINDOWS) -#include "Environment_WIN32.cpp" -#endif - - -namespace Poco { - - -std::string Environment::get(const std::string& name) -{ - return EnvironmentImpl::getImpl(name); -} - - -bool Environment::has(const std::string& name) -{ - return EnvironmentImpl::hasImpl(name); -} - - -void Environment::set(const std::string& name, const std::string& value) -{ - EnvironmentImpl::setImpl(name, value); -} - - -std::string Environment::osName() -{ - return EnvironmentImpl::osNameImpl(); -} - - -std::string Environment::osVersion() -{ - return EnvironmentImpl::osVersionImpl(); -} - - -std::string Environment::osArchitecture() -{ - return EnvironmentImpl::osArchitectureImpl(); -} - - -std::string Environment::nodeName() -{ - return EnvironmentImpl::nodeNameImpl(); -} - - -} // namespace Poco +// +// Environment.cpp +// +// $Id: //poco/1.2/Foundation/src/Environment.cpp#1 $ +// +// Library: Foundation +// Package: Core +// Module: Environment +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/Environment.h" + + +#if defined(POCO_OS_FAMILY_VMS) +#include "Environment_VMS.cpp" +#elif defined(POCO_OS_FAMILY_UNIX) +#include "Environment_UNIX.cpp" +#elif defined(POCO_OS_FAMILY_WINDOWS) && defined(POCO_WIN32_UTF8) +#include "Environment_WIN32U.cpp" +#elif defined(POCO_OS_FAMILY_WINDOWS) +#include "Environment_WIN32.cpp" +#endif + + +namespace Poco { + + +std::string Environment::get(const std::string& name) +{ + return EnvironmentImpl::getImpl(name); +} + + +bool Environment::has(const std::string& name) +{ + return EnvironmentImpl::hasImpl(name); +} + + +void Environment::set(const std::string& name, const std::string& value) +{ + EnvironmentImpl::setImpl(name, value); +} + + +std::string Environment::osName() +{ + return EnvironmentImpl::osNameImpl(); +} + + +std::string Environment::osVersion() +{ + return EnvironmentImpl::osVersionImpl(); +} + + +std::string Environment::osArchitecture() +{ + return EnvironmentImpl::osArchitectureImpl(); +} + + +std::string Environment::nodeName() +{ + return EnvironmentImpl::nodeNameImpl(); +} + + +} // namespace Poco diff --git a/Foundation/src/Environment_UNIX.cpp b/Foundation/src/Environment_UNIX.cpp index dd3269191..226b4bcdc 100644 --- a/Foundation/src/Environment_UNIX.cpp +++ b/Foundation/src/Environment_UNIX.cpp @@ -1,120 +1,120 @@ -// -// Environment_UNIX.cpp -// -// $Id: //poco/1.2/Foundation/src/Environment_UNIX.cpp#1 $ -// -// Library: Foundation -// Package: Core -// Module: Environment -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/Environment_UNIX.h" -#include "Poco/Exception.h" -#include -#include -#include - - -namespace Poco { - - -EnvironmentImpl::StringMap EnvironmentImpl::_map; -FastMutex EnvironmentImpl::_mutex; - - -std::string EnvironmentImpl::getImpl(const std::string& name) -{ - FastMutex::ScopedLock lock(_mutex); - - const char* val = getenv(name.c_str()); - if (val) - return std::string(val); - else - throw NotFoundException(name); -} - - -bool EnvironmentImpl::hasImpl(const std::string& name) -{ - FastMutex::ScopedLock lock(_mutex); - - return getenv(name.c_str()) != 0; -} - - -void EnvironmentImpl::setImpl(const std::string& name, const std::string& value) -{ - FastMutex::ScopedLock lock(_mutex); - - std::string var = name; - var.append("="); - var.append(value); - _map[name] = var; - if (putenv((char*) _map[name].c_str())) - { - std::string msg = "cannot set environment variable: "; - msg.append(name); - throw SystemException(msg); - } -} - - -std::string EnvironmentImpl::osNameImpl() -{ - struct utsname uts; - uname(&uts); - return uts.sysname; -} - - -std::string EnvironmentImpl::osVersionImpl() -{ - struct utsname uts; - uname(&uts); - return uts.release; -} - - -std::string EnvironmentImpl::osArchitectureImpl() -{ - struct utsname uts; - uname(&uts); - return uts.machine; -} - - -std::string EnvironmentImpl::nodeNameImpl() -{ - struct utsname uts; - uname(&uts); - return uts.nodename; -} - - -} // namespace Poco +// +// Environment_UNIX.cpp +// +// $Id: //poco/1.2/Foundation/src/Environment_UNIX.cpp#1 $ +// +// Library: Foundation +// Package: Core +// Module: Environment +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/Environment_UNIX.h" +#include "Poco/Exception.h" +#include +#include +#include + + +namespace Poco { + + +EnvironmentImpl::StringMap EnvironmentImpl::_map; +FastMutex EnvironmentImpl::_mutex; + + +std::string EnvironmentImpl::getImpl(const std::string& name) +{ + FastMutex::ScopedLock lock(_mutex); + + const char* val = getenv(name.c_str()); + if (val) + return std::string(val); + else + throw NotFoundException(name); +} + + +bool EnvironmentImpl::hasImpl(const std::string& name) +{ + FastMutex::ScopedLock lock(_mutex); + + return getenv(name.c_str()) != 0; +} + + +void EnvironmentImpl::setImpl(const std::string& name, const std::string& value) +{ + FastMutex::ScopedLock lock(_mutex); + + std::string var = name; + var.append("="); + var.append(value); + _map[name] = var; + if (putenv((char*) _map[name].c_str())) + { + std::string msg = "cannot set environment variable: "; + msg.append(name); + throw SystemException(msg); + } +} + + +std::string EnvironmentImpl::osNameImpl() +{ + struct utsname uts; + uname(&uts); + return uts.sysname; +} + + +std::string EnvironmentImpl::osVersionImpl() +{ + struct utsname uts; + uname(&uts); + return uts.release; +} + + +std::string EnvironmentImpl::osArchitectureImpl() +{ + struct utsname uts; + uname(&uts); + return uts.machine; +} + + +std::string EnvironmentImpl::nodeNameImpl() +{ + struct utsname uts; + uname(&uts); + return uts.nodename; +} + + +} // namespace Poco diff --git a/Foundation/src/Environment_VMS.cpp b/Foundation/src/Environment_VMS.cpp index 873ff4773..d5738948e 100644 --- a/Foundation/src/Environment_VMS.cpp +++ b/Foundation/src/Environment_VMS.cpp @@ -1,171 +1,171 @@ -// -// Environment_VMS.cpp -// -// $Id: //poco/1.2/Foundation/src/Environment_VMS.cpp#1 $ -// -// Library: Foundation -// Package: Core -// Module: Environment -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/Environment_VMS.h" -#include "Poco/Exception.h" -#include -#include -#include -#include -#include -#include -#include - - -namespace Poco { - - -FastMutex EnvironmentImpl::_mutex; - - -std::string EnvironmentImpl::getImpl(const std::string& name) -{ - FastMutex::ScopedLock lock(_mutex); - - const char* val = getenv(name.c_str()); - if (val) - return std::string(val); - else - throw NotFoundException(name); -} - - -bool EnvironmentImpl::hasImpl(const std::string& name) -{ - FastMutex::ScopedLock lock(_mutex); - - return getenv(name.c_str()) != 0; -} - - -void EnvironmentImpl::setImpl(const std::string& name, const std::string& value) -{ - FastMutex::ScopedLock lock(_mutex); - - if (setenv(name.c_str(), value.c_str(), 1)) - { - std::string msg = "cannot set environment variable: "; - msg.append(name); - throw SystemException(msg); - } -} - - -std::string EnvironmentImpl::osNameImpl() -{ - return getsyi(SYI$_NODE_SWTYPE); -} - - -std::string EnvironmentImpl::osVersionImpl() -{ - return getsyi(SYI$_VERSION); -} - - -std::string EnvironmentImpl::osArchitectureImpl() -{ - return getsyi(SYI$_ARCH_NAME); -} - - -std::string EnvironmentImpl::nodeNameImpl() -{ - return getsyi(SYI$_NODENAME); -} - - -std::string EnvironmentImpl::getsyi(unsigned short code) -{ - #pragma pointer_size save - #pragma pointer_size 32 - - unsigned char result[16]; - unsigned short length; - - ILE3 items[2]; - items[0].ile3$w_code = code; - items[0].ile3$w_length = sizeof(result); - items[0].ile3$ps_bufaddr = result; - items[0].ile3$ps_retlen_addr = &length; - items[1].ile3$w_code = 0; - items[1].ile3$w_length = 0; - - if (sys$getsyiw(0, 0, 0, items, 0, 0, 0) == 1) - return std::string((char*) result, length); - else - throw SystemException("$GETSYI failed"); - - #pragma pointer_size restore -} - - -std::string EnvironmentImpl::trnlnm(const std::string& name) -{ - #pragma pointer_size save - #pragma pointer_size 32 - - unsigned char result[LNM$C_NAMLENGTH]; - unsigned short length; - - ILE3 items[2]; - items[0].ile3$w_code = LNM$_STRING; - items[0].ile3$w_length = sizeof(result); - items[0].ile3$ps_bufaddr = result; - items[0].ile3$ps_retlen_addr = &length; - items[1].ile3$w_code = 0; - items[1].ile3$w_length = 0; - - #pragma pointer_size restore - - unsigned int trnAttr = LNM$M_CASE_BLIND; - POCO_DESCRIPTOR_LITERAL(tableDsc, "LNM$FILE_DEV"); - POCO_DESCRIPTOR_STRING(nameDsc, name); - if (sys$trnlnm(&trnAttr, &tableDsc, &nameDsc, 0, &items) == 1) - { - if (result[0] == 0x1B) - return std::string((char*) result + 4, length - 4); - else - return std::string((char*) result, length); - } - else - { - return std::string(); - } -} - - -} // namespace Poco +// +// Environment_VMS.cpp +// +// $Id: //poco/1.2/Foundation/src/Environment_VMS.cpp#1 $ +// +// Library: Foundation +// Package: Core +// Module: Environment +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/Environment_VMS.h" +#include "Poco/Exception.h" +#include +#include +#include +#include +#include +#include +#include + + +namespace Poco { + + +FastMutex EnvironmentImpl::_mutex; + + +std::string EnvironmentImpl::getImpl(const std::string& name) +{ + FastMutex::ScopedLock lock(_mutex); + + const char* val = getenv(name.c_str()); + if (val) + return std::string(val); + else + throw NotFoundException(name); +} + + +bool EnvironmentImpl::hasImpl(const std::string& name) +{ + FastMutex::ScopedLock lock(_mutex); + + return getenv(name.c_str()) != 0; +} + + +void EnvironmentImpl::setImpl(const std::string& name, const std::string& value) +{ + FastMutex::ScopedLock lock(_mutex); + + if (setenv(name.c_str(), value.c_str(), 1)) + { + std::string msg = "cannot set environment variable: "; + msg.append(name); + throw SystemException(msg); + } +} + + +std::string EnvironmentImpl::osNameImpl() +{ + return getsyi(SYI$_NODE_SWTYPE); +} + + +std::string EnvironmentImpl::osVersionImpl() +{ + return getsyi(SYI$_VERSION); +} + + +std::string EnvironmentImpl::osArchitectureImpl() +{ + return getsyi(SYI$_ARCH_NAME); +} + + +std::string EnvironmentImpl::nodeNameImpl() +{ + return getsyi(SYI$_NODENAME); +} + + +std::string EnvironmentImpl::getsyi(unsigned short code) +{ + #pragma pointer_size save + #pragma pointer_size 32 + + unsigned char result[16]; + unsigned short length; + + ILE3 items[2]; + items[0].ile3$w_code = code; + items[0].ile3$w_length = sizeof(result); + items[0].ile3$ps_bufaddr = result; + items[0].ile3$ps_retlen_addr = &length; + items[1].ile3$w_code = 0; + items[1].ile3$w_length = 0; + + if (sys$getsyiw(0, 0, 0, items, 0, 0, 0) == 1) + return std::string((char*) result, length); + else + throw SystemException("$GETSYI failed"); + + #pragma pointer_size restore +} + + +std::string EnvironmentImpl::trnlnm(const std::string& name) +{ + #pragma pointer_size save + #pragma pointer_size 32 + + unsigned char result[LNM$C_NAMLENGTH]; + unsigned short length; + + ILE3 items[2]; + items[0].ile3$w_code = LNM$_STRING; + items[0].ile3$w_length = sizeof(result); + items[0].ile3$ps_bufaddr = result; + items[0].ile3$ps_retlen_addr = &length; + items[1].ile3$w_code = 0; + items[1].ile3$w_length = 0; + + #pragma pointer_size restore + + unsigned int trnAttr = LNM$M_CASE_BLIND; + POCO_DESCRIPTOR_LITERAL(tableDsc, "LNM$FILE_DEV"); + POCO_DESCRIPTOR_STRING(nameDsc, name); + if (sys$trnlnm(&trnAttr, &tableDsc, &nameDsc, 0, &items) == 1) + { + if (result[0] == 0x1B) + return std::string((char*) result + 4, length - 4); + else + return std::string((char*) result, length); + } + else + { + return std::string(); + } +} + + +} // namespace Poco diff --git a/Foundation/src/Environment_WIN32.cpp b/Foundation/src/Environment_WIN32.cpp index 61a9c3fc9..bcb6198c5 100644 --- a/Foundation/src/Environment_WIN32.cpp +++ b/Foundation/src/Environment_WIN32.cpp @@ -1,147 +1,147 @@ -// -// Environment_WIN32.cpp -// -// $Id: //poco/1.2/Foundation/src/Environment_WIN32.cpp#1 $ -// -// Library: Foundation -// Package: Core -// Module: Environment -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/Environment_WIN32.h" -#include "Poco/Exception.h" -#include -#include - - -namespace Poco { - - -std::string EnvironmentImpl::getImpl(const std::string& name) -{ - DWORD len = GetEnvironmentVariable(name.c_str(), 0, 0); - if (len == 0) throw NotFoundException(name); - char* buffer = new char[len]; - GetEnvironmentVariable(name.c_str(), buffer, len); - std::string result(buffer); - delete [] buffer; - return result; -} - - -bool EnvironmentImpl::hasImpl(const std::string& name) -{ - DWORD len = GetEnvironmentVariable(name.c_str(), 0, 0); - return len > 0; -} - - -void EnvironmentImpl::setImpl(const std::string& name, const std::string& value) -{ - if (SetEnvironmentVariable(name.c_str(), value.c_str()) == 0) - { - std::string msg = "cannot set environment variable: "; - msg.append(name); - throw SystemException(msg); - } -} - - -std::string EnvironmentImpl::osNameImpl() -{ - OSVERSIONINFO vi; - vi.dwOSVersionInfoSize = sizeof(vi); - if (GetVersionEx(&vi) == 0) throw SystemException("Cannot get OS version information"); - switch (vi.dwPlatformId) - { - case VER_PLATFORM_WIN32s: - return "Windows 3.x"; - case VER_PLATFORM_WIN32_WINDOWS: - return vi.dwMinorVersion == 0 ? "Windows 95" : "Windows 98"; - case VER_PLATFORM_WIN32_NT: - return "Windows NT"; - default: - return "Unknown"; - } -} - - -std::string EnvironmentImpl::osVersionImpl() -{ - OSVERSIONINFO vi; - vi.dwOSVersionInfoSize = sizeof(vi); - if (GetVersionEx(&vi) == 0) throw SystemException("Cannot get OS version information"); - std::ostringstream str; - str << vi.dwMajorVersion << "." << vi.dwMinorVersion << " (Build " << (vi.dwBuildNumber & 0xFFFF); - if (vi.szCSDVersion[0]) str << ": " << vi.szCSDVersion; - str << ")"; - return str.str(); -} - - -std::string EnvironmentImpl::osArchitectureImpl() -{ - SYSTEM_INFO si; - GetSystemInfo(&si); - switch (si.wProcessorArchitecture) - { - case PROCESSOR_ARCHITECTURE_INTEL: - return "IA32"; - case PROCESSOR_ARCHITECTURE_MIPS: - return "MIPS"; - case PROCESSOR_ARCHITECTURE_ALPHA: - return "ALPHA"; - case PROCESSOR_ARCHITECTURE_PPC: - return "PPC"; - case PROCESSOR_ARCHITECTURE_IA64: - return "IA64"; -#ifdef PROCESSOR_ARCHITECTURE_IA32_ON_WIN64 - case PROCESSOR_ARCHITECTURE_IA32_ON_WIN64: - return "IA64/32"; -#endif -#ifdef PROCESSOR_ARCHITECTURE_AMD64 - case PROCESSOR_ARCHITECTURE_AMD64: - return "AMD64"; -#endif - default: - return "Unknown"; - } -} - - -std::string EnvironmentImpl::nodeNameImpl() -{ - char name[MAX_COMPUTERNAME_LENGTH + 1]; - DWORD size = sizeof(name); - if (GetComputerName(name, &size) == 0) throw SystemException("Cannot get computer name"); - return std::string(name); -} - - -} // namespace Poco +// +// Environment_WIN32.cpp +// +// $Id: //poco/1.2/Foundation/src/Environment_WIN32.cpp#1 $ +// +// Library: Foundation +// Package: Core +// Module: Environment +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/Environment_WIN32.h" +#include "Poco/Exception.h" +#include +#include + + +namespace Poco { + + +std::string EnvironmentImpl::getImpl(const std::string& name) +{ + DWORD len = GetEnvironmentVariable(name.c_str(), 0, 0); + if (len == 0) throw NotFoundException(name); + char* buffer = new char[len]; + GetEnvironmentVariable(name.c_str(), buffer, len); + std::string result(buffer); + delete [] buffer; + return result; +} + + +bool EnvironmentImpl::hasImpl(const std::string& name) +{ + DWORD len = GetEnvironmentVariable(name.c_str(), 0, 0); + return len > 0; +} + + +void EnvironmentImpl::setImpl(const std::string& name, const std::string& value) +{ + if (SetEnvironmentVariable(name.c_str(), value.c_str()) == 0) + { + std::string msg = "cannot set environment variable: "; + msg.append(name); + throw SystemException(msg); + } +} + + +std::string EnvironmentImpl::osNameImpl() +{ + OSVERSIONINFO vi; + vi.dwOSVersionInfoSize = sizeof(vi); + if (GetVersionEx(&vi) == 0) throw SystemException("Cannot get OS version information"); + switch (vi.dwPlatformId) + { + case VER_PLATFORM_WIN32s: + return "Windows 3.x"; + case VER_PLATFORM_WIN32_WINDOWS: + return vi.dwMinorVersion == 0 ? "Windows 95" : "Windows 98"; + case VER_PLATFORM_WIN32_NT: + return "Windows NT"; + default: + return "Unknown"; + } +} + + +std::string EnvironmentImpl::osVersionImpl() +{ + OSVERSIONINFO vi; + vi.dwOSVersionInfoSize = sizeof(vi); + if (GetVersionEx(&vi) == 0) throw SystemException("Cannot get OS version information"); + std::ostringstream str; + str << vi.dwMajorVersion << "." << vi.dwMinorVersion << " (Build " << (vi.dwBuildNumber & 0xFFFF); + if (vi.szCSDVersion[0]) str << ": " << vi.szCSDVersion; + str << ")"; + return str.str(); +} + + +std::string EnvironmentImpl::osArchitectureImpl() +{ + SYSTEM_INFO si; + GetSystemInfo(&si); + switch (si.wProcessorArchitecture) + { + case PROCESSOR_ARCHITECTURE_INTEL: + return "IA32"; + case PROCESSOR_ARCHITECTURE_MIPS: + return "MIPS"; + case PROCESSOR_ARCHITECTURE_ALPHA: + return "ALPHA"; + case PROCESSOR_ARCHITECTURE_PPC: + return "PPC"; + case PROCESSOR_ARCHITECTURE_IA64: + return "IA64"; +#ifdef PROCESSOR_ARCHITECTURE_IA32_ON_WIN64 + case PROCESSOR_ARCHITECTURE_IA32_ON_WIN64: + return "IA64/32"; +#endif +#ifdef PROCESSOR_ARCHITECTURE_AMD64 + case PROCESSOR_ARCHITECTURE_AMD64: + return "AMD64"; +#endif + default: + return "Unknown"; + } +} + + +std::string EnvironmentImpl::nodeNameImpl() +{ + char name[MAX_COMPUTERNAME_LENGTH + 1]; + DWORD size = sizeof(name); + if (GetComputerName(name, &size) == 0) throw SystemException("Cannot get computer name"); + return std::string(name); +} + + +} // namespace Poco diff --git a/Foundation/src/Environment_WIN32U.cpp b/Foundation/src/Environment_WIN32U.cpp index 7590c5678..214c31d4d 100644 --- a/Foundation/src/Environment_WIN32U.cpp +++ b/Foundation/src/Environment_WIN32U.cpp @@ -1,162 +1,162 @@ -// -// Environment_WIN32U.cpp -// -// $Id: //poco/1.2/Foundation/src/Environment_WIN32U.cpp#1 $ -// -// Library: Foundation -// Package: Core -// Module: Environment -// -// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/Environment_WIN32U.h" -#include "Poco/Exception.h" -#include "Poco/UnicodeConverter.h" -#include "Poco/Buffer.h" -#include -#include -#include - - -namespace Poco { - - -std::string EnvironmentImpl::getImpl(const std::string& name) -{ - std::wstring uname; - UnicodeConverter::toUTF16(name, uname); - DWORD len = GetEnvironmentVariableW(uname.c_str(), 0, 0); - if (len == 0) throw NotFoundException(name); - Buffer buffer(len); - GetEnvironmentVariableW(uname.c_str(), buffer.begin(), len); - std::string result; - UnicodeConverter::toUTF8(buffer.begin(), len - 1, result); - return result; -} - - -bool EnvironmentImpl::hasImpl(const std::string& name) -{ - std::wstring uname; - UnicodeConverter::toUTF16(name, uname); - DWORD len = GetEnvironmentVariableW(uname.c_str(), 0, 0); - return len > 0; -} - - -void EnvironmentImpl::setImpl(const std::string& name, const std::string& value) -{ - std::wstring uname; - std::wstring uvalue; - UnicodeConverter::toUTF16(name, uname); - UnicodeConverter::toUTF16(value, uvalue); - if (SetEnvironmentVariableW(uname.c_str(), uvalue.c_str()) == 0) - { - std::string msg = "cannot set environment variable: "; - msg.append(name); - throw SystemException(msg); - } -} - - -std::string EnvironmentImpl::osNameImpl() -{ - OSVERSIONINFO vi; - vi.dwOSVersionInfoSize = sizeof(vi); - if (GetVersionEx(&vi) == 0) throw SystemException("Cannot get OS version information"); - switch (vi.dwPlatformId) - { - case VER_PLATFORM_WIN32s: - return "Windows 3.x"; - case VER_PLATFORM_WIN32_WINDOWS: - return vi.dwMinorVersion == 0 ? "Windows 95" : "Windows 98"; - case VER_PLATFORM_WIN32_NT: - return "Windows NT"; - default: - return "Unknown"; - } -} - - -std::string EnvironmentImpl::osVersionImpl() -{ - OSVERSIONINFO vi; - vi.dwOSVersionInfoSize = sizeof(vi); - if (GetVersionEx(&vi) == 0) throw SystemException("Cannot get OS version information"); - std::ostringstream str; - str << vi.dwMajorVersion << "." << vi.dwMinorVersion << " (Build " << (vi.dwBuildNumber & 0xFFFF); - std::string version; - UnicodeConverter::toUTF8(vi.szCSDVersion, version); - if (!version.empty()) str << ": " << version; - str << ")"; - return str.str(); -} - - -std::string EnvironmentImpl::osArchitectureImpl() -{ - SYSTEM_INFO si; - GetSystemInfo(&si); - switch (si.wProcessorArchitecture) - { - case PROCESSOR_ARCHITECTURE_INTEL: - return "IA32"; - case PROCESSOR_ARCHITECTURE_MIPS: - return "MIPS"; - case PROCESSOR_ARCHITECTURE_ALPHA: - return "ALPHA"; - case PROCESSOR_ARCHITECTURE_PPC: - return "PPC"; - case PROCESSOR_ARCHITECTURE_IA64: - return "IA64"; -#ifdef PROCESSOR_ARCHITECTURE_IA32_ON_WIN64 - case PROCESSOR_ARCHITECTURE_IA32_ON_WIN64: - return "IA64/32"; -#endif -#ifdef PROCESSOR_ARCHITECTURE_AMD64 - case PROCESSOR_ARCHITECTURE_AMD64: - return "AMD64"; -#endif - default: - return "Unknown"; - } -} - - -std::string EnvironmentImpl::nodeNameImpl() -{ - wchar_t name[MAX_COMPUTERNAME_LENGTH + 1]; - DWORD size = MAX_COMPUTERNAME_LENGTH + 1; - if (GetComputerNameW(name, &size) == 0) throw SystemException("Cannot get computer name"); - std::string result; - UnicodeConverter::toUTF8(name, result); - return result; -} - - -} // namespace Poco +// +// Environment_WIN32U.cpp +// +// $Id: //poco/1.2/Foundation/src/Environment_WIN32U.cpp#1 $ +// +// Library: Foundation +// Package: Core +// Module: Environment +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/Environment_WIN32U.h" +#include "Poco/Exception.h" +#include "Poco/UnicodeConverter.h" +#include "Poco/Buffer.h" +#include +#include +#include + + +namespace Poco { + + +std::string EnvironmentImpl::getImpl(const std::string& name) +{ + std::wstring uname; + UnicodeConverter::toUTF16(name, uname); + DWORD len = GetEnvironmentVariableW(uname.c_str(), 0, 0); + if (len == 0) throw NotFoundException(name); + Buffer buffer(len); + GetEnvironmentVariableW(uname.c_str(), buffer.begin(), len); + std::string result; + UnicodeConverter::toUTF8(buffer.begin(), len - 1, result); + return result; +} + + +bool EnvironmentImpl::hasImpl(const std::string& name) +{ + std::wstring uname; + UnicodeConverter::toUTF16(name, uname); + DWORD len = GetEnvironmentVariableW(uname.c_str(), 0, 0); + return len > 0; +} + + +void EnvironmentImpl::setImpl(const std::string& name, const std::string& value) +{ + std::wstring uname; + std::wstring uvalue; + UnicodeConverter::toUTF16(name, uname); + UnicodeConverter::toUTF16(value, uvalue); + if (SetEnvironmentVariableW(uname.c_str(), uvalue.c_str()) == 0) + { + std::string msg = "cannot set environment variable: "; + msg.append(name); + throw SystemException(msg); + } +} + + +std::string EnvironmentImpl::osNameImpl() +{ + OSVERSIONINFO vi; + vi.dwOSVersionInfoSize = sizeof(vi); + if (GetVersionEx(&vi) == 0) throw SystemException("Cannot get OS version information"); + switch (vi.dwPlatformId) + { + case VER_PLATFORM_WIN32s: + return "Windows 3.x"; + case VER_PLATFORM_WIN32_WINDOWS: + return vi.dwMinorVersion == 0 ? "Windows 95" : "Windows 98"; + case VER_PLATFORM_WIN32_NT: + return "Windows NT"; + default: + return "Unknown"; + } +} + + +std::string EnvironmentImpl::osVersionImpl() +{ + OSVERSIONINFO vi; + vi.dwOSVersionInfoSize = sizeof(vi); + if (GetVersionEx(&vi) == 0) throw SystemException("Cannot get OS version information"); + std::ostringstream str; + str << vi.dwMajorVersion << "." << vi.dwMinorVersion << " (Build " << (vi.dwBuildNumber & 0xFFFF); + std::string version; + UnicodeConverter::toUTF8(vi.szCSDVersion, version); + if (!version.empty()) str << ": " << version; + str << ")"; + return str.str(); +} + + +std::string EnvironmentImpl::osArchitectureImpl() +{ + SYSTEM_INFO si; + GetSystemInfo(&si); + switch (si.wProcessorArchitecture) + { + case PROCESSOR_ARCHITECTURE_INTEL: + return "IA32"; + case PROCESSOR_ARCHITECTURE_MIPS: + return "MIPS"; + case PROCESSOR_ARCHITECTURE_ALPHA: + return "ALPHA"; + case PROCESSOR_ARCHITECTURE_PPC: + return "PPC"; + case PROCESSOR_ARCHITECTURE_IA64: + return "IA64"; +#ifdef PROCESSOR_ARCHITECTURE_IA32_ON_WIN64 + case PROCESSOR_ARCHITECTURE_IA32_ON_WIN64: + return "IA64/32"; +#endif +#ifdef PROCESSOR_ARCHITECTURE_AMD64 + case PROCESSOR_ARCHITECTURE_AMD64: + return "AMD64"; +#endif + default: + return "Unknown"; + } +} + + +std::string EnvironmentImpl::nodeNameImpl() +{ + wchar_t name[MAX_COMPUTERNAME_LENGTH + 1]; + DWORD size = MAX_COMPUTERNAME_LENGTH + 1; + if (GetComputerNameW(name, &size) == 0) throw SystemException("Cannot get computer name"); + std::string result; + UnicodeConverter::toUTF8(name, result); + return result; +} + + +} // namespace Poco diff --git a/Foundation/src/ErrorHandler.cpp b/Foundation/src/ErrorHandler.cpp index e48b85533..6b90d7c41 100644 --- a/Foundation/src/ErrorHandler.cpp +++ b/Foundation/src/ErrorHandler.cpp @@ -1,133 +1,133 @@ -// -// ErrorHandler.cpp -// -// $Id: //poco/1.2/Foundation/src/ErrorHandler.cpp#1 $ -// -// Library: Foundation -// Package: Threading -// Module: ErrorHandler -// -// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/ErrorHandler.h" -#include "Poco/SingletonHolder.h" - - -namespace Poco { - - -ErrorHandler* ErrorHandler::_pHandler = ErrorHandler::defaultHandler(); -FastMutex ErrorHandler::_mutex; - - -ErrorHandler::ErrorHandler() -{ -} - - -ErrorHandler::~ErrorHandler() -{ -} - - -void ErrorHandler::exception(const Exception& exc) -{ - poco_debugger_msg(exc.what()); -} - - -void ErrorHandler::exception(const std::exception& exc) -{ - poco_debugger_msg(exc.what()); -} - - -void ErrorHandler::exception() -{ - poco_debugger_msg("unknown exception"); -} - - -void ErrorHandler::handle(const Exception& exc) -{ - FastMutex::ScopedLock lock(_mutex); - try - { - _pHandler->exception(exc); - } - catch (...) - { - } -} - - -void ErrorHandler::handle(const std::exception& exc) -{ - FastMutex::ScopedLock lock(_mutex); - try - { - _pHandler->exception(exc); - } - catch (...) - { - } -} - - -void ErrorHandler::handle() -{ - FastMutex::ScopedLock lock(_mutex); - try - { - _pHandler->exception(); - } - catch (...) - { - } -} - - -ErrorHandler* ErrorHandler::set(ErrorHandler* pHandler) -{ - poco_check_ptr(pHandler); - - FastMutex::ScopedLock lock(_mutex); - ErrorHandler* pOld = _pHandler; - _pHandler = pHandler; - return pOld; -} - - -ErrorHandler* ErrorHandler::defaultHandler() -{ - static SingletonHolder sh; - return sh.get(); -} - - -} // namespace Poco +// +// ErrorHandler.cpp +// +// $Id: //poco/1.2/Foundation/src/ErrorHandler.cpp#1 $ +// +// Library: Foundation +// Package: Threading +// Module: ErrorHandler +// +// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/ErrorHandler.h" +#include "Poco/SingletonHolder.h" + + +namespace Poco { + + +ErrorHandler* ErrorHandler::_pHandler = ErrorHandler::defaultHandler(); +FastMutex ErrorHandler::_mutex; + + +ErrorHandler::ErrorHandler() +{ +} + + +ErrorHandler::~ErrorHandler() +{ +} + + +void ErrorHandler::exception(const Exception& exc) +{ + poco_debugger_msg(exc.what()); +} + + +void ErrorHandler::exception(const std::exception& exc) +{ + poco_debugger_msg(exc.what()); +} + + +void ErrorHandler::exception() +{ + poco_debugger_msg("unknown exception"); +} + + +void ErrorHandler::handle(const Exception& exc) +{ + FastMutex::ScopedLock lock(_mutex); + try + { + _pHandler->exception(exc); + } + catch (...) + { + } +} + + +void ErrorHandler::handle(const std::exception& exc) +{ + FastMutex::ScopedLock lock(_mutex); + try + { + _pHandler->exception(exc); + } + catch (...) + { + } +} + + +void ErrorHandler::handle() +{ + FastMutex::ScopedLock lock(_mutex); + try + { + _pHandler->exception(); + } + catch (...) + { + } +} + + +ErrorHandler* ErrorHandler::set(ErrorHandler* pHandler) +{ + poco_check_ptr(pHandler); + + FastMutex::ScopedLock lock(_mutex); + ErrorHandler* pOld = _pHandler; + _pHandler = pHandler; + return pOld; +} + + +ErrorHandler* ErrorHandler::defaultHandler() +{ + static SingletonHolder sh; + return sh.get(); +} + + +} // namespace Poco diff --git a/Foundation/src/Event.cpp b/Foundation/src/Event.cpp index f145e4577..e4eccbf6b 100644 --- a/Foundation/src/Event.cpp +++ b/Foundation/src/Event.cpp @@ -1,60 +1,60 @@ -// -// Event.cpp -// -// $Id: //poco/1.2/Foundation/src/Event.cpp#1 $ -// -// Library: Foundation -// Package: Threading -// Module: Event -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/Event.h" - - -#if defined(POCO_OS_FAMILY_WINDOWS) -#include "Event_WIN32.cpp" -#else -#include "Event_POSIX.cpp" -#endif - - -namespace Poco { - - -Event::Event(bool autoReset): EventImpl(autoReset) -{ -} - - -Event::~Event() -{ -} - - -} // namespace Poco +// +// Event.cpp +// +// $Id: //poco/1.2/Foundation/src/Event.cpp#1 $ +// +// Library: Foundation +// Package: Threading +// Module: Event +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/Event.h" + + +#if defined(POCO_OS_FAMILY_WINDOWS) +#include "Event_WIN32.cpp" +#else +#include "Event_POSIX.cpp" +#endif + + +namespace Poco { + + +Event::Event(bool autoReset): EventImpl(autoReset) +{ +} + + +Event::~Event() +{ +} + + +} // namespace Poco diff --git a/Foundation/src/EventArgs.cpp b/Foundation/src/EventArgs.cpp index d08c7abd0..8dd187b7f 100644 --- a/Foundation/src/EventArgs.cpp +++ b/Foundation/src/EventArgs.cpp @@ -1,55 +1,55 @@ -// -// EventArgs.cpp -// -// $Id: //poco/1.2/Foundation/src/EventArgs.cpp#1 $ -// -// Library: Foundation -// Package: Events -// Module: EventArgs -// -// Implementation of EventArgs -// -// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/EventArgs.h" - - -namespace Poco { - - -EventArgs::EventArgs() -{ -} - - -EventArgs::~EventArgs() -{ -} - - -} // namespace Poco +// +// EventArgs.cpp +// +// $Id: //poco/1.2/Foundation/src/EventArgs.cpp#1 $ +// +// Library: Foundation +// Package: Events +// Module: EventArgs +// +// Implementation of EventArgs +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/EventArgs.h" + + +namespace Poco { + + +EventArgs::EventArgs() +{ +} + + +EventArgs::~EventArgs() +{ +} + + +} // namespace Poco diff --git a/Foundation/src/EventLogChannel.cpp b/Foundation/src/EventLogChannel.cpp index 850653b08..0157bf733 100644 --- a/Foundation/src/EventLogChannel.cpp +++ b/Foundation/src/EventLogChannel.cpp @@ -1,315 +1,315 @@ -// -// EventLogChannel.cpp -// -// $Id: //poco/1.2/Foundation/src/EventLogChannel.cpp#2 $ -// -// Library: Foundation -// Package: Logging -// Module: EventLogChannel -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/EventLogChannel.h" -#include "Poco/Message.h" -#include "Poco/String.h" -#include "pocomsg.h" -#if defined(POCO_WIN32_UTF8) -#include "Poco/UnicodeConverter.h" -#endif - - -namespace Poco { - - -const std::string EventLogChannel::PROP_NAME = "name"; -const std::string EventLogChannel::PROP_HOST = "host"; -const std::string EventLogChannel::PROP_LOGHOST = "loghost"; -const std::string EventLogChannel::PROP_LOGFILE = "logfile"; - - -EventLogChannel::EventLogChannel(): - _logFile("Application"), - _h(0) -{ -#if defined(POCO_WIN32_UTF8) - wchar_t name[256]; - int n = GetModuleFileNameW(NULL, name, sizeof(name)); - if (n > 0) - { - wchar_t* end = name + n - 1; - while (end > name && *end != '\\') --end; - if (*end == '\\') ++end; - std::wstring uname(end); - UnicodeConverter::toUTF8(uname, _name); - } -#else - char name[256]; - int n = GetModuleFileName(NULL, name, sizeof(name)); - if (n > 0) - { - char* end = name + n - 1; - while (end > name && *end != '\\') --end; - if (*end == '\\') ++end; - _name = end; - } -#endif -} - - -EventLogChannel::EventLogChannel(const std::string& name): - _name(name), - _logFile("Application"), - _h(0) -{ -} - - -EventLogChannel::EventLogChannel(const std::string& name, const std::string& host): - _name(name), - _host(host), - _logFile("Application"), - _h(0) -{ -} - - -EventLogChannel::~EventLogChannel() -{ - close(); -} - - -void EventLogChannel::open() -{ - setUpRegistry(); -#if defined(POCO_WIN32_UTF8) - std::wstring uhost; - UnicodeConverter::toUTF16(_host, uhost); - std::wstring uname; - UnicodeConverter::toUTF16(_name, uname); - _h = RegisterEventSourceW(uhost.empty() ? NULL : uhost.c_str(), uname.c_str()); -#else - _h = RegisterEventSource(_host.empty() ? NULL : _host.c_str(), _name.c_str()); -#endif - if (!_h) throw SystemException("cannot register event source"); -} - - -void EventLogChannel::close() -{ - if (_h) DeregisterEventSource(_h); - _h = 0; -} - - -void EventLogChannel::log(const Message& msg) -{ - if (!_h) open(); -#if defined(POCO_WIN32_UTF8) - std::wstring utext; - UnicodeConverter::toUTF16(msg.getText(), utext); - const wchar_t* pMsg = utext.c_str(); - ReportEventW(_h, getType(msg), getCategory(msg), POCO_MSG_LOG, NULL, 1, 0, &pMsg, NULL); -#else - const char* pMsg = msg.getText().c_str(); - ReportEvent(_h, getType(msg), getCategory(msg), POCO_MSG_LOG, NULL, 1, 0, &pMsg, NULL); -#endif -} - - -void EventLogChannel::setProperty(const std::string& name, const std::string& value) -{ - if (icompare(name, PROP_NAME) == 0) - _name = value; - else if (icompare(name, PROP_HOST) == 0) - _host = value; - else if (icompare(name, PROP_LOGHOST) == 0) - _host = value; - else if (icompare(name, PROP_LOGFILE) == 0) - _logFile = value; - else - Channel::setProperty(name, value); -} - - -std::string EventLogChannel::getProperty(const std::string& name) const -{ - if (icompare(name, PROP_NAME) == 0) - return _name; - else if (icompare(name, PROP_HOST) == 0) - return _host; - else if (icompare(name, PROP_LOGHOST) == 0) - return _host; - else if (icompare(name, PROP_LOGFILE) == 0) - return _logFile; - else - return Channel::getProperty(name); -} - - -int EventLogChannel::getType(const Message& msg) -{ - switch (msg.getPriority()) - { - case Message::PRIO_TRACE: - case Message::PRIO_DEBUG: - case Message::PRIO_INFORMATION: - return EVENTLOG_INFORMATION_TYPE; - case Message::PRIO_NOTICE: - case Message::PRIO_WARNING: - return EVENTLOG_WARNING_TYPE; - default: - return EVENTLOG_ERROR_TYPE; - } -} - - -int EventLogChannel::getCategory(const Message& msg) -{ - switch (msg.getPriority()) - { - case Message::PRIO_TRACE: - return POCO_CTG_TRACE; - case Message::PRIO_DEBUG: - return POCO_CTG_DEBUG; - case Message::PRIO_INFORMATION: - return POCO_CTG_INFORMATION; - case Message::PRIO_NOTICE: - return POCO_CTG_NOTICE; - case Message::PRIO_WARNING: - return POCO_CTG_WARNING; - case Message::PRIO_ERROR: - return POCO_CTG_ERROR; - case Message::PRIO_CRITICAL: - return POCO_CTG_CRITICAL; - case Message::PRIO_FATAL: - return POCO_CTG_FATAL; - default: - return 0; - } -} - - -void EventLogChannel::setUpRegistry() const -{ - std::string key = "SYSTEM\\CurrentControlSet\\Services\\EventLog\\"; - key.append(_logFile); - key.append("\\"); - key.append(_name); - HKEY hKey; - DWORD disp; -#if defined(POCO_WIN32_UTF8) - std::wstring ukey; - UnicodeConverter::toUTF16(key, ukey); - DWORD rc = RegCreateKeyExW(HKEY_LOCAL_MACHINE, ukey.c_str(), 0, NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hKey, &disp); -#else - DWORD rc = RegCreateKeyEx(HKEY_LOCAL_MACHINE, key.c_str(), 0, NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hKey, &disp); -#endif - if (rc != ERROR_SUCCESS) return; - - if (disp == REG_CREATED_NEW_KEY) - { -#if defined(POCO_WIN32_UTF8) - std::wstring path; - #if defined(POCO_DLL) - #if defined(_DEBUG) - path = findLibrary(L"PocoFoundationd.dll"); - #else - path = findLibrary(L"PocoFoundation.dll"); - #endif - #endif - - if (path.empty()) - path = findLibrary(L"PocoMsg.dll"); -#else - std::string path; - #if defined(POCO_DLL) - #if defined(_DEBUG) - path = findLibrary("PocoFoundationd.dll"); - #else - path = findLibrary("PocoFoundation.dll"); - #endif - #endif - - if (path.empty()) - path = findLibrary("PocoMsg.dll"); -#endif - - if (!path.empty()) - { - DWORD count = 8; - DWORD types = 7; -#if defined(POCO_WIN32_UTF8) - RegSetValueExW(hKey, L"CategoryMessageFile", 0, REG_SZ, (const BYTE*) path.c_str(), (DWORD) path.size() + 1); - RegSetValueExW(hKey, L"EventMessageFile", 0, REG_SZ, (const BYTE*) path.c_str(), (DWORD) path.size() + 1); - RegSetValueExW(hKey, L"CategoryCount", 0, REG_DWORD, (const BYTE*) &count, (DWORD) sizeof(count)); - RegSetValueExW(hKey, L"TypesSupported", 0, REG_DWORD, (const BYTE*) &types, (DWORD) sizeof(types)); -#else - RegSetValueEx(hKey, "CategoryMessageFile", 0, REG_SZ, (const BYTE*) path.c_str(), (DWORD) path.size() + 1); - RegSetValueEx(hKey, "EventMessageFile", 0, REG_SZ, (const BYTE*) path.c_str(), (DWORD) path.size() + 1); - RegSetValueEx(hKey, "CategoryCount", 0, REG_DWORD, (const BYTE*) &count, (DWORD) sizeof(count)); - RegSetValueEx(hKey, "TypesSupported", 0, REG_DWORD, (const BYTE*) &types, (DWORD) sizeof(types)); -#endif - } - } - RegCloseKey(hKey); -} - - -#if defined(POCO_WIN32_UTF8) -std::wstring EventLogChannel::findLibrary(const wchar_t* name) -{ - std::wstring path; - HMODULE dll = LoadLibraryW(name); - if (dll) - { - wchar_t name[MAX_PATH + 1]; - int n = GetModuleFileNameW(dll, name, sizeof(name)); - if (n > 0) path = name; - FreeLibrary(dll); - } - return path; -} -#else -std::string EventLogChannel::findLibrary(const char* name) -{ - std::string path; - HMODULE dll = LoadLibrary(name); - if (dll) - { - char name[MAX_PATH + 1]; - int n = GetModuleFileName(dll, name, sizeof(name)); - if (n > 0) path = name; - FreeLibrary(dll); - } - return path; -} -#endif - - -} // namespace Poco +// +// EventLogChannel.cpp +// +// $Id: //poco/1.2/Foundation/src/EventLogChannel.cpp#2 $ +// +// Library: Foundation +// Package: Logging +// Module: EventLogChannel +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/EventLogChannel.h" +#include "Poco/Message.h" +#include "Poco/String.h" +#include "pocomsg.h" +#if defined(POCO_WIN32_UTF8) +#include "Poco/UnicodeConverter.h" +#endif + + +namespace Poco { + + +const std::string EventLogChannel::PROP_NAME = "name"; +const std::string EventLogChannel::PROP_HOST = "host"; +const std::string EventLogChannel::PROP_LOGHOST = "loghost"; +const std::string EventLogChannel::PROP_LOGFILE = "logfile"; + + +EventLogChannel::EventLogChannel(): + _logFile("Application"), + _h(0) +{ +#if defined(POCO_WIN32_UTF8) + wchar_t name[256]; + int n = GetModuleFileNameW(NULL, name, sizeof(name)); + if (n > 0) + { + wchar_t* end = name + n - 1; + while (end > name && *end != '\\') --end; + if (*end == '\\') ++end; + std::wstring uname(end); + UnicodeConverter::toUTF8(uname, _name); + } +#else + char name[256]; + int n = GetModuleFileName(NULL, name, sizeof(name)); + if (n > 0) + { + char* end = name + n - 1; + while (end > name && *end != '\\') --end; + if (*end == '\\') ++end; + _name = end; + } +#endif +} + + +EventLogChannel::EventLogChannel(const std::string& name): + _name(name), + _logFile("Application"), + _h(0) +{ +} + + +EventLogChannel::EventLogChannel(const std::string& name, const std::string& host): + _name(name), + _host(host), + _logFile("Application"), + _h(0) +{ +} + + +EventLogChannel::~EventLogChannel() +{ + close(); +} + + +void EventLogChannel::open() +{ + setUpRegistry(); +#if defined(POCO_WIN32_UTF8) + std::wstring uhost; + UnicodeConverter::toUTF16(_host, uhost); + std::wstring uname; + UnicodeConverter::toUTF16(_name, uname); + _h = RegisterEventSourceW(uhost.empty() ? NULL : uhost.c_str(), uname.c_str()); +#else + _h = RegisterEventSource(_host.empty() ? NULL : _host.c_str(), _name.c_str()); +#endif + if (!_h) throw SystemException("cannot register event source"); +} + + +void EventLogChannel::close() +{ + if (_h) DeregisterEventSource(_h); + _h = 0; +} + + +void EventLogChannel::log(const Message& msg) +{ + if (!_h) open(); +#if defined(POCO_WIN32_UTF8) + std::wstring utext; + UnicodeConverter::toUTF16(msg.getText(), utext); + const wchar_t* pMsg = utext.c_str(); + ReportEventW(_h, getType(msg), getCategory(msg), POCO_MSG_LOG, NULL, 1, 0, &pMsg, NULL); +#else + const char* pMsg = msg.getText().c_str(); + ReportEvent(_h, getType(msg), getCategory(msg), POCO_MSG_LOG, NULL, 1, 0, &pMsg, NULL); +#endif +} + + +void EventLogChannel::setProperty(const std::string& name, const std::string& value) +{ + if (icompare(name, PROP_NAME) == 0) + _name = value; + else if (icompare(name, PROP_HOST) == 0) + _host = value; + else if (icompare(name, PROP_LOGHOST) == 0) + _host = value; + else if (icompare(name, PROP_LOGFILE) == 0) + _logFile = value; + else + Channel::setProperty(name, value); +} + + +std::string EventLogChannel::getProperty(const std::string& name) const +{ + if (icompare(name, PROP_NAME) == 0) + return _name; + else if (icompare(name, PROP_HOST) == 0) + return _host; + else if (icompare(name, PROP_LOGHOST) == 0) + return _host; + else if (icompare(name, PROP_LOGFILE) == 0) + return _logFile; + else + return Channel::getProperty(name); +} + + +int EventLogChannel::getType(const Message& msg) +{ + switch (msg.getPriority()) + { + case Message::PRIO_TRACE: + case Message::PRIO_DEBUG: + case Message::PRIO_INFORMATION: + return EVENTLOG_INFORMATION_TYPE; + case Message::PRIO_NOTICE: + case Message::PRIO_WARNING: + return EVENTLOG_WARNING_TYPE; + default: + return EVENTLOG_ERROR_TYPE; + } +} + + +int EventLogChannel::getCategory(const Message& msg) +{ + switch (msg.getPriority()) + { + case Message::PRIO_TRACE: + return POCO_CTG_TRACE; + case Message::PRIO_DEBUG: + return POCO_CTG_DEBUG; + case Message::PRIO_INFORMATION: + return POCO_CTG_INFORMATION; + case Message::PRIO_NOTICE: + return POCO_CTG_NOTICE; + case Message::PRIO_WARNING: + return POCO_CTG_WARNING; + case Message::PRIO_ERROR: + return POCO_CTG_ERROR; + case Message::PRIO_CRITICAL: + return POCO_CTG_CRITICAL; + case Message::PRIO_FATAL: + return POCO_CTG_FATAL; + default: + return 0; + } +} + + +void EventLogChannel::setUpRegistry() const +{ + std::string key = "SYSTEM\\CurrentControlSet\\Services\\EventLog\\"; + key.append(_logFile); + key.append("\\"); + key.append(_name); + HKEY hKey; + DWORD disp; +#if defined(POCO_WIN32_UTF8) + std::wstring ukey; + UnicodeConverter::toUTF16(key, ukey); + DWORD rc = RegCreateKeyExW(HKEY_LOCAL_MACHINE, ukey.c_str(), 0, NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hKey, &disp); +#else + DWORD rc = RegCreateKeyEx(HKEY_LOCAL_MACHINE, key.c_str(), 0, NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hKey, &disp); +#endif + if (rc != ERROR_SUCCESS) return; + + if (disp == REG_CREATED_NEW_KEY) + { +#if defined(POCO_WIN32_UTF8) + std::wstring path; + #if defined(POCO_DLL) + #if defined(_DEBUG) + path = findLibrary(L"PocoFoundationd.dll"); + #else + path = findLibrary(L"PocoFoundation.dll"); + #endif + #endif + + if (path.empty()) + path = findLibrary(L"PocoMsg.dll"); +#else + std::string path; + #if defined(POCO_DLL) + #if defined(_DEBUG) + path = findLibrary("PocoFoundationd.dll"); + #else + path = findLibrary("PocoFoundation.dll"); + #endif + #endif + + if (path.empty()) + path = findLibrary("PocoMsg.dll"); +#endif + + if (!path.empty()) + { + DWORD count = 8; + DWORD types = 7; +#if defined(POCO_WIN32_UTF8) + RegSetValueExW(hKey, L"CategoryMessageFile", 0, REG_SZ, (const BYTE*) path.c_str(), (DWORD) path.size() + 1); + RegSetValueExW(hKey, L"EventMessageFile", 0, REG_SZ, (const BYTE*) path.c_str(), (DWORD) path.size() + 1); + RegSetValueExW(hKey, L"CategoryCount", 0, REG_DWORD, (const BYTE*) &count, (DWORD) sizeof(count)); + RegSetValueExW(hKey, L"TypesSupported", 0, REG_DWORD, (const BYTE*) &types, (DWORD) sizeof(types)); +#else + RegSetValueEx(hKey, "CategoryMessageFile", 0, REG_SZ, (const BYTE*) path.c_str(), (DWORD) path.size() + 1); + RegSetValueEx(hKey, "EventMessageFile", 0, REG_SZ, (const BYTE*) path.c_str(), (DWORD) path.size() + 1); + RegSetValueEx(hKey, "CategoryCount", 0, REG_DWORD, (const BYTE*) &count, (DWORD) sizeof(count)); + RegSetValueEx(hKey, "TypesSupported", 0, REG_DWORD, (const BYTE*) &types, (DWORD) sizeof(types)); +#endif + } + } + RegCloseKey(hKey); +} + + +#if defined(POCO_WIN32_UTF8) +std::wstring EventLogChannel::findLibrary(const wchar_t* name) +{ + std::wstring path; + HMODULE dll = LoadLibraryW(name); + if (dll) + { + wchar_t name[MAX_PATH + 1]; + int n = GetModuleFileNameW(dll, name, sizeof(name)); + if (n > 0) path = name; + FreeLibrary(dll); + } + return path; +} +#else +std::string EventLogChannel::findLibrary(const char* name) +{ + std::string path; + HMODULE dll = LoadLibrary(name); + if (dll) + { + char name[MAX_PATH + 1]; + int n = GetModuleFileName(dll, name, sizeof(name)); + if (n > 0) path = name; + FreeLibrary(dll); + } + return path; +} +#endif + + +} // namespace Poco diff --git a/Foundation/src/Event_POSIX.cpp b/Foundation/src/Event_POSIX.cpp index 5c711aa6a..7bfe52e29 100644 --- a/Foundation/src/Event_POSIX.cpp +++ b/Foundation/src/Event_POSIX.cpp @@ -1,117 +1,117 @@ -// -// Event_POSIX.cpp -// -// $Id: //poco/1.2/Foundation/src/Event_POSIX.cpp#1 $ -// -// Library: Foundation -// Package: Threading -// Module: Event -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/Event_POSIX.h" -#include - - -namespace Poco { - - -EventImpl::EventImpl(bool autoReset): _auto(autoReset), _state(false) -{ - if (pthread_mutex_init(&_mutex, NULL)) - throw SystemException("cannot create event (mutex)"); - if (pthread_cond_init(&_cond, NULL)) - throw SystemException("cannot create event (condition)"); -} - - -EventImpl::~EventImpl() -{ - pthread_cond_destroy(&_cond); - pthread_mutex_destroy(&_mutex); -} - - -void EventImpl::waitImpl() -{ - if (pthread_mutex_lock(&_mutex)) - throw SystemException("wait for event failed (lock)"); - while (!_state) - { - if (pthread_cond_wait(&_cond, &_mutex)) - { - pthread_mutex_unlock(&_mutex); - throw SystemException("wait for event failed"); - } - } - if (_auto) - _state = false; - pthread_mutex_unlock(&_mutex); -} - - -bool EventImpl::waitImpl(long milliseconds) -{ - int rc = 0; - struct timespec abstime; - -#if defined(__VMS) - struct timespec delta; - delta.tv_sec = milliseconds / 1000; - delta.tv_nsec = (milliseconds % 1000)*1000000; - pthread_get_expiration_np(&delta, &abstime); -#else - struct timeval tv; - gettimeofday(&tv, NULL); - abstime.tv_sec = tv.tv_sec + milliseconds / 1000; - abstime.tv_nsec = tv.tv_usec*1000 + (milliseconds % 1000)*1000000; - if (abstime.tv_nsec >= 1000000000) - { - abstime.tv_nsec -= 1000000000; - abstime.tv_sec++; - } -#endif - - if (pthread_mutex_lock(&_mutex) != 0) - throw SystemException("wait for event failed (lock)"); - while (!_state) - { - if ((rc = pthread_cond_timedwait(&_cond, &_mutex, &abstime))) - { - if (rc == ETIMEDOUT) break; - pthread_mutex_unlock(&_mutex); - throw SystemException("cannot wait for event"); - } - } - if (rc == 0 && _auto) _state = false; - pthread_mutex_unlock(&_mutex); - return rc == 0; -} - - -} // namespace Poco +// +// Event_POSIX.cpp +// +// $Id: //poco/1.2/Foundation/src/Event_POSIX.cpp#1 $ +// +// Library: Foundation +// Package: Threading +// Module: Event +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/Event_POSIX.h" +#include + + +namespace Poco { + + +EventImpl::EventImpl(bool autoReset): _auto(autoReset), _state(false) +{ + if (pthread_mutex_init(&_mutex, NULL)) + throw SystemException("cannot create event (mutex)"); + if (pthread_cond_init(&_cond, NULL)) + throw SystemException("cannot create event (condition)"); +} + + +EventImpl::~EventImpl() +{ + pthread_cond_destroy(&_cond); + pthread_mutex_destroy(&_mutex); +} + + +void EventImpl::waitImpl() +{ + if (pthread_mutex_lock(&_mutex)) + throw SystemException("wait for event failed (lock)"); + while (!_state) + { + if (pthread_cond_wait(&_cond, &_mutex)) + { + pthread_mutex_unlock(&_mutex); + throw SystemException("wait for event failed"); + } + } + if (_auto) + _state = false; + pthread_mutex_unlock(&_mutex); +} + + +bool EventImpl::waitImpl(long milliseconds) +{ + int rc = 0; + struct timespec abstime; + +#if defined(__VMS) + struct timespec delta; + delta.tv_sec = milliseconds / 1000; + delta.tv_nsec = (milliseconds % 1000)*1000000; + pthread_get_expiration_np(&delta, &abstime); +#else + struct timeval tv; + gettimeofday(&tv, NULL); + abstime.tv_sec = tv.tv_sec + milliseconds / 1000; + abstime.tv_nsec = tv.tv_usec*1000 + (milliseconds % 1000)*1000000; + if (abstime.tv_nsec >= 1000000000) + { + abstime.tv_nsec -= 1000000000; + abstime.tv_sec++; + } +#endif + + if (pthread_mutex_lock(&_mutex) != 0) + throw SystemException("wait for event failed (lock)"); + while (!_state) + { + if ((rc = pthread_cond_timedwait(&_cond, &_mutex, &abstime))) + { + if (rc == ETIMEDOUT) break; + pthread_mutex_unlock(&_mutex); + throw SystemException("cannot wait for event"); + } + } + if (rc == 0 && _auto) _state = false; + pthread_mutex_unlock(&_mutex); + return rc == 0; +} + + +} // namespace Poco diff --git a/Foundation/src/Event_WIN32.cpp b/Foundation/src/Event_WIN32.cpp index 634a3f3e3..a60ed9bf5 100644 --- a/Foundation/src/Event_WIN32.cpp +++ b/Foundation/src/Event_WIN32.cpp @@ -1,83 +1,83 @@ -// -// Event_WIN32.cpp -// -// $Id: //poco/1.2/Foundation/src/Event_WIN32.cpp#1 $ -// -// Library: Foundation -// Package: Threading -// Module: Event -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/Event_WIN32.h" - - -namespace Poco { - - -EventImpl::EventImpl(bool autoReset) -{ - _event = CreateEvent(NULL, autoReset ? FALSE : TRUE, FALSE, NULL); - if (!_event) - throw SystemException("cannot create event"); -} - - -EventImpl::~EventImpl() -{ - CloseHandle(_event); -} - - -void EventImpl::waitImpl() -{ - switch (WaitForSingleObject(_event, INFINITE)) - { - case WAIT_OBJECT_0: - return; - default: - throw SystemException("wait for event failed"); - } -} - - -bool EventImpl::waitImpl(long milliseconds) -{ - switch (WaitForSingleObject(_event, milliseconds + 1)) - { - case WAIT_TIMEOUT: - return false; - case WAIT_OBJECT_0: - return true; - default: - throw SystemException("wait for event failed"); - } -} - - -} // namespace Poco +// +// Event_WIN32.cpp +// +// $Id: //poco/1.2/Foundation/src/Event_WIN32.cpp#1 $ +// +// Library: Foundation +// Package: Threading +// Module: Event +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/Event_WIN32.h" + + +namespace Poco { + + +EventImpl::EventImpl(bool autoReset) +{ + _event = CreateEvent(NULL, autoReset ? FALSE : TRUE, FALSE, NULL); + if (!_event) + throw SystemException("cannot create event"); +} + + +EventImpl::~EventImpl() +{ + CloseHandle(_event); +} + + +void EventImpl::waitImpl() +{ + switch (WaitForSingleObject(_event, INFINITE)) + { + case WAIT_OBJECT_0: + return; + default: + throw SystemException("wait for event failed"); + } +} + + +bool EventImpl::waitImpl(long milliseconds) +{ + switch (WaitForSingleObject(_event, milliseconds + 1)) + { + case WAIT_TIMEOUT: + return false; + case WAIT_OBJECT_0: + return true; + default: + throw SystemException("wait for event failed"); + } +} + + +} // namespace Poco diff --git a/Foundation/src/Exception.cpp b/Foundation/src/Exception.cpp index 561f4db86..f5a25c23d 100644 --- a/Foundation/src/Exception.cpp +++ b/Foundation/src/Exception.cpp @@ -1,184 +1,184 @@ -// -// Exception.cpp -// -// $Id: //poco/1.2/Foundation/src/Exception.cpp#1 $ -// -// Library: Foundation -// Package: Core -// Module: Exception -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/Exception.h" -#include - - -namespace Poco { - - -Exception::Exception(): _pNested(0) -{ -} - - -Exception::Exception(const std::string& msg): _msg(msg), _pNested(0) -{ -} - - -Exception::Exception(const std::string& msg, const std::string& arg): _msg(msg), _pNested(0) -{ - if (!arg.empty()) - { - _msg.append(": "); - _msg.append(arg); - } -} - - -Exception::Exception(const std::string& msg, const Exception& nested): _msg(msg), _pNested(nested.clone()) -{ -} - - -Exception::Exception(const Exception& exc): std::exception(exc) -{ - _msg = exc._msg; - _pNested = exc._pNested ? exc._pNested->clone() : 0; -} - - -Exception::~Exception() throw() -{ - delete _pNested; -} - - -Exception& Exception::operator = (const Exception& exc) -{ - if (&exc != this) - { - delete _pNested; - _msg = exc._msg; - _pNested = exc._pNested ? exc._pNested->clone() : 0; - } - return *this; -} - - -const char* Exception::name() const throw() -{ - return "Exception"; -} - - -const char* Exception::className() const throw() -{ - return typeid(*this).name(); -} - - -const char* Exception::what() const throw() -{ - return _msg.c_str(); -} - - -std::string Exception::displayText() const -{ - std::string txt = name(); - if (!_msg.empty()) - { - txt.append(": "); - txt.append(_msg); - } - return txt; -} - - -Exception* Exception::clone() const -{ - return new Exception(*this); -} - - -void Exception::rethrow() const -{ - throw *this; -} - - -POCO_IMPLEMENT_EXCEPTION(LogicException, Exception, "Logic exception") -POCO_IMPLEMENT_EXCEPTION(AssertionViolationException, LogicException, "Assertion violation") -POCO_IMPLEMENT_EXCEPTION(NullPointerException, LogicException, "Null pointer") -POCO_IMPLEMENT_EXCEPTION(BugcheckException, LogicException, "Bugcheck") -POCO_IMPLEMENT_EXCEPTION(InvalidArgumentException, LogicException, "Invalid argument") -POCO_IMPLEMENT_EXCEPTION(NotImplementedException, LogicException, "Not implemented") -POCO_IMPLEMENT_EXCEPTION(RangeException, LogicException, "Out of range") -POCO_IMPLEMENT_EXCEPTION(IllegalStateException, LogicException, "Illegal state") -POCO_IMPLEMENT_EXCEPTION(InvalidAccessException, LogicException, "Invalid access") -POCO_IMPLEMENT_EXCEPTION(SignalException, LogicException, "Signal received") -POCO_IMPLEMENT_EXCEPTION(UnhandledException, LogicException, "Signal received") - -POCO_IMPLEMENT_EXCEPTION(RuntimeException, Exception, "Runtime exception") -POCO_IMPLEMENT_EXCEPTION(NotFoundException, RuntimeException, "Not found") -POCO_IMPLEMENT_EXCEPTION(ExistsException, RuntimeException, "Exists") -POCO_IMPLEMENT_EXCEPTION(TimeoutException, RuntimeException, "Timeout") -POCO_IMPLEMENT_EXCEPTION(SystemException, RuntimeException, "System exception") -POCO_IMPLEMENT_EXCEPTION(RegularExpressionException, RuntimeException, "Error in regular exception") -POCO_IMPLEMENT_EXCEPTION(LibraryLoadException, RuntimeException, "Cannot load library") -POCO_IMPLEMENT_EXCEPTION(LibraryAlreadyLoadedException, RuntimeException, "Library already loaded") -POCO_IMPLEMENT_EXCEPTION(NoThreadAvailableException, RuntimeException, "No thread available") -POCO_IMPLEMENT_EXCEPTION(PropertyNotSupportedException, RuntimeException, "Property not supported") -POCO_IMPLEMENT_EXCEPTION(PoolOverflowException, RuntimeException, "Pool overflow") -POCO_IMPLEMENT_EXCEPTION(NoPermissionException, RuntimeException, "No permission") -POCO_IMPLEMENT_EXCEPTION(OutOfMemoryException, RuntimeException, "Out of memory") -POCO_IMPLEMENT_EXCEPTION(DataException, RuntimeException, "Data error") - -POCO_IMPLEMENT_EXCEPTION(DataFormatException, DataException, "Bad data format") -POCO_IMPLEMENT_EXCEPTION(SyntaxException, DataException, "Syntax error") -POCO_IMPLEMENT_EXCEPTION(CircularReferenceException, DataException, "Circular reference") -POCO_IMPLEMENT_EXCEPTION(PathSyntaxException, SyntaxException, "Bad path syntax") -POCO_IMPLEMENT_EXCEPTION(IOException, RuntimeException, "I/O error") -POCO_IMPLEMENT_EXCEPTION(FileException, IOException, "File access error") -POCO_IMPLEMENT_EXCEPTION(FileExistsException, FileException, "File exists") -POCO_IMPLEMENT_EXCEPTION(FileNotFoundException, FileException, "File not found") -POCO_IMPLEMENT_EXCEPTION(PathNotFoundException, FileException, "Path not found") -POCO_IMPLEMENT_EXCEPTION(FileReadOnlyException, FileException, "File is read-only") -POCO_IMPLEMENT_EXCEPTION(FileAccessDeniedException, FileException, "Access to file denied") -POCO_IMPLEMENT_EXCEPTION(CreateFileException, FileException, "Cannot create file") -POCO_IMPLEMENT_EXCEPTION(OpenFileException, FileException, "Cannot open file") -POCO_IMPLEMENT_EXCEPTION(WriteFileException, FileException, "Cannot write file") -POCO_IMPLEMENT_EXCEPTION(ReadFileException, FileException, "Cannot read file") -POCO_IMPLEMENT_EXCEPTION(UnknownURISchemeException, RuntimeException, "Unknown URI scheme") - - -POCO_IMPLEMENT_EXCEPTION(ApplicationException, Exception, "Application exception") -POCO_IMPLEMENT_EXCEPTION(BadCastException, RuntimeException, "Bad cast exception") - -} // namespace Poco +// +// Exception.cpp +// +// $Id: //poco/1.2/Foundation/src/Exception.cpp#1 $ +// +// Library: Foundation +// Package: Core +// Module: Exception +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/Exception.h" +#include + + +namespace Poco { + + +Exception::Exception(): _pNested(0) +{ +} + + +Exception::Exception(const std::string& msg): _msg(msg), _pNested(0) +{ +} + + +Exception::Exception(const std::string& msg, const std::string& arg): _msg(msg), _pNested(0) +{ + if (!arg.empty()) + { + _msg.append(": "); + _msg.append(arg); + } +} + + +Exception::Exception(const std::string& msg, const Exception& nested): _msg(msg), _pNested(nested.clone()) +{ +} + + +Exception::Exception(const Exception& exc): std::exception(exc) +{ + _msg = exc._msg; + _pNested = exc._pNested ? exc._pNested->clone() : 0; +} + + +Exception::~Exception() throw() +{ + delete _pNested; +} + + +Exception& Exception::operator = (const Exception& exc) +{ + if (&exc != this) + { + delete _pNested; + _msg = exc._msg; + _pNested = exc._pNested ? exc._pNested->clone() : 0; + } + return *this; +} + + +const char* Exception::name() const throw() +{ + return "Exception"; +} + + +const char* Exception::className() const throw() +{ + return typeid(*this).name(); +} + + +const char* Exception::what() const throw() +{ + return _msg.c_str(); +} + + +std::string Exception::displayText() const +{ + std::string txt = name(); + if (!_msg.empty()) + { + txt.append(": "); + txt.append(_msg); + } + return txt; +} + + +Exception* Exception::clone() const +{ + return new Exception(*this); +} + + +void Exception::rethrow() const +{ + throw *this; +} + + +POCO_IMPLEMENT_EXCEPTION(LogicException, Exception, "Logic exception") +POCO_IMPLEMENT_EXCEPTION(AssertionViolationException, LogicException, "Assertion violation") +POCO_IMPLEMENT_EXCEPTION(NullPointerException, LogicException, "Null pointer") +POCO_IMPLEMENT_EXCEPTION(BugcheckException, LogicException, "Bugcheck") +POCO_IMPLEMENT_EXCEPTION(InvalidArgumentException, LogicException, "Invalid argument") +POCO_IMPLEMENT_EXCEPTION(NotImplementedException, LogicException, "Not implemented") +POCO_IMPLEMENT_EXCEPTION(RangeException, LogicException, "Out of range") +POCO_IMPLEMENT_EXCEPTION(IllegalStateException, LogicException, "Illegal state") +POCO_IMPLEMENT_EXCEPTION(InvalidAccessException, LogicException, "Invalid access") +POCO_IMPLEMENT_EXCEPTION(SignalException, LogicException, "Signal received") +POCO_IMPLEMENT_EXCEPTION(UnhandledException, LogicException, "Signal received") + +POCO_IMPLEMENT_EXCEPTION(RuntimeException, Exception, "Runtime exception") +POCO_IMPLEMENT_EXCEPTION(NotFoundException, RuntimeException, "Not found") +POCO_IMPLEMENT_EXCEPTION(ExistsException, RuntimeException, "Exists") +POCO_IMPLEMENT_EXCEPTION(TimeoutException, RuntimeException, "Timeout") +POCO_IMPLEMENT_EXCEPTION(SystemException, RuntimeException, "System exception") +POCO_IMPLEMENT_EXCEPTION(RegularExpressionException, RuntimeException, "Error in regular exception") +POCO_IMPLEMENT_EXCEPTION(LibraryLoadException, RuntimeException, "Cannot load library") +POCO_IMPLEMENT_EXCEPTION(LibraryAlreadyLoadedException, RuntimeException, "Library already loaded") +POCO_IMPLEMENT_EXCEPTION(NoThreadAvailableException, RuntimeException, "No thread available") +POCO_IMPLEMENT_EXCEPTION(PropertyNotSupportedException, RuntimeException, "Property not supported") +POCO_IMPLEMENT_EXCEPTION(PoolOverflowException, RuntimeException, "Pool overflow") +POCO_IMPLEMENT_EXCEPTION(NoPermissionException, RuntimeException, "No permission") +POCO_IMPLEMENT_EXCEPTION(OutOfMemoryException, RuntimeException, "Out of memory") +POCO_IMPLEMENT_EXCEPTION(DataException, RuntimeException, "Data error") + +POCO_IMPLEMENT_EXCEPTION(DataFormatException, DataException, "Bad data format") +POCO_IMPLEMENT_EXCEPTION(SyntaxException, DataException, "Syntax error") +POCO_IMPLEMENT_EXCEPTION(CircularReferenceException, DataException, "Circular reference") +POCO_IMPLEMENT_EXCEPTION(PathSyntaxException, SyntaxException, "Bad path syntax") +POCO_IMPLEMENT_EXCEPTION(IOException, RuntimeException, "I/O error") +POCO_IMPLEMENT_EXCEPTION(FileException, IOException, "File access error") +POCO_IMPLEMENT_EXCEPTION(FileExistsException, FileException, "File exists") +POCO_IMPLEMENT_EXCEPTION(FileNotFoundException, FileException, "File not found") +POCO_IMPLEMENT_EXCEPTION(PathNotFoundException, FileException, "Path not found") +POCO_IMPLEMENT_EXCEPTION(FileReadOnlyException, FileException, "File is read-only") +POCO_IMPLEMENT_EXCEPTION(FileAccessDeniedException, FileException, "Access to file denied") +POCO_IMPLEMENT_EXCEPTION(CreateFileException, FileException, "Cannot create file") +POCO_IMPLEMENT_EXCEPTION(OpenFileException, FileException, "Cannot open file") +POCO_IMPLEMENT_EXCEPTION(WriteFileException, FileException, "Cannot write file") +POCO_IMPLEMENT_EXCEPTION(ReadFileException, FileException, "Cannot read file") +POCO_IMPLEMENT_EXCEPTION(UnknownURISchemeException, RuntimeException, "Unknown URI scheme") + + +POCO_IMPLEMENT_EXCEPTION(ApplicationException, Exception, "Application exception") +POCO_IMPLEMENT_EXCEPTION(BadCastException, RuntimeException, "Bad cast exception") + +} // namespace Poco diff --git a/Foundation/src/FPEnvironment.cpp b/Foundation/src/FPEnvironment.cpp index 105b215ce..5d989cf0e 100644 --- a/Foundation/src/FPEnvironment.cpp +++ b/Foundation/src/FPEnvironment.cpp @@ -1,107 +1,107 @@ -// -// FPEnvironment.cpp -// -// $Id: //poco/1.2/Foundation/src/FPEnvironment.cpp#1 $ -// -// Library: Foundation -// Package: Core -// Module: FPEnvironment -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -// pull in platform identification macros needed below -#include "Poco/Platform.h" - - -#if defined(POCO_NO_FPENVIRONMENT) -#include "FPEnvironment_DUMMY.cpp" -#elif defined(__osf__) || defined(__VMS) -#include "FPEnvironment_DEC.cpp" -#elif defined(sun) || defined(__sun) -#include "FPEnvironment_SUN.cpp" -#elif defined(POCO_OS_FAMILY_UNIX) -#include "FPEnvironment_C99.cpp" -#elif defined(POCO_OS_FAMILY_WINDOWS) -#include "FPEnvironment_WIN32.cpp" -#else -#include "FPEnvironment_DUMMY.cpp" -#endif - - -// header file must be included after platform-specific part -// due to _XOPEN_SOURCE conflict on Tru64 (see FPEnvironment_DEC.cpp) -#include "Poco/FPEnvironment.h" - - -namespace Poco { - - -FPEnvironment::FPEnvironment() -{ -} - - -FPEnvironment::FPEnvironment(RoundingMode rm) -{ - setRoundingMode(rm); -} - - -FPEnvironment::FPEnvironment(const FPEnvironment& env): FPEnvironmentImpl(env) -{ -} - - -FPEnvironment::~FPEnvironment() -{ -} - - -FPEnvironment& FPEnvironment::operator = (const FPEnvironment& env) -{ - if (&env != this) - { - FPEnvironmentImpl::operator = (env); - } - return *this; -} - - -void FPEnvironment::keepCurrent() -{ - keepCurrentImpl(); -} - - -void FPEnvironment::clearFlags() -{ - clearFlagsImpl(); -} - - -} // namespace Poco +// +// FPEnvironment.cpp +// +// $Id: //poco/1.2/Foundation/src/FPEnvironment.cpp#1 $ +// +// Library: Foundation +// Package: Core +// Module: FPEnvironment +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +// pull in platform identification macros needed below +#include "Poco/Platform.h" + + +#if defined(POCO_NO_FPENVIRONMENT) +#include "FPEnvironment_DUMMY.cpp" +#elif defined(__osf__) || defined(__VMS) +#include "FPEnvironment_DEC.cpp" +#elif defined(sun) || defined(__sun) +#include "FPEnvironment_SUN.cpp" +#elif defined(POCO_OS_FAMILY_UNIX) +#include "FPEnvironment_C99.cpp" +#elif defined(POCO_OS_FAMILY_WINDOWS) +#include "FPEnvironment_WIN32.cpp" +#else +#include "FPEnvironment_DUMMY.cpp" +#endif + + +// header file must be included after platform-specific part +// due to _XOPEN_SOURCE conflict on Tru64 (see FPEnvironment_DEC.cpp) +#include "Poco/FPEnvironment.h" + + +namespace Poco { + + +FPEnvironment::FPEnvironment() +{ +} + + +FPEnvironment::FPEnvironment(RoundingMode rm) +{ + setRoundingMode(rm); +} + + +FPEnvironment::FPEnvironment(const FPEnvironment& env): FPEnvironmentImpl(env) +{ +} + + +FPEnvironment::~FPEnvironment() +{ +} + + +FPEnvironment& FPEnvironment::operator = (const FPEnvironment& env) +{ + if (&env != this) + { + FPEnvironmentImpl::operator = (env); + } + return *this; +} + + +void FPEnvironment::keepCurrent() +{ + keepCurrentImpl(); +} + + +void FPEnvironment::clearFlags() +{ + clearFlagsImpl(); +} + + +} // namespace Poco diff --git a/Foundation/src/FPEnvironment_C99.cpp b/Foundation/src/FPEnvironment_C99.cpp index f7aa0641f..ef29086c1 100644 --- a/Foundation/src/FPEnvironment_C99.cpp +++ b/Foundation/src/FPEnvironment_C99.cpp @@ -1,104 +1,104 @@ -// -// FPEnvironment_C99.cpp -// -// $Id: //poco/1.2/Foundation/src/FPEnvironment_C99.cpp#1 $ -// -// Library: Foundation -// Package: Core -// Module: FPEnvironment -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/FPEnvironment_C99.h" - - -namespace Poco { - - -FPEnvironmentImpl::FPEnvironmentImpl() -{ - fegetenv(&_env); -} - - -FPEnvironmentImpl::FPEnvironmentImpl(const FPEnvironmentImpl& env) -{ - _env = env._env; -} - - -FPEnvironmentImpl::~FPEnvironmentImpl() -{ - fesetenv(&_env); -} - - -FPEnvironmentImpl& FPEnvironmentImpl::operator = (const FPEnvironmentImpl& env) -{ - _env = env._env; - return *this; -} - - -void FPEnvironmentImpl::keepCurrentImpl() -{ - fegetenv(&_env); -} - - -void FPEnvironmentImpl::clearFlagsImpl() -{ - feclearexcept(FE_ALL_EXCEPT); -} - - -bool FPEnvironmentImpl::isFlagImpl(FlagImpl flag) -{ - return fetestexcept(flag) != 0; -} - - -void FPEnvironmentImpl::setRoundingModeImpl(RoundingModeImpl mode) -{ - fesetround(mode); -} - - -FPEnvironmentImpl::RoundingModeImpl FPEnvironmentImpl::getRoundingModeImpl() -{ - return (RoundingModeImpl) fegetround(); -} - - -long double FPEnvironmentImpl::copySignImpl(long double target, long double source) -{ - return (source >= 0 && target >= 0) || (source < 0 && target < 0) ? target : -target; -} - - -} // namespace Poco +// +// FPEnvironment_C99.cpp +// +// $Id: //poco/1.2/Foundation/src/FPEnvironment_C99.cpp#1 $ +// +// Library: Foundation +// Package: Core +// Module: FPEnvironment +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/FPEnvironment_C99.h" + + +namespace Poco { + + +FPEnvironmentImpl::FPEnvironmentImpl() +{ + fegetenv(&_env); +} + + +FPEnvironmentImpl::FPEnvironmentImpl(const FPEnvironmentImpl& env) +{ + _env = env._env; +} + + +FPEnvironmentImpl::~FPEnvironmentImpl() +{ + fesetenv(&_env); +} + + +FPEnvironmentImpl& FPEnvironmentImpl::operator = (const FPEnvironmentImpl& env) +{ + _env = env._env; + return *this; +} + + +void FPEnvironmentImpl::keepCurrentImpl() +{ + fegetenv(&_env); +} + + +void FPEnvironmentImpl::clearFlagsImpl() +{ + feclearexcept(FE_ALL_EXCEPT); +} + + +bool FPEnvironmentImpl::isFlagImpl(FlagImpl flag) +{ + return fetestexcept(flag) != 0; +} + + +void FPEnvironmentImpl::setRoundingModeImpl(RoundingModeImpl mode) +{ + fesetround(mode); +} + + +FPEnvironmentImpl::RoundingModeImpl FPEnvironmentImpl::getRoundingModeImpl() +{ + return (RoundingModeImpl) fegetround(); +} + + +long double FPEnvironmentImpl::copySignImpl(long double target, long double source) +{ + return (source >= 0 && target >= 0) || (source < 0 && target < 0) ? target : -target; +} + + +} // namespace Poco diff --git a/Foundation/src/FPEnvironment_DEC.cpp b/Foundation/src/FPEnvironment_DEC.cpp index 24b26ef99..693dfb7f8 100644 --- a/Foundation/src/FPEnvironment_DEC.cpp +++ b/Foundation/src/FPEnvironment_DEC.cpp @@ -1,217 +1,217 @@ -// -// FPEnvironment_DEC.cpp -// -// $Id: //poco/1.2/Foundation/src/FPEnvironment_DEC.cpp#1 $ -// -// Library: Foundation -// Package: Core -// Module: FPEnvironment -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -// -// _XOPEN_SOURCE disables the ieee fp functions -// in , therefore we undefine it for this file. -// -#undef _XOPEN_SOURCE - - -#include -#include -#include -#if defined(__VMS) -#include -#endif -#include "Poco/FPEnvironment_DEC.h" - - -namespace Poco { - - -FPEnvironmentImpl::FPEnvironmentImpl() -{ -#if defined(__VMS) - #pragma pointer_size save - #pragma pointer_size 32 - struct _ieee env; - sys$ieee_set_fp_control(0, 0, &env); - #pragma pointer_size restore - _env = env; -#else - _env = ieee_get_fp_control(); -#endif -} - - -FPEnvironmentImpl::FPEnvironmentImpl(const FPEnvironmentImpl& env) -{ - _env = env._env; -} - - -FPEnvironmentImpl::~FPEnvironmentImpl() -{ -#if defined(__VMS) - #pragma pointer_size save - #pragma pointer_size 32 - struct _ieee mask; - mask.ieee$q_flags = 0xFFFFFFFFFFFFFFFF; - struct _ieee env = _env; - sys$ieee_set_fp_control(&mask, &env, 0); - #pragma pointer_size restore -#else - ieee_set_fp_control(_env); -#endif -} - - -FPEnvironmentImpl& FPEnvironmentImpl::operator = (const FPEnvironmentImpl& env) -{ - _env = env._env; - return *this; -} - - -bool FPEnvironmentImpl::isInfiniteImpl(float value) -{ - int cls = fp_classf(value); - return cls == FP_POS_INF || cls == FP_NEG_INF; -} - - -bool FPEnvironmentImpl::isInfiniteImpl(double value) -{ - int cls = fp_class(value); - return cls == FP_POS_INF || cls == FP_NEG_INF; -} - - -bool FPEnvironmentImpl::isInfiniteImpl(long double value) -{ - int cls = fp_classl(value); - return cls == FP_POS_INF || cls == FP_NEG_INF; -} - - -bool FPEnvironmentImpl::isNaNImpl(float value) -{ - return isnanf(value) != 0; -} - - -bool FPEnvironmentImpl::isNaNImpl(double value) -{ - return isnan(value) != 0; -} - - -bool FPEnvironmentImpl::isNaNImpl(long double value) -{ - return isnanl(value) != 0; -} - - -float FPEnvironmentImpl::copySignImpl(float target, float source) -{ - return copysignf(target, source); -} - - -double FPEnvironmentImpl::copySignImpl(double target, double source) -{ - return copysign(target, source); -} - - -long double FPEnvironmentImpl::copySignImpl(long double target, long double source) -{ - return copysignl(target, source); -} - - -void FPEnvironmentImpl::keepCurrentImpl() -{ -#if defined(__VMS) - #pragma pointer_size save - #pragma pointer_size 32 - struct _ieee env; - sys$ieee_set_fp_control(0, 0, &env); - #pragma pointer_size restore - _env = env; -#else - ieee_set_fp_control(_env); -#endif -} - - -void FPEnvironmentImpl::clearFlagsImpl() -{ -#if defined(__VMS) - #pragma pointer_size save - #pragma pointer_size 32 - struct _ieee mask; - mask.ieee$q_flags = 0xFFFFFFFFFFFFFFFF; - struct _ieee clr; - clr.ieee$q_flags = 0; - sys$ieee_set_fp_control(&mask, &clr, 0); - #pragma pointer_size restore -#else - ieee_set_fp_control(0); -#endif -} - - -bool FPEnvironmentImpl::isFlagImpl(FlagImpl flag) -{ -#if defined(__VMS) - #pragma pointer_size save - #pragma pointer_size 32 - struct _ieee flags; - sys$ieee_set_fp_control(0, 0, &flags); - return (flags.ieee$q_flags & flag) != 0; - #pragma pointer_size restore -#else - return (ieee_get_fp_control() & flag) != 0; -#endif -} - - -void FPEnvironmentImpl::setRoundingModeImpl(RoundingModeImpl mode) -{ - // not supported -} - - -FPEnvironmentImpl::RoundingModeImpl FPEnvironmentImpl::getRoundingModeImpl() -{ - // not supported - return FPEnvironmentImpl::RoundingModeImpl(0); -} - - -} // namespace Poco +// +// FPEnvironment_DEC.cpp +// +// $Id: //poco/1.2/Foundation/src/FPEnvironment_DEC.cpp#1 $ +// +// Library: Foundation +// Package: Core +// Module: FPEnvironment +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +// +// _XOPEN_SOURCE disables the ieee fp functions +// in , therefore we undefine it for this file. +// +#undef _XOPEN_SOURCE + + +#include +#include +#include +#if defined(__VMS) +#include +#endif +#include "Poco/FPEnvironment_DEC.h" + + +namespace Poco { + + +FPEnvironmentImpl::FPEnvironmentImpl() +{ +#if defined(__VMS) + #pragma pointer_size save + #pragma pointer_size 32 + struct _ieee env; + sys$ieee_set_fp_control(0, 0, &env); + #pragma pointer_size restore + _env = env; +#else + _env = ieee_get_fp_control(); +#endif +} + + +FPEnvironmentImpl::FPEnvironmentImpl(const FPEnvironmentImpl& env) +{ + _env = env._env; +} + + +FPEnvironmentImpl::~FPEnvironmentImpl() +{ +#if defined(__VMS) + #pragma pointer_size save + #pragma pointer_size 32 + struct _ieee mask; + mask.ieee$q_flags = 0xFFFFFFFFFFFFFFFF; + struct _ieee env = _env; + sys$ieee_set_fp_control(&mask, &env, 0); + #pragma pointer_size restore +#else + ieee_set_fp_control(_env); +#endif +} + + +FPEnvironmentImpl& FPEnvironmentImpl::operator = (const FPEnvironmentImpl& env) +{ + _env = env._env; + return *this; +} + + +bool FPEnvironmentImpl::isInfiniteImpl(float value) +{ + int cls = fp_classf(value); + return cls == FP_POS_INF || cls == FP_NEG_INF; +} + + +bool FPEnvironmentImpl::isInfiniteImpl(double value) +{ + int cls = fp_class(value); + return cls == FP_POS_INF || cls == FP_NEG_INF; +} + + +bool FPEnvironmentImpl::isInfiniteImpl(long double value) +{ + int cls = fp_classl(value); + return cls == FP_POS_INF || cls == FP_NEG_INF; +} + + +bool FPEnvironmentImpl::isNaNImpl(float value) +{ + return isnanf(value) != 0; +} + + +bool FPEnvironmentImpl::isNaNImpl(double value) +{ + return isnan(value) != 0; +} + + +bool FPEnvironmentImpl::isNaNImpl(long double value) +{ + return isnanl(value) != 0; +} + + +float FPEnvironmentImpl::copySignImpl(float target, float source) +{ + return copysignf(target, source); +} + + +double FPEnvironmentImpl::copySignImpl(double target, double source) +{ + return copysign(target, source); +} + + +long double FPEnvironmentImpl::copySignImpl(long double target, long double source) +{ + return copysignl(target, source); +} + + +void FPEnvironmentImpl::keepCurrentImpl() +{ +#if defined(__VMS) + #pragma pointer_size save + #pragma pointer_size 32 + struct _ieee env; + sys$ieee_set_fp_control(0, 0, &env); + #pragma pointer_size restore + _env = env; +#else + ieee_set_fp_control(_env); +#endif +} + + +void FPEnvironmentImpl::clearFlagsImpl() +{ +#if defined(__VMS) + #pragma pointer_size save + #pragma pointer_size 32 + struct _ieee mask; + mask.ieee$q_flags = 0xFFFFFFFFFFFFFFFF; + struct _ieee clr; + clr.ieee$q_flags = 0; + sys$ieee_set_fp_control(&mask, &clr, 0); + #pragma pointer_size restore +#else + ieee_set_fp_control(0); +#endif +} + + +bool FPEnvironmentImpl::isFlagImpl(FlagImpl flag) +{ +#if defined(__VMS) + #pragma pointer_size save + #pragma pointer_size 32 + struct _ieee flags; + sys$ieee_set_fp_control(0, 0, &flags); + return (flags.ieee$q_flags & flag) != 0; + #pragma pointer_size restore +#else + return (ieee_get_fp_control() & flag) != 0; +#endif +} + + +void FPEnvironmentImpl::setRoundingModeImpl(RoundingModeImpl mode) +{ + // not supported +} + + +FPEnvironmentImpl::RoundingModeImpl FPEnvironmentImpl::getRoundingModeImpl() +{ + // not supported + return FPEnvironmentImpl::RoundingModeImpl(0); +} + + +} // namespace Poco diff --git a/Foundation/src/FPEnvironment_DUMMY.cpp b/Foundation/src/FPEnvironment_DUMMY.cpp index 7ea63d692..aea0aee88 100644 --- a/Foundation/src/FPEnvironment_DUMMY.cpp +++ b/Foundation/src/FPEnvironment_DUMMY.cpp @@ -1,101 +1,101 @@ -// -// FPEnvironment_C99.cpp -// -// $Id: //poco/1.2/Foundation/src/FPEnvironment_DUMMY.cpp#1 $ -// -// Library: Foundation -// Package: Core -// Module: FPEnvironment -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/FPEnvironment_DUMMY.h" - - -namespace Poco { - - -FPEnvironmentImpl::RoundingModeImpl FPEnvironmentImpl::_roundingMode; - - -FPEnvironmentImpl::FPEnvironmentImpl() -{ -} - - -FPEnvironmentImpl::FPEnvironmentImpl(const FPEnvironmentImpl& env) -{ -} - - -FPEnvironmentImpl::~FPEnvironmentImpl() -{ -} - - -FPEnvironmentImpl& FPEnvironmentImpl::operator = (const FPEnvironmentImpl& env) -{ - return *this; -} - - -void FPEnvironmentImpl::keepCurrentImpl() -{ -} - - -void FPEnvironmentImpl::clearFlagsImpl() -{ -} - - -bool FPEnvironmentImpl::isFlagImpl(FlagImpl flag) -{ - return false; -} - - -void FPEnvironmentImpl::setRoundingModeImpl(RoundingModeImpl mode) -{ - _roundingMode = mode; -} - - -FPEnvironmentImpl::RoundingModeImpl FPEnvironmentImpl::getRoundingModeImpl() -{ - return _roundingMode; -} - - -long double FPEnvironmentImpl::copySignImpl(long double target, long double source) -{ - return (source >= 0 && target >= 0) || (source < 0 && target < 0) ? target : -target; -} - - -} // namespace Poco +// +// FPEnvironment_C99.cpp +// +// $Id: //poco/1.2/Foundation/src/FPEnvironment_DUMMY.cpp#1 $ +// +// Library: Foundation +// Package: Core +// Module: FPEnvironment +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/FPEnvironment_DUMMY.h" + + +namespace Poco { + + +FPEnvironmentImpl::RoundingModeImpl FPEnvironmentImpl::_roundingMode; + + +FPEnvironmentImpl::FPEnvironmentImpl() +{ +} + + +FPEnvironmentImpl::FPEnvironmentImpl(const FPEnvironmentImpl& env) +{ +} + + +FPEnvironmentImpl::~FPEnvironmentImpl() +{ +} + + +FPEnvironmentImpl& FPEnvironmentImpl::operator = (const FPEnvironmentImpl& env) +{ + return *this; +} + + +void FPEnvironmentImpl::keepCurrentImpl() +{ +} + + +void FPEnvironmentImpl::clearFlagsImpl() +{ +} + + +bool FPEnvironmentImpl::isFlagImpl(FlagImpl flag) +{ + return false; +} + + +void FPEnvironmentImpl::setRoundingModeImpl(RoundingModeImpl mode) +{ + _roundingMode = mode; +} + + +FPEnvironmentImpl::RoundingModeImpl FPEnvironmentImpl::getRoundingModeImpl() +{ + return _roundingMode; +} + + +long double FPEnvironmentImpl::copySignImpl(long double target, long double source) +{ + return (source >= 0 && target >= 0) || (source < 0 && target < 0) ? target : -target; +} + + +} // namespace Poco diff --git a/Foundation/src/FPEnvironment_SUN.cpp b/Foundation/src/FPEnvironment_SUN.cpp index d24cf8be4..fa2aa3181 100644 --- a/Foundation/src/FPEnvironment_SUN.cpp +++ b/Foundation/src/FPEnvironment_SUN.cpp @@ -1,161 +1,161 @@ -// -// FPEnvironment_SUN.cpp -// -// $Id: //poco/1.2/Foundation/src/FPEnvironment_SUN.cpp#1 $ -// -// Library: Foundation -// Package: Core -// Module: FPEnvironment -// -// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include -#include "Poco/FPEnvironment_SUN.h" - - -namespace Poco { - - -FPEnvironmentImpl::FPEnvironmentImpl() -{ - _rnd = fpgetround(); - _exc = fpgetmask(); -} - - -FPEnvironmentImpl::FPEnvironmentImpl(const FPEnvironmentImpl& env) -{ - _rnd = env._rnd; - _exc = env._exc; -} - - -FPEnvironmentImpl::~FPEnvironmentImpl() -{ - fpsetround(_rnd); - fpsetmask(_exc); -} - - -FPEnvironmentImpl& FPEnvironmentImpl::operator = (const FPEnvironmentImpl& env) -{ - _rnd = env._rnd; - _exc = env._exc; - return *this; -} - - -bool FPEnvironmentImpl::isInfiniteImpl(float value) -{ - int cls = fpclass(value); - return cls == FP_PINF || cls == FP_NINF; -} - - -bool FPEnvironmentImpl::isInfiniteImpl(double value) -{ - int cls = fpclass(value); - return cls == FP_PINF || cls == FP_NINF; -} - - -bool FPEnvironmentImpl::isInfiniteImpl(long double value) -{ - int cls = fpclass(value); - return cls == FP_PINF || cls == FP_NINF; -} - - -bool FPEnvironmentImpl::isNaNImpl(float value) -{ - return isnanf(value) != 0; -} - - -bool FPEnvironmentImpl::isNaNImpl(double value) -{ - return isnan(value) != 0; -} - - -bool FPEnvironmentImpl::isNaNImpl(long double value) -{ - return isnan((double) value) != 0; -} - - -float FPEnvironmentImpl::copySignImpl(float target, float source) -{ - return (float) copysign(target, source); -} - - -double FPEnvironmentImpl::copySignImpl(double target, double source) -{ - return (float) copysign(target, source); -} - - -long double FPEnvironmentImpl::copySignImpl(long double target, long double source) -{ - return (source > 0 && target > 0) || (source < 0 && target < 0) ? target : -target; -} - - -void FPEnvironmentImpl::keepCurrentImpl() -{ - fpsetround(_rnd); - fpsetmask(_exc); -} - - -void FPEnvironmentImpl::clearFlagsImpl() -{ - fpsetsticky(0); -} - - -bool FPEnvironmentImpl::isFlagImpl(FlagImpl flag) -{ - return (fpgetsticky() & flag) != 0; -} - - -void FPEnvironmentImpl::setRoundingModeImpl(RoundingModeImpl mode) -{ - fpsetround((fp_rnd) mode); -} - - -FPEnvironmentImpl::RoundingModeImpl FPEnvironmentImpl::getRoundingModeImpl() -{ - return (FPEnvironmentImpl::RoundingModeImpl) fpgetround(); -} - - -} // namespace Poco +// +// FPEnvironment_SUN.cpp +// +// $Id: //poco/1.2/Foundation/src/FPEnvironment_SUN.cpp#1 $ +// +// Library: Foundation +// Package: Core +// Module: FPEnvironment +// +// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include +#include "Poco/FPEnvironment_SUN.h" + + +namespace Poco { + + +FPEnvironmentImpl::FPEnvironmentImpl() +{ + _rnd = fpgetround(); + _exc = fpgetmask(); +} + + +FPEnvironmentImpl::FPEnvironmentImpl(const FPEnvironmentImpl& env) +{ + _rnd = env._rnd; + _exc = env._exc; +} + + +FPEnvironmentImpl::~FPEnvironmentImpl() +{ + fpsetround(_rnd); + fpsetmask(_exc); +} + + +FPEnvironmentImpl& FPEnvironmentImpl::operator = (const FPEnvironmentImpl& env) +{ + _rnd = env._rnd; + _exc = env._exc; + return *this; +} + + +bool FPEnvironmentImpl::isInfiniteImpl(float value) +{ + int cls = fpclass(value); + return cls == FP_PINF || cls == FP_NINF; +} + + +bool FPEnvironmentImpl::isInfiniteImpl(double value) +{ + int cls = fpclass(value); + return cls == FP_PINF || cls == FP_NINF; +} + + +bool FPEnvironmentImpl::isInfiniteImpl(long double value) +{ + int cls = fpclass(value); + return cls == FP_PINF || cls == FP_NINF; +} + + +bool FPEnvironmentImpl::isNaNImpl(float value) +{ + return isnanf(value) != 0; +} + + +bool FPEnvironmentImpl::isNaNImpl(double value) +{ + return isnan(value) != 0; +} + + +bool FPEnvironmentImpl::isNaNImpl(long double value) +{ + return isnan((double) value) != 0; +} + + +float FPEnvironmentImpl::copySignImpl(float target, float source) +{ + return (float) copysign(target, source); +} + + +double FPEnvironmentImpl::copySignImpl(double target, double source) +{ + return (float) copysign(target, source); +} + + +long double FPEnvironmentImpl::copySignImpl(long double target, long double source) +{ + return (source > 0 && target > 0) || (source < 0 && target < 0) ? target : -target; +} + + +void FPEnvironmentImpl::keepCurrentImpl() +{ + fpsetround(_rnd); + fpsetmask(_exc); +} + + +void FPEnvironmentImpl::clearFlagsImpl() +{ + fpsetsticky(0); +} + + +bool FPEnvironmentImpl::isFlagImpl(FlagImpl flag) +{ + return (fpgetsticky() & flag) != 0; +} + + +void FPEnvironmentImpl::setRoundingModeImpl(RoundingModeImpl mode) +{ + fpsetround((fp_rnd) mode); +} + + +FPEnvironmentImpl::RoundingModeImpl FPEnvironmentImpl::getRoundingModeImpl() +{ + return (FPEnvironmentImpl::RoundingModeImpl) fpgetround(); +} + + +} // namespace Poco diff --git a/Foundation/src/FPEnvironment_WIN32.cpp b/Foundation/src/FPEnvironment_WIN32.cpp index 6b4aa1132..17662cc41 100644 --- a/Foundation/src/FPEnvironment_WIN32.cpp +++ b/Foundation/src/FPEnvironment_WIN32.cpp @@ -1,98 +1,98 @@ -// -// FPEnvironment_WIN32.cpp -// -// $Id: //poco/1.2/Foundation/src/FPEnvironment_WIN32.cpp#1 $ -// -// Library: Foundation -// Package: Core -// Module: FPEnvironment -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/FPEnvironment_WIN32.h" - - -namespace Poco { - - -FPEnvironmentImpl::FPEnvironmentImpl() -{ - _env = _controlfp(0, 0); -} - - -FPEnvironmentImpl::FPEnvironmentImpl(const FPEnvironmentImpl& env) -{ - _env = env._env; -} - - -FPEnvironmentImpl::~FPEnvironmentImpl() -{ - _controlfp(_env, MCW_RC); -} - - -FPEnvironmentImpl& FPEnvironmentImpl::operator = (const FPEnvironmentImpl& env) -{ - _env = env._env; - return *this; -} - - -void FPEnvironmentImpl::keepCurrentImpl() -{ - _env = _controlfp(0, 0); -} - - -void FPEnvironmentImpl::clearFlagsImpl() -{ - _clearfp(); -} - - -bool FPEnvironmentImpl::isFlagImpl(FlagImpl flag) -{ - return (_statusfp() & flag) != 0; -} - - -void FPEnvironmentImpl::setRoundingModeImpl(RoundingModeImpl mode) -{ - _controlfp(mode, MCW_RC); -} - - -FPEnvironmentImpl::RoundingModeImpl FPEnvironmentImpl::getRoundingModeImpl() -{ - return RoundingModeImpl(_controlfp(0, 0) & MCW_RC); -} - - -} // namespace Poco +// +// FPEnvironment_WIN32.cpp +// +// $Id: //poco/1.2/Foundation/src/FPEnvironment_WIN32.cpp#1 $ +// +// Library: Foundation +// Package: Core +// Module: FPEnvironment +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/FPEnvironment_WIN32.h" + + +namespace Poco { + + +FPEnvironmentImpl::FPEnvironmentImpl() +{ + _env = _controlfp(0, 0); +} + + +FPEnvironmentImpl::FPEnvironmentImpl(const FPEnvironmentImpl& env) +{ + _env = env._env; +} + + +FPEnvironmentImpl::~FPEnvironmentImpl() +{ + _controlfp(_env, MCW_RC); +} + + +FPEnvironmentImpl& FPEnvironmentImpl::operator = (const FPEnvironmentImpl& env) +{ + _env = env._env; + return *this; +} + + +void FPEnvironmentImpl::keepCurrentImpl() +{ + _env = _controlfp(0, 0); +} + + +void FPEnvironmentImpl::clearFlagsImpl() +{ + _clearfp(); +} + + +bool FPEnvironmentImpl::isFlagImpl(FlagImpl flag) +{ + return (_statusfp() & flag) != 0; +} + + +void FPEnvironmentImpl::setRoundingModeImpl(RoundingModeImpl mode) +{ + _controlfp(mode, MCW_RC); +} + + +FPEnvironmentImpl::RoundingModeImpl FPEnvironmentImpl::getRoundingModeImpl() +{ + return RoundingModeImpl(_controlfp(0, 0) & MCW_RC); +} + + +} // namespace Poco diff --git a/Foundation/src/File.cpp b/Foundation/src/File.cpp index a2263d5fb..68fbd4bb0 100644 --- a/Foundation/src/File.cpp +++ b/Foundation/src/File.cpp @@ -1,301 +1,301 @@ -// -// File.cpp -// -// $Id: //poco/1.2/Foundation/src/File.cpp#1 $ -// -// Library: Foundation -// Package: Filesystem -// Module: File -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/File.h" -#include "Poco/Path.h" -#include "Poco/DirectoryIterator.h" - - -#if defined(POCO_OS_FAMILY_WINDOWS) && defined(POCO_WIN32_UTF8) -#include "File_WIN32U.cpp" -#elif defined(POCO_OS_FAMILY_WINDOWS) -#include "File_WIN32.cpp" -#elif defined(POCO_OS_FAMILY_UNIX) -#include "File_UNIX.cpp" -#else -#include "File_VMS.cpp" -#endif - - -namespace Poco { - - -File::File() -{ -} - - -File::File(const std::string& path): FileImpl(path) -{ -} - - -File::File(const char* path): FileImpl(std::string(path)) -{ -} - - -File::File(const Path& path): FileImpl(path.toString()) -{ -} - - -File::File(const File& file): FileImpl(file.getPathImpl()) -{ -} - - -File::~File() -{ -} - - -File& File::operator = (const File& file) -{ - setPathImpl(file.getPathImpl()); - return *this; -} - - -File& File::operator = (const std::string& path) -{ - setPathImpl(path); - return *this; -} - - -File& File::operator = (const char* path) -{ - poco_check_ptr (path); - setPathImpl(path); - return *this; -} - - -File& File::operator = (const Path& path) -{ - setPathImpl(path.toString()); - return *this; -} - - -void File::swap(File& file) -{ - swapImpl(file); -} - - -bool File::exists() const -{ - return existsImpl(); -} - - -bool File::canRead() const -{ - return canReadImpl(); -} - - -bool File::canWrite() const -{ - return canWriteImpl(); -} - - -bool File::isFile() const -{ - return isFileImpl(); -} - - -bool File::isDirectory() const -{ - return isDirectoryImpl(); -} - - -bool File::isLink() const -{ - return isLinkImpl(); -} - - -Timestamp File::created() const -{ - return createdImpl(); -} - - -Timestamp File::getLastModified() const -{ - return getLastModifiedImpl(); -} - - -void File::setLastModified(const Timestamp& ts) -{ - setLastModifiedImpl(ts); -} - - -File::FileSize File::getSize() const -{ - return getSizeImpl(); -} - - -void File::setSize(FileSizeImpl size) -{ - setSizeImpl(size); -} - - -void File::setWriteable(bool flag) -{ - setWriteableImpl(flag); -} - - -void File::setReadOnly(bool flag) -{ - setWriteableImpl(!flag); -} - - -void File::copyTo(const std::string& path) const -{ - Path src(getPathImpl()); - File srcFile(src); - if (srcFile.isDirectory()) - throw OpenFileException("cannot copy directory", src.toString()); - - Path dest(path); - if (dest.isDirectory()) - { - dest.makeDirectory(); - dest.setFileName(src.getFileName()); - } - copyToImpl(dest.toString()); -} - - -void File::moveTo(const std::string& path) -{ - copyToImpl(path); - removeImpl(); - setPathImpl(path); -} - - -void File::renameTo(const std::string& path) -{ - renameToImpl(path); - setPathImpl(path); -} - - -void File::remove(bool recursive) -{ - if (recursive && !isLink() && isDirectory()) - { - std::vector files; - list(files); - for (std::vector::iterator it = files.begin(); it != files.end(); ++it) - { - it->remove(true); - } - } - removeImpl(); -} - - -bool File::createFile() -{ - return createFileImpl(); -} - - -bool File::createDirectory() -{ - return createDirectoryImpl(); -} - - -void File::createDirectories() -{ - if (!exists()) - { - Path p(getPathImpl()); - p.makeDirectory(); - if (p.depth() > 1) - { - p.makeParent(); - File f(p); - f.createDirectories(); - } - createDirectoryImpl(); - } -} - - -void File::list(std::vector& files) const -{ - files.clear(); - DirectoryIterator it(*this); - DirectoryIterator end; - while (it != end) - { - files.push_back(it.name()); - ++it; - } -} - - -void File::list(std::vector& files) const -{ - files.clear(); - DirectoryIterator it(*this); - DirectoryIterator end; - while (it != end) - { - files.push_back(*it); - ++it; - } -} - - -} // namespace Poco +// +// File.cpp +// +// $Id: //poco/1.2/Foundation/src/File.cpp#1 $ +// +// Library: Foundation +// Package: Filesystem +// Module: File +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/File.h" +#include "Poco/Path.h" +#include "Poco/DirectoryIterator.h" + + +#if defined(POCO_OS_FAMILY_WINDOWS) && defined(POCO_WIN32_UTF8) +#include "File_WIN32U.cpp" +#elif defined(POCO_OS_FAMILY_WINDOWS) +#include "File_WIN32.cpp" +#elif defined(POCO_OS_FAMILY_UNIX) +#include "File_UNIX.cpp" +#else +#include "File_VMS.cpp" +#endif + + +namespace Poco { + + +File::File() +{ +} + + +File::File(const std::string& path): FileImpl(path) +{ +} + + +File::File(const char* path): FileImpl(std::string(path)) +{ +} + + +File::File(const Path& path): FileImpl(path.toString()) +{ +} + + +File::File(const File& file): FileImpl(file.getPathImpl()) +{ +} + + +File::~File() +{ +} + + +File& File::operator = (const File& file) +{ + setPathImpl(file.getPathImpl()); + return *this; +} + + +File& File::operator = (const std::string& path) +{ + setPathImpl(path); + return *this; +} + + +File& File::operator = (const char* path) +{ + poco_check_ptr (path); + setPathImpl(path); + return *this; +} + + +File& File::operator = (const Path& path) +{ + setPathImpl(path.toString()); + return *this; +} + + +void File::swap(File& file) +{ + swapImpl(file); +} + + +bool File::exists() const +{ + return existsImpl(); +} + + +bool File::canRead() const +{ + return canReadImpl(); +} + + +bool File::canWrite() const +{ + return canWriteImpl(); +} + + +bool File::isFile() const +{ + return isFileImpl(); +} + + +bool File::isDirectory() const +{ + return isDirectoryImpl(); +} + + +bool File::isLink() const +{ + return isLinkImpl(); +} + + +Timestamp File::created() const +{ + return createdImpl(); +} + + +Timestamp File::getLastModified() const +{ + return getLastModifiedImpl(); +} + + +void File::setLastModified(const Timestamp& ts) +{ + setLastModifiedImpl(ts); +} + + +File::FileSize File::getSize() const +{ + return getSizeImpl(); +} + + +void File::setSize(FileSizeImpl size) +{ + setSizeImpl(size); +} + + +void File::setWriteable(bool flag) +{ + setWriteableImpl(flag); +} + + +void File::setReadOnly(bool flag) +{ + setWriteableImpl(!flag); +} + + +void File::copyTo(const std::string& path) const +{ + Path src(getPathImpl()); + File srcFile(src); + if (srcFile.isDirectory()) + throw OpenFileException("cannot copy directory", src.toString()); + + Path dest(path); + if (dest.isDirectory()) + { + dest.makeDirectory(); + dest.setFileName(src.getFileName()); + } + copyToImpl(dest.toString()); +} + + +void File::moveTo(const std::string& path) +{ + copyToImpl(path); + removeImpl(); + setPathImpl(path); +} + + +void File::renameTo(const std::string& path) +{ + renameToImpl(path); + setPathImpl(path); +} + + +void File::remove(bool recursive) +{ + if (recursive && !isLink() && isDirectory()) + { + std::vector files; + list(files); + for (std::vector::iterator it = files.begin(); it != files.end(); ++it) + { + it->remove(true); + } + } + removeImpl(); +} + + +bool File::createFile() +{ + return createFileImpl(); +} + + +bool File::createDirectory() +{ + return createDirectoryImpl(); +} + + +void File::createDirectories() +{ + if (!exists()) + { + Path p(getPathImpl()); + p.makeDirectory(); + if (p.depth() > 1) + { + p.makeParent(); + File f(p); + f.createDirectories(); + } + createDirectoryImpl(); + } +} + + +void File::list(std::vector& files) const +{ + files.clear(); + DirectoryIterator it(*this); + DirectoryIterator end; + while (it != end) + { + files.push_back(it.name()); + ++it; + } +} + + +void File::list(std::vector& files) const +{ + files.clear(); + DirectoryIterator it(*this); + DirectoryIterator end; + while (it != end) + { + files.push_back(*it); + ++it; + } +} + + +} // namespace Poco diff --git a/Foundation/src/FileChannel.cpp b/Foundation/src/FileChannel.cpp index 928d82980..cd1af4e41 100644 --- a/Foundation/src/FileChannel.cpp +++ b/Foundation/src/FileChannel.cpp @@ -1,358 +1,358 @@ -// -// FileChannel.cpp -// -// $Id: //poco/1.2/Foundation/src/FileChannel.cpp#2 $ -// -// Library: Foundation -// Package: Logging -// Module: FileChannel -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/FileChannel.h" -#include "Poco/ArchiveStrategy.h" -#include "Poco/RotateStrategy.h" -#include "Poco/PurgeStrategy.h" -#include "Poco/Message.h" -#include "Poco/NumberParser.h" -#include "Poco/DateTimeFormatter.h" -#include "Poco/DateTime.h" -#include "Poco/LocalDateTime.h" -#include "Poco/String.h" -#include "Poco/Timespan.h" -#include "Poco/Exception.h" -#include - - -namespace Poco { - - -const std::string FileChannel::PROP_PATH = "path"; -const std::string FileChannel::PROP_ROTATION = "rotation"; -const std::string FileChannel::PROP_ARCHIVE = "archive"; -const std::string FileChannel::PROP_TIMES = "times"; -const std::string FileChannel::PROP_COMPRESS = "compress"; -const std::string FileChannel::PROP_PURGEAGE = "purgeAge"; -const std::string FileChannel::PROP_PURGECOUNT = "purgeCount"; - - -FileChannel::FileChannel(): - _times("utc"), - _compress(false), - _pFile(0), - _pRotateStrategy(0), - _pArchiveStrategy(new ArchiveByNumberStrategy), - _pPurgeStrategy(0) -{ -} - - -FileChannel::FileChannel(const std::string& path): - _path(path), - _times("utc"), - _compress(false), - _pFile(0), - _pRotateStrategy(0), - _pArchiveStrategy(new ArchiveByNumberStrategy), - _pPurgeStrategy(0) -{ -} - - -FileChannel::~FileChannel() -{ - close(); - delete _pRotateStrategy; - delete _pArchiveStrategy; - delete _pPurgeStrategy; -} - - -void FileChannel::open() -{ - FastMutex::ScopedLock lock(_mutex); - - if (!_pFile) - { - _pFile = new LogFile(_path); - } -} - - -void FileChannel::close() -{ - FastMutex::ScopedLock lock(_mutex); - - delete _pFile; - _pFile = 0; -} - - -void FileChannel::log(const Message& msg) -{ - open(); - - FastMutex::ScopedLock lock(_mutex); - - if (_pRotateStrategy && _pArchiveStrategy && _pRotateStrategy->mustRotate(_pFile)) - { - try - { - _pFile = _pArchiveStrategy->archive(_pFile); - purge(); - } - catch (...) - { - _pFile = new LogFile(_path); - } - } - _pFile->write(msg.getText()); -} - - -void FileChannel::setProperty(const std::string& name, const std::string& value) -{ - FastMutex::ScopedLock lock(_mutex); - - if (name == PROP_TIMES) - { - _times = value; - - if (!_rotation.empty()) - setRotation(_rotation); - - if (!_archive.empty()) - setArchive(_archive); - } - else if (name == PROP_PATH) - _path = value; - else if (name == PROP_ROTATION) - setRotation(value); - else if (name == PROP_ARCHIVE) - setArchive(value); - else if (name == PROP_COMPRESS) - setCompress(value); - else if (name == PROP_PURGEAGE) - setPurgeAge(value); - else if (name == PROP_PURGECOUNT) - setPurgeCount(value); - else - Channel::setProperty(name, value); -} - - -std::string FileChannel::getProperty(const std::string& name) const -{ - if (name == PROP_TIMES) - return _times; - else if (name == PROP_PATH) - return _path; - else if (name == PROP_ROTATION) - return _rotation; - else if (name == PROP_ARCHIVE) - return _archive; - else if (name == PROP_COMPRESS) - return std::string(_compress ? "true" : "false"); - else if (name == PROP_PURGEAGE) - return _purgeAge; - else if (name == PROP_PURGECOUNT) - return _purgeCount; - else - return Channel::getProperty(name); -} - - -Timestamp FileChannel::creationDate() const -{ - if (_pFile) - return _pFile->creationDate(); - else - return 0; -} - - -UInt64 FileChannel::size() const -{ - if (_pFile) - return _pFile->size(); - else - return 0; -} - - -const std::string& FileChannel::path() const -{ - return _path; -} - - -void FileChannel::setRotation(const std::string& rotation) -{ - std::string::const_iterator it = rotation.begin(); - std::string::const_iterator end = rotation.end(); - int n = 0; - while (it != end && isspace(*it)) ++it; - while (it != end && isdigit(*it)) { n *= 10; n += *it++ - '0'; } - while (it != end && isspace(*it)) ++it; - std::string unit; - while (it != end && isalpha(*it)) unit += *it++; - - RotateStrategy* pStrategy = 0; - if ((rotation.find(',') != std::string::npos) || (rotation.find(':') != std::string::npos)) - { - if (_times == "utc") - pStrategy = new RotateAtTimeStrategy(rotation); - else if (_times == "local") - pStrategy = new RotateAtTimeStrategy(rotation); - else - throw PropertyNotSupportedException("times", _times); - } - else if (unit == "daily") - pStrategy = new RotateByIntervalStrategy(Timespan(1*Timespan::DAYS)); - else if (unit == "weekly") - pStrategy = new RotateByIntervalStrategy(Timespan(7*Timespan::DAYS)); - else if (unit == "monthly") - pStrategy = new RotateByIntervalStrategy(Timespan(30*Timespan::DAYS)); - else if (unit == "seconds") // for testing only - pStrategy = new RotateByIntervalStrategy(Timespan(n*Timespan::SECONDS)); - else if (unit == "hours") - pStrategy = new RotateByIntervalStrategy(Timespan(n*Timespan::HOURS)); - else if (unit == "days") - pStrategy = new RotateByIntervalStrategy(Timespan(n*Timespan::DAYS)); - else if (unit == "weeks") - pStrategy = new RotateByIntervalStrategy(Timespan(n*7*Timespan::DAYS)); - else if (unit == "months") - pStrategy = new RotateByIntervalStrategy(Timespan(n*30*Timespan::DAYS)); - else if (unit == "K") - pStrategy = new RotateBySizeStrategy(n*1024); - else if (unit == "M") - pStrategy = new RotateBySizeStrategy(n*1024*1024); - else if (unit.empty()) - pStrategy = new RotateBySizeStrategy(n); - else if (unit != "never") - throw InvalidArgumentException("rotation", rotation); - delete _pRotateStrategy; - _pRotateStrategy = pStrategy; - _rotation = rotation; -} - - -void FileChannel::setArchive(const std::string& archive) -{ - ArchiveStrategy* pStrategy = 0; - if (archive == "number") - { - pStrategy = new ArchiveByNumberStrategy; - } - else if (archive == "timestamp") - { - if (_times == "utc") - pStrategy = new ArchiveByTimestampStrategy; - else if (_times == "local") - pStrategy = new ArchiveByTimestampStrategy; - else - throw PropertyNotSupportedException("times", _times); - } - else throw InvalidArgumentException("archive", archive); - delete _pArchiveStrategy; - pStrategy->compress(_compress); - _pArchiveStrategy = pStrategy; - _archive = archive; -} - - -void FileChannel::setCompress(const std::string& compress) -{ - _compress = icompare(compress, "true") == 0; - if (_pArchiveStrategy) - _pArchiveStrategy->compress(_compress); -} - - -void FileChannel::setPurgeAge(const std::string& age) -{ - std::string::const_iterator it = age.begin(); - std::string::const_iterator end = age.end(); - int n = 0; - while (it != end && isspace(*it)) ++it; - while (it != end && isdigit(*it)) { n *= 10; n += *it++ - '0'; } - while (it != end && isspace(*it)) ++it; - std::string unit; - while (it != end && isalpha(*it)) unit += *it++; - - Timespan::TimeDiff factor = Timespan::SECONDS; - if (unit == "minutes") - factor = Timespan::MINUTES; - else if (unit == "hours") - factor = Timespan::HOURS; - else if (unit == "days") - factor = Timespan::DAYS; - else if (unit == "weeks") - factor = 7*Timespan::DAYS; - else if (unit == "months") - factor = 30*Timespan::DAYS; - else if (unit != "seconds") - throw InvalidArgumentException("purgeAge", age); - - delete _pPurgeStrategy; - _pPurgeStrategy = new PurgeByAgeStrategy(Timespan(factor*n)); - _purgeAge = age; -} - - -void FileChannel::setPurgeCount(const std::string& count) -{ - std::string::const_iterator it = count.begin(); - std::string::const_iterator end = count.end(); - int n = 0; - while (it != end && isspace(*it)) ++it; - while (it != end && isdigit(*it)) { n *= 10; n += *it++ - '0'; } - while (it != end && isspace(*it)) ++it; - - delete _pPurgeStrategy; - _pPurgeStrategy = new PurgeByCountStrategy(n); - _purgeCount = count; -} - - -void FileChannel::purge() -{ - if (_pPurgeStrategy) - { - try - { - _pPurgeStrategy->purge(_path); - } - catch (...) - { - } - } -} - - -} // namespace Poco +// +// FileChannel.cpp +// +// $Id: //poco/1.2/Foundation/src/FileChannel.cpp#2 $ +// +// Library: Foundation +// Package: Logging +// Module: FileChannel +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/FileChannel.h" +#include "Poco/ArchiveStrategy.h" +#include "Poco/RotateStrategy.h" +#include "Poco/PurgeStrategy.h" +#include "Poco/Message.h" +#include "Poco/NumberParser.h" +#include "Poco/DateTimeFormatter.h" +#include "Poco/DateTime.h" +#include "Poco/LocalDateTime.h" +#include "Poco/String.h" +#include "Poco/Timespan.h" +#include "Poco/Exception.h" +#include + + +namespace Poco { + + +const std::string FileChannel::PROP_PATH = "path"; +const std::string FileChannel::PROP_ROTATION = "rotation"; +const std::string FileChannel::PROP_ARCHIVE = "archive"; +const std::string FileChannel::PROP_TIMES = "times"; +const std::string FileChannel::PROP_COMPRESS = "compress"; +const std::string FileChannel::PROP_PURGEAGE = "purgeAge"; +const std::string FileChannel::PROP_PURGECOUNT = "purgeCount"; + + +FileChannel::FileChannel(): + _times("utc"), + _compress(false), + _pFile(0), + _pRotateStrategy(0), + _pArchiveStrategy(new ArchiveByNumberStrategy), + _pPurgeStrategy(0) +{ +} + + +FileChannel::FileChannel(const std::string& path): + _path(path), + _times("utc"), + _compress(false), + _pFile(0), + _pRotateStrategy(0), + _pArchiveStrategy(new ArchiveByNumberStrategy), + _pPurgeStrategy(0) +{ +} + + +FileChannel::~FileChannel() +{ + close(); + delete _pRotateStrategy; + delete _pArchiveStrategy; + delete _pPurgeStrategy; +} + + +void FileChannel::open() +{ + FastMutex::ScopedLock lock(_mutex); + + if (!_pFile) + { + _pFile = new LogFile(_path); + } +} + + +void FileChannel::close() +{ + FastMutex::ScopedLock lock(_mutex); + + delete _pFile; + _pFile = 0; +} + + +void FileChannel::log(const Message& msg) +{ + open(); + + FastMutex::ScopedLock lock(_mutex); + + if (_pRotateStrategy && _pArchiveStrategy && _pRotateStrategy->mustRotate(_pFile)) + { + try + { + _pFile = _pArchiveStrategy->archive(_pFile); + purge(); + } + catch (...) + { + _pFile = new LogFile(_path); + } + } + _pFile->write(msg.getText()); +} + + +void FileChannel::setProperty(const std::string& name, const std::string& value) +{ + FastMutex::ScopedLock lock(_mutex); + + if (name == PROP_TIMES) + { + _times = value; + + if (!_rotation.empty()) + setRotation(_rotation); + + if (!_archive.empty()) + setArchive(_archive); + } + else if (name == PROP_PATH) + _path = value; + else if (name == PROP_ROTATION) + setRotation(value); + else if (name == PROP_ARCHIVE) + setArchive(value); + else if (name == PROP_COMPRESS) + setCompress(value); + else if (name == PROP_PURGEAGE) + setPurgeAge(value); + else if (name == PROP_PURGECOUNT) + setPurgeCount(value); + else + Channel::setProperty(name, value); +} + + +std::string FileChannel::getProperty(const std::string& name) const +{ + if (name == PROP_TIMES) + return _times; + else if (name == PROP_PATH) + return _path; + else if (name == PROP_ROTATION) + return _rotation; + else if (name == PROP_ARCHIVE) + return _archive; + else if (name == PROP_COMPRESS) + return std::string(_compress ? "true" : "false"); + else if (name == PROP_PURGEAGE) + return _purgeAge; + else if (name == PROP_PURGECOUNT) + return _purgeCount; + else + return Channel::getProperty(name); +} + + +Timestamp FileChannel::creationDate() const +{ + if (_pFile) + return _pFile->creationDate(); + else + return 0; +} + + +UInt64 FileChannel::size() const +{ + if (_pFile) + return _pFile->size(); + else + return 0; +} + + +const std::string& FileChannel::path() const +{ + return _path; +} + + +void FileChannel::setRotation(const std::string& rotation) +{ + std::string::const_iterator it = rotation.begin(); + std::string::const_iterator end = rotation.end(); + int n = 0; + while (it != end && isspace(*it)) ++it; + while (it != end && isdigit(*it)) { n *= 10; n += *it++ - '0'; } + while (it != end && isspace(*it)) ++it; + std::string unit; + while (it != end && isalpha(*it)) unit += *it++; + + RotateStrategy* pStrategy = 0; + if ((rotation.find(',') != std::string::npos) || (rotation.find(':') != std::string::npos)) + { + if (_times == "utc") + pStrategy = new RotateAtTimeStrategy(rotation); + else if (_times == "local") + pStrategy = new RotateAtTimeStrategy(rotation); + else + throw PropertyNotSupportedException("times", _times); + } + else if (unit == "daily") + pStrategy = new RotateByIntervalStrategy(Timespan(1*Timespan::DAYS)); + else if (unit == "weekly") + pStrategy = new RotateByIntervalStrategy(Timespan(7*Timespan::DAYS)); + else if (unit == "monthly") + pStrategy = new RotateByIntervalStrategy(Timespan(30*Timespan::DAYS)); + else if (unit == "seconds") // for testing only + pStrategy = new RotateByIntervalStrategy(Timespan(n*Timespan::SECONDS)); + else if (unit == "hours") + pStrategy = new RotateByIntervalStrategy(Timespan(n*Timespan::HOURS)); + else if (unit == "days") + pStrategy = new RotateByIntervalStrategy(Timespan(n*Timespan::DAYS)); + else if (unit == "weeks") + pStrategy = new RotateByIntervalStrategy(Timespan(n*7*Timespan::DAYS)); + else if (unit == "months") + pStrategy = new RotateByIntervalStrategy(Timespan(n*30*Timespan::DAYS)); + else if (unit == "K") + pStrategy = new RotateBySizeStrategy(n*1024); + else if (unit == "M") + pStrategy = new RotateBySizeStrategy(n*1024*1024); + else if (unit.empty()) + pStrategy = new RotateBySizeStrategy(n); + else if (unit != "never") + throw InvalidArgumentException("rotation", rotation); + delete _pRotateStrategy; + _pRotateStrategy = pStrategy; + _rotation = rotation; +} + + +void FileChannel::setArchive(const std::string& archive) +{ + ArchiveStrategy* pStrategy = 0; + if (archive == "number") + { + pStrategy = new ArchiveByNumberStrategy; + } + else if (archive == "timestamp") + { + if (_times == "utc") + pStrategy = new ArchiveByTimestampStrategy; + else if (_times == "local") + pStrategy = new ArchiveByTimestampStrategy; + else + throw PropertyNotSupportedException("times", _times); + } + else throw InvalidArgumentException("archive", archive); + delete _pArchiveStrategy; + pStrategy->compress(_compress); + _pArchiveStrategy = pStrategy; + _archive = archive; +} + + +void FileChannel::setCompress(const std::string& compress) +{ + _compress = icompare(compress, "true") == 0; + if (_pArchiveStrategy) + _pArchiveStrategy->compress(_compress); +} + + +void FileChannel::setPurgeAge(const std::string& age) +{ + std::string::const_iterator it = age.begin(); + std::string::const_iterator end = age.end(); + int n = 0; + while (it != end && isspace(*it)) ++it; + while (it != end && isdigit(*it)) { n *= 10; n += *it++ - '0'; } + while (it != end && isspace(*it)) ++it; + std::string unit; + while (it != end && isalpha(*it)) unit += *it++; + + Timespan::TimeDiff factor = Timespan::SECONDS; + if (unit == "minutes") + factor = Timespan::MINUTES; + else if (unit == "hours") + factor = Timespan::HOURS; + else if (unit == "days") + factor = Timespan::DAYS; + else if (unit == "weeks") + factor = 7*Timespan::DAYS; + else if (unit == "months") + factor = 30*Timespan::DAYS; + else if (unit != "seconds") + throw InvalidArgumentException("purgeAge", age); + + delete _pPurgeStrategy; + _pPurgeStrategy = new PurgeByAgeStrategy(Timespan(factor*n)); + _purgeAge = age; +} + + +void FileChannel::setPurgeCount(const std::string& count) +{ + std::string::const_iterator it = count.begin(); + std::string::const_iterator end = count.end(); + int n = 0; + while (it != end && isspace(*it)) ++it; + while (it != end && isdigit(*it)) { n *= 10; n += *it++ - '0'; } + while (it != end && isspace(*it)) ++it; + + delete _pPurgeStrategy; + _pPurgeStrategy = new PurgeByCountStrategy(n); + _purgeCount = count; +} + + +void FileChannel::purge() +{ + if (_pPurgeStrategy) + { + try + { + _pPurgeStrategy->purge(_path); + } + catch (...) + { + } + } +} + + +} // namespace Poco diff --git a/Foundation/src/FileStreamFactory.cpp b/Foundation/src/FileStreamFactory.cpp index a2e2f7642..c802dc74a 100644 --- a/Foundation/src/FileStreamFactory.cpp +++ b/Foundation/src/FileStreamFactory.cpp @@ -1,86 +1,86 @@ -// -// FileStreamFactory.cpp -// -// $Id: //poco/1.2/Foundation/src/FileStreamFactory.cpp#1 $ -// -// Library: Foundation -// Package: URI -// Module: FileStreamFactory -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/FileStreamFactory.h" -#include "Poco/URI.h" -#include "Poco/Path.h" -#include "Poco/File.h" -#include "Poco/Exception.h" -#include - - -namespace Poco { - - -FileStreamFactory::FileStreamFactory() -{ -} - - -FileStreamFactory::~FileStreamFactory() -{ -} - - -std::istream* FileStreamFactory::open(const URI& uri) -{ - poco_assert (uri.isRelative() || uri.getScheme() == "file"); - - std::string uriPath = uri.getPath(); - if (uriPath.substr(0, 2) == "./") - uriPath.erase(0, 2); - Path p(uriPath, Path::PATH_UNIX); - p.setNode(uri.getHost()); - return open(p); -} - - -std::istream* FileStreamFactory::open(const Path& path) -{ - File file(path); - if (!file.exists()) throw FileNotFoundException(path.toString()); - - std::ifstream* istr = new std::ifstream(path.toString().c_str(), std::ios::binary); - if (!istr->good()) - { - delete istr; - throw OpenFileException(path.toString()); - } - return istr; -} - - -} // namespace Poco +// +// FileStreamFactory.cpp +// +// $Id: //poco/1.2/Foundation/src/FileStreamFactory.cpp#1 $ +// +// Library: Foundation +// Package: URI +// Module: FileStreamFactory +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/FileStreamFactory.h" +#include "Poco/URI.h" +#include "Poco/Path.h" +#include "Poco/File.h" +#include "Poco/Exception.h" +#include + + +namespace Poco { + + +FileStreamFactory::FileStreamFactory() +{ +} + + +FileStreamFactory::~FileStreamFactory() +{ +} + + +std::istream* FileStreamFactory::open(const URI& uri) +{ + poco_assert (uri.isRelative() || uri.getScheme() == "file"); + + std::string uriPath = uri.getPath(); + if (uriPath.substr(0, 2) == "./") + uriPath.erase(0, 2); + Path p(uriPath, Path::PATH_UNIX); + p.setNode(uri.getHost()); + return open(p); +} + + +std::istream* FileStreamFactory::open(const Path& path) +{ + File file(path); + if (!file.exists()) throw FileNotFoundException(path.toString()); + + std::ifstream* istr = new std::ifstream(path.toString().c_str(), std::ios::binary); + if (!istr->good()) + { + delete istr; + throw OpenFileException(path.toString()); + } + return istr; +} + + +} // namespace Poco diff --git a/Foundation/src/File_UNIX.cpp b/Foundation/src/File_UNIX.cpp index cad3dd996..b7cd047e9 100644 --- a/Foundation/src/File_UNIX.cpp +++ b/Foundation/src/File_UNIX.cpp @@ -1,388 +1,388 @@ -// -// File_UNIX.cpp -// -// $Id: //poco/1.2/Foundation/src/File_UNIX.cpp#1 $ -// -// Library: Foundation -// Package: Filesystem -// Module: File -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/File_UNIX.h" -#include "Poco/Buffer.h" -#include "Poco/Exception.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include - - -namespace Poco { - - -FileImpl::FileImpl() -{ -} - - -FileImpl::FileImpl(const std::string& path): _path(path) -{ - std::string::size_type n = _path.size(); - if (n > 0 && _path[n - 1] == '/') - _path.resize(n - 1); -} - - -FileImpl::~FileImpl() -{ -} - - -void FileImpl::swapImpl(FileImpl& file) -{ - std::swap(_path, file._path); -} - - -void FileImpl::setPathImpl(const std::string& path) -{ - _path = path; -} - - -bool FileImpl::existsImpl() const -{ - poco_assert (!_path.empty()); - - struct stat st; - return stat(_path.c_str(), &st) == 0; -} - - -bool FileImpl::canReadImpl() const -{ - poco_assert (!_path.empty()); - - struct stat st; - if (stat(_path.c_str(), &st) == 0) - { - if (st.st_uid == geteuid()) - return (st.st_mode & S_IRUSR) != 0; - else if (st.st_gid == getegid()) - return (st.st_mode & S_IRGRP) != 0; - else - return (st.st_mode & S_IROTH) != 0; - } - else handleError(_path); - return false; -} - - -bool FileImpl::canWriteImpl() const -{ - poco_assert (!_path.empty()); - - struct stat st; - if (stat(_path.c_str(), &st) == 0) - { - if (st.st_uid == geteuid()) - return (st.st_mode & S_IWUSR) != 0; - else if (st.st_gid == getegid()) - return (st.st_mode & S_IWGRP) != 0; - else - return (st.st_mode & S_IWOTH) != 0; - } - else handleError(_path); - return false; -} - - -bool FileImpl::isFileImpl() const -{ - poco_assert (!_path.empty()); - - struct stat st; - if (stat(_path.c_str(), &st) == 0) - return S_ISREG(st.st_mode); - else - handleError(_path); - return false; -} - - -bool FileImpl::isDirectoryImpl() const -{ - poco_assert (!_path.empty()); - - struct stat st; - if (stat(_path.c_str(), &st) == 0) - return S_ISDIR(st.st_mode); - else - handleError(_path); - return false; -} - - -bool FileImpl::isLinkImpl() const -{ - poco_assert (!_path.empty()); - - struct stat st; - if (lstat(_path.c_str(), &st) == 0) - return S_ISLNK(st.st_mode); - else - handleError(_path); - return false; -} - - -Timestamp FileImpl::createdImpl() const -{ - poco_assert (!_path.empty()); - - struct stat st; - if (stat(_path.c_str(), &st) == 0) - return Timestamp::fromEpochTime(st.st_mtime); - else - handleError(_path); - return 0; -} - - -Timestamp FileImpl::getLastModifiedImpl() const -{ - poco_assert (!_path.empty()); - - struct stat st; - if (stat(_path.c_str(), &st) == 0) - return Timestamp::fromEpochTime(st.st_mtime); - else - handleError(_path); - return 0; -} - - -void FileImpl::setLastModifiedImpl(const Timestamp& ts) -{ - poco_assert (!_path.empty()); - - struct utimbuf tb; - tb.actime = ts.epochTime(); - tb.modtime = ts.epochTime(); - if (utime(_path.c_str(), &tb) != 0) - handleError(_path); -} - - -FileImpl::FileSizeImpl FileImpl::getSizeImpl() const -{ - poco_assert (!_path.empty()); - - struct stat st; - if (stat(_path.c_str(), &st) == 0) - return st.st_size; - else - handleError(_path); - return 0; -} - - -void FileImpl::setSizeImpl(FileSizeImpl size) -{ - poco_assert (!_path.empty()); - - if (truncate(_path.c_str(), size) != 0) - handleError(_path); -} - - -void FileImpl::setWriteableImpl(bool flag) -{ - poco_assert (!_path.empty()); - - struct stat st; - if (stat(_path.c_str(), &st) != 0) - handleError(_path); - mode_t mode; - if (flag) - { - mode = st.st_mode | S_IWUSR; - } - else - { - mode_t wmask = S_IWUSR | S_IWGRP | S_IWOTH; - mode = st.st_mode & ~wmask; - } - if (chmod(_path.c_str(), mode) != 0) - handleError(_path); -} - - -void FileImpl::copyToImpl(const std::string& path) const -{ - poco_assert (!_path.empty()); - - int sd = open(_path.c_str(), O_RDONLY); - if (sd == -1) handleError(_path); - - struct stat st; - if (fstat(sd, &st) != 0) - { - close(sd); - handleError(_path); - } - const long blockSize = st.st_blksize; - - int dd = open(path.c_str(), O_CREAT | O_TRUNC | O_WRONLY, st.st_mode & S_IRWXU); - if (dd == -1) - { - close(sd); - handleError(path); - } - Buffer buffer(blockSize); - try - { - int n; - while ((n = read(sd, buffer.begin(), blockSize)) > 0) - { - if (write(dd, buffer.begin(), n) != n) - handleError(path); - } - if (n < 0) - handleError(_path); - } - catch (...) - { - close(sd); - close(dd); - throw; - } - close(sd); - if (fsync(dd) != 0) - { - close(dd); - handleError(path); - } - if (close(dd) != 0) - handleError(path); -} - - -void FileImpl::renameToImpl(const std::string& path) -{ - poco_assert (!_path.empty()); - - if (rename(_path.c_str(), path.c_str()) != 0) - handleError(_path); -} - - -void FileImpl::removeImpl() -{ - poco_assert (!_path.empty()); - - int rc; - if (!isLinkImpl() && isDirectoryImpl()) - rc = rmdir(_path.c_str()); - else - rc = unlink(_path.c_str()); - if (rc) handleError(_path); -} - - -bool FileImpl::createFileImpl() -{ - poco_assert (!_path.empty()); - - int n = open(_path.c_str(), O_WRONLY | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR); - if (n != -1) - { - close(n); - return true; - } - if (n == -1 && errno == EEXIST) - return false; - else - handleError(_path); - return false; -} - - -bool FileImpl::createDirectoryImpl() -{ - poco_assert (!_path.empty()); - - if (existsImpl() && isDirectoryImpl()) - return false; - if (mkdir(_path.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) != 0) - handleError(_path); - return true; -} - - -void FileImpl::handleError(const std::string& path) -{ - switch (errno) - { - case EIO: - throw IOException(path); - case EPERM: - throw FileAccessDeniedException("insufficient permissions", path); - case EACCES: - throw FileAccessDeniedException(path); - case ENOENT: - throw FileNotFoundException(path); - case ENOTDIR: - throw OpenFileException("not a directory", path); - case EISDIR: - throw OpenFileException("not a file", path); - case EROFS: - throw FileReadOnlyException(path); - case EEXIST: - throw FileExistsException(path); - case ENOSPC: - throw FileException("no space left on device", path); - case EDQUOT: - throw FileException("disk quota exceeded", path); - case ENOTEMPTY: - throw FileException("directory not empty", path); - case ENAMETOOLONG: - throw PathSyntaxException(path); - default: - throw FileException(strerror(errno), path); - } -} - - -} // namespace Poco +// +// File_UNIX.cpp +// +// $Id: //poco/1.2/Foundation/src/File_UNIX.cpp#1 $ +// +// Library: Foundation +// Package: Filesystem +// Module: File +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/File_UNIX.h" +#include "Poco/Buffer.h" +#include "Poco/Exception.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace Poco { + + +FileImpl::FileImpl() +{ +} + + +FileImpl::FileImpl(const std::string& path): _path(path) +{ + std::string::size_type n = _path.size(); + if (n > 0 && _path[n - 1] == '/') + _path.resize(n - 1); +} + + +FileImpl::~FileImpl() +{ +} + + +void FileImpl::swapImpl(FileImpl& file) +{ + std::swap(_path, file._path); +} + + +void FileImpl::setPathImpl(const std::string& path) +{ + _path = path; +} + + +bool FileImpl::existsImpl() const +{ + poco_assert (!_path.empty()); + + struct stat st; + return stat(_path.c_str(), &st) == 0; +} + + +bool FileImpl::canReadImpl() const +{ + poco_assert (!_path.empty()); + + struct stat st; + if (stat(_path.c_str(), &st) == 0) + { + if (st.st_uid == geteuid()) + return (st.st_mode & S_IRUSR) != 0; + else if (st.st_gid == getegid()) + return (st.st_mode & S_IRGRP) != 0; + else + return (st.st_mode & S_IROTH) != 0; + } + else handleError(_path); + return false; +} + + +bool FileImpl::canWriteImpl() const +{ + poco_assert (!_path.empty()); + + struct stat st; + if (stat(_path.c_str(), &st) == 0) + { + if (st.st_uid == geteuid()) + return (st.st_mode & S_IWUSR) != 0; + else if (st.st_gid == getegid()) + return (st.st_mode & S_IWGRP) != 0; + else + return (st.st_mode & S_IWOTH) != 0; + } + else handleError(_path); + return false; +} + + +bool FileImpl::isFileImpl() const +{ + poco_assert (!_path.empty()); + + struct stat st; + if (stat(_path.c_str(), &st) == 0) + return S_ISREG(st.st_mode); + else + handleError(_path); + return false; +} + + +bool FileImpl::isDirectoryImpl() const +{ + poco_assert (!_path.empty()); + + struct stat st; + if (stat(_path.c_str(), &st) == 0) + return S_ISDIR(st.st_mode); + else + handleError(_path); + return false; +} + + +bool FileImpl::isLinkImpl() const +{ + poco_assert (!_path.empty()); + + struct stat st; + if (lstat(_path.c_str(), &st) == 0) + return S_ISLNK(st.st_mode); + else + handleError(_path); + return false; +} + + +Timestamp FileImpl::createdImpl() const +{ + poco_assert (!_path.empty()); + + struct stat st; + if (stat(_path.c_str(), &st) == 0) + return Timestamp::fromEpochTime(st.st_mtime); + else + handleError(_path); + return 0; +} + + +Timestamp FileImpl::getLastModifiedImpl() const +{ + poco_assert (!_path.empty()); + + struct stat st; + if (stat(_path.c_str(), &st) == 0) + return Timestamp::fromEpochTime(st.st_mtime); + else + handleError(_path); + return 0; +} + + +void FileImpl::setLastModifiedImpl(const Timestamp& ts) +{ + poco_assert (!_path.empty()); + + struct utimbuf tb; + tb.actime = ts.epochTime(); + tb.modtime = ts.epochTime(); + if (utime(_path.c_str(), &tb) != 0) + handleError(_path); +} + + +FileImpl::FileSizeImpl FileImpl::getSizeImpl() const +{ + poco_assert (!_path.empty()); + + struct stat st; + if (stat(_path.c_str(), &st) == 0) + return st.st_size; + else + handleError(_path); + return 0; +} + + +void FileImpl::setSizeImpl(FileSizeImpl size) +{ + poco_assert (!_path.empty()); + + if (truncate(_path.c_str(), size) != 0) + handleError(_path); +} + + +void FileImpl::setWriteableImpl(bool flag) +{ + poco_assert (!_path.empty()); + + struct stat st; + if (stat(_path.c_str(), &st) != 0) + handleError(_path); + mode_t mode; + if (flag) + { + mode = st.st_mode | S_IWUSR; + } + else + { + mode_t wmask = S_IWUSR | S_IWGRP | S_IWOTH; + mode = st.st_mode & ~wmask; + } + if (chmod(_path.c_str(), mode) != 0) + handleError(_path); +} + + +void FileImpl::copyToImpl(const std::string& path) const +{ + poco_assert (!_path.empty()); + + int sd = open(_path.c_str(), O_RDONLY); + if (sd == -1) handleError(_path); + + struct stat st; + if (fstat(sd, &st) != 0) + { + close(sd); + handleError(_path); + } + const long blockSize = st.st_blksize; + + int dd = open(path.c_str(), O_CREAT | O_TRUNC | O_WRONLY, st.st_mode & S_IRWXU); + if (dd == -1) + { + close(sd); + handleError(path); + } + Buffer buffer(blockSize); + try + { + int n; + while ((n = read(sd, buffer.begin(), blockSize)) > 0) + { + if (write(dd, buffer.begin(), n) != n) + handleError(path); + } + if (n < 0) + handleError(_path); + } + catch (...) + { + close(sd); + close(dd); + throw; + } + close(sd); + if (fsync(dd) != 0) + { + close(dd); + handleError(path); + } + if (close(dd) != 0) + handleError(path); +} + + +void FileImpl::renameToImpl(const std::string& path) +{ + poco_assert (!_path.empty()); + + if (rename(_path.c_str(), path.c_str()) != 0) + handleError(_path); +} + + +void FileImpl::removeImpl() +{ + poco_assert (!_path.empty()); + + int rc; + if (!isLinkImpl() && isDirectoryImpl()) + rc = rmdir(_path.c_str()); + else + rc = unlink(_path.c_str()); + if (rc) handleError(_path); +} + + +bool FileImpl::createFileImpl() +{ + poco_assert (!_path.empty()); + + int n = open(_path.c_str(), O_WRONLY | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR); + if (n != -1) + { + close(n); + return true; + } + if (n == -1 && errno == EEXIST) + return false; + else + handleError(_path); + return false; +} + + +bool FileImpl::createDirectoryImpl() +{ + poco_assert (!_path.empty()); + + if (existsImpl() && isDirectoryImpl()) + return false; + if (mkdir(_path.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) != 0) + handleError(_path); + return true; +} + + +void FileImpl::handleError(const std::string& path) +{ + switch (errno) + { + case EIO: + throw IOException(path); + case EPERM: + throw FileAccessDeniedException("insufficient permissions", path); + case EACCES: + throw FileAccessDeniedException(path); + case ENOENT: + throw FileNotFoundException(path); + case ENOTDIR: + throw OpenFileException("not a directory", path); + case EISDIR: + throw OpenFileException("not a file", path); + case EROFS: + throw FileReadOnlyException(path); + case EEXIST: + throw FileExistsException(path); + case ENOSPC: + throw FileException("no space left on device", path); + case EDQUOT: + throw FileException("disk quota exceeded", path); + case ENOTEMPTY: + throw FileException("directory not empty", path); + case ENAMETOOLONG: + throw PathSyntaxException(path); + default: + throw FileException(strerror(errno), path); + } +} + + +} // namespace Poco diff --git a/Foundation/src/File_VMS.cpp b/Foundation/src/File_VMS.cpp index 8e69062ab..cf5966391 100644 --- a/Foundation/src/File_VMS.cpp +++ b/Foundation/src/File_VMS.cpp @@ -1,381 +1,381 @@ -// -// File_VMS.cpp -// -// $Id: //poco/1.2/Foundation/src/File_VMS.cpp#1 $ -// -// Library: Foundation -// Package: Filesystem -// Module: File -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/File_VMS.h" -#include "Poco/Exception.h" -#include "Poco/Path.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - - -namespace Poco { - - -FileImpl::FileImpl() -{ -} - - -FileImpl::FileImpl(const std::string& path): _path(path) -{ - if (!_path.empty()) - { - Path p(_path); - p.makeFile(); - _path = p.toString(); - } -} - - -FileImpl::~FileImpl() -{ -} - - -void FileImpl::swapImpl(FileImpl& file) -{ - std::swap(_path, file._path); -} - - -void FileImpl::setPathImpl(const std::string& path) -{ - _path = path; -} - - -bool FileImpl::existsImpl() const -{ - poco_assert (!_path.empty()); - - return access(_path.c_str(), F_OK) == 0; -} - - -bool FileImpl::canReadImpl() const -{ - poco_assert (!_path.empty()); - - struct stat st; - if (stat(_path.c_str(), &st) == 0) - { - if (st.st_uid == geteuid()) - return (st.st_mode & S_IRUSR) != 0; - else if (st.st_gid == getegid()) - return (st.st_mode & S_IRGRP) != 0; - else - return (st.st_mode & S_IROTH) != 0; - } - else handleError(_path); - return false; -} - - -bool FileImpl::canWriteImpl() const -{ - poco_assert (!_path.empty()); - - struct stat st; - if (stat(_path.c_str(), &st) == 0) - { - if (st.st_uid == geteuid()) - return (st.st_mode & S_IWUSR) != 0; - else if (st.st_gid == getegid()) - return (st.st_mode & S_IWGRP) != 0; - else - return (st.st_mode & S_IWOTH) != 0; - } - else handleError(_path); - return false; -} - - -bool FileImpl::isFileImpl() const -{ - poco_assert (!_path.empty()); - - struct stat st; - if (stat(_path.c_str(), &st) == 0) - return S_ISREG(st.st_mode); - else - handleError(_path); - return false; -} - - -bool FileImpl::isDirectoryImpl() const -{ - poco_assert (!_path.empty()); - - struct stat st; - if (stat(_path.c_str(), &st) == 0) - return S_ISDIR(st.st_mode); - else - handleError(_path); - return false; -} - - -bool FileImpl::isLinkImpl() const -{ - return false; -} - - -Timestamp FileImpl::createdImpl() const -{ - poco_assert (!_path.empty()); - - struct stat st; - if (stat(_path.c_str(), &st) == 0) - return Timestamp(st.st_mtime); - else - handleError(_path); - return 0; -} - - -Timestamp FileImpl::getLastModifiedImpl() const -{ - poco_assert (!_path.empty()); - - struct stat st; - if (stat(_path.c_str(), &st) == 0) - return Timestamp(st.st_mtime); - else - handleError(_path); - return 0; -} - - -void FileImpl::setLastModifiedImpl(const Timestamp& ts) -{ - poco_assert (!_path.empty()); - - struct utimbuf tb; - tb.actime = ts.epochTime(); - tb.modtime = ts.epochTime(); - if (utime(_path.c_str(), &tb) != 0) - handleError(_path); -} - - -FileImpl::FileSizeImpl FileImpl::getSizeImpl() const -{ - poco_assert (!_path.empty()); - - struct stat st; - if (stat(_path.c_str(), &st) == 0) - return st.st_size; - else - handleError(_path); - return 0; -} - - -void FileImpl::setSizeImpl(FileSizeImpl size) -{ - poco_assert (!_path.empty()); - - if (truncate(_path.c_str(), size) != 0) - handleError(_path); -} - - -void FileImpl::setWriteableImpl(bool flag) -{ - poco_assert (!_path.empty()); - - struct stat st; - if (stat(_path.c_str(), &st) != 0) - handleError(_path); - mode_t mode; - if (flag) - { - mode = st.st_mode | S_IWUSR; - } - else - { - mode_t wmask = S_IWUSR | S_IWGRP | S_IWOTH; - mode = st.st_mode & ~wmask; - } - if (chmod(_path.c_str(), mode) != 0) - handleError(_path); -} - - -void FileImpl::copyToImpl(const std::string& path) const -{ - poco_assert (!_path.empty()); - - // copying a file correctly under OpenVMS is non-trivial, - // so we just invoke the COPY program. - std::string cmd = "COPY "; - cmd.append(_path); - cmd.append(" "); - cmd.append(path); - if (system(cmd.c_str()) != 0) - throw FileException("COPY command failed", _path); -} - - -void FileImpl::renameToImpl(const std::string& path) -{ - poco_assert (!_path.empty()); - - POCO_DESCRIPTOR_STRING(oldNameDsc, _path); - POCO_DESCRIPTOR_STRING(newNameDsc, path); - - int res; - if ((res = lib$rename_file(&oldNameDsc, &newNameDsc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)) != 1) - { - switch (res & 0x0FFFFFFF) - { - case RMS$_FNF: - throw FileNotFoundException(_path); - case RMS$_DEV: - case RMS$_DNF: - throw PathNotFoundException(_path); - case RMS$_SYN: - throw PathSyntaxException(path); - case RMS$_RMV: - throw FileAccessDeniedException(_path); - case RMS$_PRV: - throw FileAccessDeniedException("insufficient privileges", _path); - default: - throw FileException(path); - } - } -} - - -void FileImpl::removeImpl() -{ - poco_assert (!_path.empty()); - - int rc; - if (isDirectoryImpl()) - { - setWriteableImpl(true); - rc = rmdir(_path.c_str()); - } - else - { - rc = unlink(_path.c_str()); - } - if (rc) handleError(_path); -} - - - -bool FileImpl::createFileImpl() -{ - poco_assert (!_path.empty()); - - int n = open(_path.c_str(), O_WRONLY | O_CREAT | O_EXCL); - if (n != -1) - { - close(n); - return true; - } - if (n == -1 && errno == EEXIST) - return false; - else - handleError(_path); - return false; -} - - -bool FileImpl::createDirectoryImpl() -{ - poco_assert (!_path.empty()); - - if (existsImpl() && isDirectoryImpl()) - return false; - Path p(_path); - p.makeDirectory(); - if (mkdir(p.toString().c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) != 0) - handleError(_path); - return true; -} - - -void FileImpl::handleError(const std::string& path) -{ - switch (errno) - { - case EIO: - throw IOException(path); - case EPERM: - throw FileAccessDeniedException("insufficient permissions", path); - case EACCES: - throw FileAccessDeniedException(path); - case ENOENT: - throw FileNotFoundException(path); - case ENOTDIR: - throw OpenFileException("not a directory", path); - case EISDIR: - throw OpenFileException("not a file", path); - case EROFS: - throw FileReadOnlyException(path); - case EEXIST: - throw FileExistsException(path); - case ENOSPC: - throw FileException("no space left on device", path); - case EDQUOT: - throw FileException("disk quota exceeded", path); - case ENOTEMPTY: - throw FileException("directory not empty", path); - case ENAMETOOLONG: - throw PathSyntaxException(path); - default: - throw FileException(strerror(errno), path); - } -} - - -} // namespace Poco +// +// File_VMS.cpp +// +// $Id: //poco/1.2/Foundation/src/File_VMS.cpp#1 $ +// +// Library: Foundation +// Package: Filesystem +// Module: File +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/File_VMS.h" +#include "Poco/Exception.h" +#include "Poco/Path.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace Poco { + + +FileImpl::FileImpl() +{ +} + + +FileImpl::FileImpl(const std::string& path): _path(path) +{ + if (!_path.empty()) + { + Path p(_path); + p.makeFile(); + _path = p.toString(); + } +} + + +FileImpl::~FileImpl() +{ +} + + +void FileImpl::swapImpl(FileImpl& file) +{ + std::swap(_path, file._path); +} + + +void FileImpl::setPathImpl(const std::string& path) +{ + _path = path; +} + + +bool FileImpl::existsImpl() const +{ + poco_assert (!_path.empty()); + + return access(_path.c_str(), F_OK) == 0; +} + + +bool FileImpl::canReadImpl() const +{ + poco_assert (!_path.empty()); + + struct stat st; + if (stat(_path.c_str(), &st) == 0) + { + if (st.st_uid == geteuid()) + return (st.st_mode & S_IRUSR) != 0; + else if (st.st_gid == getegid()) + return (st.st_mode & S_IRGRP) != 0; + else + return (st.st_mode & S_IROTH) != 0; + } + else handleError(_path); + return false; +} + + +bool FileImpl::canWriteImpl() const +{ + poco_assert (!_path.empty()); + + struct stat st; + if (stat(_path.c_str(), &st) == 0) + { + if (st.st_uid == geteuid()) + return (st.st_mode & S_IWUSR) != 0; + else if (st.st_gid == getegid()) + return (st.st_mode & S_IWGRP) != 0; + else + return (st.st_mode & S_IWOTH) != 0; + } + else handleError(_path); + return false; +} + + +bool FileImpl::isFileImpl() const +{ + poco_assert (!_path.empty()); + + struct stat st; + if (stat(_path.c_str(), &st) == 0) + return S_ISREG(st.st_mode); + else + handleError(_path); + return false; +} + + +bool FileImpl::isDirectoryImpl() const +{ + poco_assert (!_path.empty()); + + struct stat st; + if (stat(_path.c_str(), &st) == 0) + return S_ISDIR(st.st_mode); + else + handleError(_path); + return false; +} + + +bool FileImpl::isLinkImpl() const +{ + return false; +} + + +Timestamp FileImpl::createdImpl() const +{ + poco_assert (!_path.empty()); + + struct stat st; + if (stat(_path.c_str(), &st) == 0) + return Timestamp(st.st_mtime); + else + handleError(_path); + return 0; +} + + +Timestamp FileImpl::getLastModifiedImpl() const +{ + poco_assert (!_path.empty()); + + struct stat st; + if (stat(_path.c_str(), &st) == 0) + return Timestamp(st.st_mtime); + else + handleError(_path); + return 0; +} + + +void FileImpl::setLastModifiedImpl(const Timestamp& ts) +{ + poco_assert (!_path.empty()); + + struct utimbuf tb; + tb.actime = ts.epochTime(); + tb.modtime = ts.epochTime(); + if (utime(_path.c_str(), &tb) != 0) + handleError(_path); +} + + +FileImpl::FileSizeImpl FileImpl::getSizeImpl() const +{ + poco_assert (!_path.empty()); + + struct stat st; + if (stat(_path.c_str(), &st) == 0) + return st.st_size; + else + handleError(_path); + return 0; +} + + +void FileImpl::setSizeImpl(FileSizeImpl size) +{ + poco_assert (!_path.empty()); + + if (truncate(_path.c_str(), size) != 0) + handleError(_path); +} + + +void FileImpl::setWriteableImpl(bool flag) +{ + poco_assert (!_path.empty()); + + struct stat st; + if (stat(_path.c_str(), &st) != 0) + handleError(_path); + mode_t mode; + if (flag) + { + mode = st.st_mode | S_IWUSR; + } + else + { + mode_t wmask = S_IWUSR | S_IWGRP | S_IWOTH; + mode = st.st_mode & ~wmask; + } + if (chmod(_path.c_str(), mode) != 0) + handleError(_path); +} + + +void FileImpl::copyToImpl(const std::string& path) const +{ + poco_assert (!_path.empty()); + + // copying a file correctly under OpenVMS is non-trivial, + // so we just invoke the COPY program. + std::string cmd = "COPY "; + cmd.append(_path); + cmd.append(" "); + cmd.append(path); + if (system(cmd.c_str()) != 0) + throw FileException("COPY command failed", _path); +} + + +void FileImpl::renameToImpl(const std::string& path) +{ + poco_assert (!_path.empty()); + + POCO_DESCRIPTOR_STRING(oldNameDsc, _path); + POCO_DESCRIPTOR_STRING(newNameDsc, path); + + int res; + if ((res = lib$rename_file(&oldNameDsc, &newNameDsc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)) != 1) + { + switch (res & 0x0FFFFFFF) + { + case RMS$_FNF: + throw FileNotFoundException(_path); + case RMS$_DEV: + case RMS$_DNF: + throw PathNotFoundException(_path); + case RMS$_SYN: + throw PathSyntaxException(path); + case RMS$_RMV: + throw FileAccessDeniedException(_path); + case RMS$_PRV: + throw FileAccessDeniedException("insufficient privileges", _path); + default: + throw FileException(path); + } + } +} + + +void FileImpl::removeImpl() +{ + poco_assert (!_path.empty()); + + int rc; + if (isDirectoryImpl()) + { + setWriteableImpl(true); + rc = rmdir(_path.c_str()); + } + else + { + rc = unlink(_path.c_str()); + } + if (rc) handleError(_path); +} + + + +bool FileImpl::createFileImpl() +{ + poco_assert (!_path.empty()); + + int n = open(_path.c_str(), O_WRONLY | O_CREAT | O_EXCL); + if (n != -1) + { + close(n); + return true; + } + if (n == -1 && errno == EEXIST) + return false; + else + handleError(_path); + return false; +} + + +bool FileImpl::createDirectoryImpl() +{ + poco_assert (!_path.empty()); + + if (existsImpl() && isDirectoryImpl()) + return false; + Path p(_path); + p.makeDirectory(); + if (mkdir(p.toString().c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) != 0) + handleError(_path); + return true; +} + + +void FileImpl::handleError(const std::string& path) +{ + switch (errno) + { + case EIO: + throw IOException(path); + case EPERM: + throw FileAccessDeniedException("insufficient permissions", path); + case EACCES: + throw FileAccessDeniedException(path); + case ENOENT: + throw FileNotFoundException(path); + case ENOTDIR: + throw OpenFileException("not a directory", path); + case EISDIR: + throw OpenFileException("not a file", path); + case EROFS: + throw FileReadOnlyException(path); + case EEXIST: + throw FileExistsException(path); + case ENOSPC: + throw FileException("no space left on device", path); + case EDQUOT: + throw FileException("disk quota exceeded", path); + case ENOTEMPTY: + throw FileException("directory not empty", path); + case ENAMETOOLONG: + throw PathSyntaxException(path); + default: + throw FileException(strerror(errno), path); + } +} + + +} // namespace Poco diff --git a/Foundation/src/File_WIN32.cpp b/Foundation/src/File_WIN32.cpp index c6de51f6c..091a5294d 100644 --- a/Foundation/src/File_WIN32.cpp +++ b/Foundation/src/File_WIN32.cpp @@ -1,359 +1,359 @@ -// -// File_WIN32.cpp -// -// $Id: //poco/1.2/Foundation/src/File_WIN32.cpp#1 $ -// -// Library: Foundation -// Package: Filesystem -// Module: File -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/File_WIN32.h" -#include "Poco/Exception.h" -#include - - -namespace Poco { - - -class FileHandle -{ -public: - FileHandle(const std::string& path, DWORD access, DWORD share, DWORD disp) - { - _h = CreateFile(path.c_str(), access, share, 0, disp, 0, 0); - if (!_h) FileImpl::handleError(path); - } - - ~FileHandle() - { - if (_h) CloseHandle(_h); - } - - HANDLE get() const - { - return _h; - } - -private: - HANDLE _h; -}; - - -FileImpl::FileImpl() -{ -} - - -FileImpl::FileImpl(const std::string& path): _path(path) -{ - std::string::size_type n = _path.size(); - if (n > 0 && (_path[n - 1] == '\\' || _path[n - 1] == '/')) - _path.resize(n - 1); -} - - -FileImpl::~FileImpl() -{ -} - - -void FileImpl::swapImpl(FileImpl& file) -{ - std::swap(_path, file._path); -} - - -void FileImpl::setPathImpl(const std::string& path) -{ - _path = path; -} - - -bool FileImpl::existsImpl() const -{ - poco_assert (!_path.empty()); - - DWORD attr = GetFileAttributes(_path.c_str()); - if (attr == 0xFFFFFFFF) - { - switch (GetLastError()) - { - case ERROR_FILE_NOT_FOUND: - case ERROR_PATH_NOT_FOUND: - case ERROR_NOT_READY: - case ERROR_INVALID_DRIVE: - return false; - default: - handleError(_path); - } - } - return true; -} - - -bool FileImpl::canReadImpl() const -{ - poco_assert (!_path.empty()); - - DWORD attr = GetFileAttributes(_path.c_str()); - if (attr == 0xFFFFFFFF) - { - switch (GetLastError()) - { - case ERROR_ACCESS_DENIED: - return false; - default: - handleError(_path); - } - } - return true; -} - - -bool FileImpl::canWriteImpl() const -{ - poco_assert (!_path.empty()); - - DWORD attr = GetFileAttributes(_path.c_str()); - if (attr == 0xFFFFFFFF) - handleError(_path); - return (attr & FILE_ATTRIBUTE_READONLY) == 0; -} - - -bool FileImpl::isFileImpl() const -{ - poco_assert (!_path.empty()); - - DWORD attr = GetFileAttributes(_path.c_str()); - if (attr == 0xFFFFFFFF) - handleError(_path); - return (attr & FILE_ATTRIBUTE_DIRECTORY) == 0; -} - - -bool FileImpl::isDirectoryImpl() const -{ - poco_assert (!_path.empty()); - - DWORD attr = GetFileAttributes(_path.c_str()); - if (attr == 0xFFFFFFFF) - handleError(_path); - return (attr & FILE_ATTRIBUTE_DIRECTORY) != 0; -} - - -bool FileImpl::isLinkImpl() const -{ - return false; -} - - -Timestamp FileImpl::createdImpl() const -{ - poco_assert (!_path.empty()); - - WIN32_FILE_ATTRIBUTE_DATA fad; - if (GetFileAttributesEx(_path.c_str(), GetFileExInfoStandard, &fad) == 0) - handleError(_path); - return Timestamp::fromFileTimeNP(fad.ftCreationTime.dwLowDateTime, fad.ftCreationTime.dwHighDateTime); -} - - -Timestamp FileImpl::getLastModifiedImpl() const -{ - poco_assert (!_path.empty()); - - WIN32_FILE_ATTRIBUTE_DATA fad; - if (GetFileAttributesEx(_path.c_str(), GetFileExInfoStandard, &fad) == 0) - handleError(_path); - return Timestamp::fromFileTimeNP(fad.ftLastWriteTime.dwLowDateTime, fad.ftLastWriteTime.dwHighDateTime); -} - - -void FileImpl::setLastModifiedImpl(const Timestamp& ts) -{ - poco_assert (!_path.empty()); - - UInt32 low; - UInt32 high; - ts.toFileTimeNP(low, high); - FILETIME ft; - ft.dwLowDateTime = low; - ft.dwHighDateTime = high; - FileHandle fh(_path, FILE_ALL_ACCESS, FILE_SHARE_WRITE, OPEN_EXISTING); - if (SetFileTime(fh.get(), 0, &ft, &ft) == 0) - handleError(_path); -} - - -FileImpl::FileSizeImpl FileImpl::getSizeImpl() const -{ - poco_assert (!_path.empty()); - - WIN32_FILE_ATTRIBUTE_DATA fad; - if (GetFileAttributesEx(_path.c_str(), GetFileExInfoStandard, &fad) == 0) - handleError(_path); - LARGE_INTEGER li; - li.LowPart = fad.nFileSizeLow; - li.HighPart = fad.nFileSizeHigh; - return li.QuadPart; -} - - -void FileImpl::setSizeImpl(FileSizeImpl size) -{ - poco_assert (!_path.empty()); - - FileHandle fh(_path, GENERIC_WRITE, FILE_SHARE_WRITE, OPEN_EXISTING); - LARGE_INTEGER li; - li.QuadPart = size; - if (SetFilePointer(fh.get(), li.LowPart, &li.HighPart, FILE_BEGIN) == -1) - handleError(_path); - if (SetEndOfFile(fh.get()) == 0) - handleError(_path); -} - - -void FileImpl::setWriteableImpl(bool flag) -{ - poco_assert (!_path.empty()); - - DWORD attr = GetFileAttributes(_path.c_str()); - if (attr == -1) - handleError(_path); - if (flag) - attr &= ~FILE_ATTRIBUTE_READONLY; - else - attr |= FILE_ATTRIBUTE_READONLY; - if (SetFileAttributes(_path.c_str(), attr) == 0) - handleError(_path); -} - - -void FileImpl::copyToImpl(const std::string& path) const -{ - poco_assert (!_path.empty()); - - if (CopyFile(_path.c_str(), path.c_str(), FALSE) == 0) - handleError(_path); -} - - -void FileImpl::renameToImpl(const std::string& path) -{ - poco_assert (!_path.empty()); - - if (MoveFile(_path.c_str(), path.c_str()) == 0) - handleError(_path); -} - - -void FileImpl::removeImpl() -{ - poco_assert (!_path.empty()); - - if (isDirectoryImpl()) - { - if (RemoveDirectory(_path.c_str()) == 0) - handleError(_path); - } - else - { - if (DeleteFile(_path.c_str()) == 0) - handleError(_path); - } -} - - -bool FileImpl::createFileImpl() -{ - poco_assert (!_path.empty()); - - HANDLE hFile = CreateFile(_path.c_str(), GENERIC_WRITE, 0, 0, CREATE_NEW, 0, 0); - if (hFile) - { - CloseHandle(hFile); - return true; - } - else if (GetLastError() == ERROR_ALREADY_EXISTS) - return false; - else - handleError(_path); - return false; -} - - -bool FileImpl::createDirectoryImpl() -{ - poco_assert (!_path.empty()); - - if (existsImpl() && isDirectoryImpl()) - return false; - if (CreateDirectory(_path.c_str(), 0) == 0) - handleError(_path); - return true; -} - - -void FileImpl::handleError(const std::string& path) -{ - switch (GetLastError()) - { - case ERROR_FILE_NOT_FOUND: - throw FileNotFoundException(path); - case ERROR_PATH_NOT_FOUND: - case ERROR_BAD_NETPATH: - case ERROR_CANT_RESOLVE_FILENAME: - case ERROR_INVALID_DRIVE: - throw PathNotFoundException(path); - case ERROR_ACCESS_DENIED: - throw FileAccessDeniedException(path); - case ERROR_ALREADY_EXISTS: - case ERROR_FILE_EXISTS: - throw FileExistsException(path); - case ERROR_INVALID_NAME: - case ERROR_DIRECTORY: - case ERROR_FILENAME_EXCED_RANGE: - case ERROR_BAD_PATHNAME: - throw PathSyntaxException(path); - case ERROR_FILE_READ_ONLY: - throw FileReadOnlyException(path); - case ERROR_CANNOT_MAKE: - throw CreateFileException(path); - case ERROR_DIR_NOT_EMPTY: - throw FileException("directory not empty", path); - default: - throw FileException(path); - } -} - - -} // namespace Poco +// +// File_WIN32.cpp +// +// $Id: //poco/1.2/Foundation/src/File_WIN32.cpp#1 $ +// +// Library: Foundation +// Package: Filesystem +// Module: File +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/File_WIN32.h" +#include "Poco/Exception.h" +#include + + +namespace Poco { + + +class FileHandle +{ +public: + FileHandle(const std::string& path, DWORD access, DWORD share, DWORD disp) + { + _h = CreateFile(path.c_str(), access, share, 0, disp, 0, 0); + if (!_h) FileImpl::handleError(path); + } + + ~FileHandle() + { + if (_h) CloseHandle(_h); + } + + HANDLE get() const + { + return _h; + } + +private: + HANDLE _h; +}; + + +FileImpl::FileImpl() +{ +} + + +FileImpl::FileImpl(const std::string& path): _path(path) +{ + std::string::size_type n = _path.size(); + if (n > 0 && (_path[n - 1] == '\\' || _path[n - 1] == '/')) + _path.resize(n - 1); +} + + +FileImpl::~FileImpl() +{ +} + + +void FileImpl::swapImpl(FileImpl& file) +{ + std::swap(_path, file._path); +} + + +void FileImpl::setPathImpl(const std::string& path) +{ + _path = path; +} + + +bool FileImpl::existsImpl() const +{ + poco_assert (!_path.empty()); + + DWORD attr = GetFileAttributes(_path.c_str()); + if (attr == 0xFFFFFFFF) + { + switch (GetLastError()) + { + case ERROR_FILE_NOT_FOUND: + case ERROR_PATH_NOT_FOUND: + case ERROR_NOT_READY: + case ERROR_INVALID_DRIVE: + return false; + default: + handleError(_path); + } + } + return true; +} + + +bool FileImpl::canReadImpl() const +{ + poco_assert (!_path.empty()); + + DWORD attr = GetFileAttributes(_path.c_str()); + if (attr == 0xFFFFFFFF) + { + switch (GetLastError()) + { + case ERROR_ACCESS_DENIED: + return false; + default: + handleError(_path); + } + } + return true; +} + + +bool FileImpl::canWriteImpl() const +{ + poco_assert (!_path.empty()); + + DWORD attr = GetFileAttributes(_path.c_str()); + if (attr == 0xFFFFFFFF) + handleError(_path); + return (attr & FILE_ATTRIBUTE_READONLY) == 0; +} + + +bool FileImpl::isFileImpl() const +{ + poco_assert (!_path.empty()); + + DWORD attr = GetFileAttributes(_path.c_str()); + if (attr == 0xFFFFFFFF) + handleError(_path); + return (attr & FILE_ATTRIBUTE_DIRECTORY) == 0; +} + + +bool FileImpl::isDirectoryImpl() const +{ + poco_assert (!_path.empty()); + + DWORD attr = GetFileAttributes(_path.c_str()); + if (attr == 0xFFFFFFFF) + handleError(_path); + return (attr & FILE_ATTRIBUTE_DIRECTORY) != 0; +} + + +bool FileImpl::isLinkImpl() const +{ + return false; +} + + +Timestamp FileImpl::createdImpl() const +{ + poco_assert (!_path.empty()); + + WIN32_FILE_ATTRIBUTE_DATA fad; + if (GetFileAttributesEx(_path.c_str(), GetFileExInfoStandard, &fad) == 0) + handleError(_path); + return Timestamp::fromFileTimeNP(fad.ftCreationTime.dwLowDateTime, fad.ftCreationTime.dwHighDateTime); +} + + +Timestamp FileImpl::getLastModifiedImpl() const +{ + poco_assert (!_path.empty()); + + WIN32_FILE_ATTRIBUTE_DATA fad; + if (GetFileAttributesEx(_path.c_str(), GetFileExInfoStandard, &fad) == 0) + handleError(_path); + return Timestamp::fromFileTimeNP(fad.ftLastWriteTime.dwLowDateTime, fad.ftLastWriteTime.dwHighDateTime); +} + + +void FileImpl::setLastModifiedImpl(const Timestamp& ts) +{ + poco_assert (!_path.empty()); + + UInt32 low; + UInt32 high; + ts.toFileTimeNP(low, high); + FILETIME ft; + ft.dwLowDateTime = low; + ft.dwHighDateTime = high; + FileHandle fh(_path, FILE_ALL_ACCESS, FILE_SHARE_WRITE, OPEN_EXISTING); + if (SetFileTime(fh.get(), 0, &ft, &ft) == 0) + handleError(_path); +} + + +FileImpl::FileSizeImpl FileImpl::getSizeImpl() const +{ + poco_assert (!_path.empty()); + + WIN32_FILE_ATTRIBUTE_DATA fad; + if (GetFileAttributesEx(_path.c_str(), GetFileExInfoStandard, &fad) == 0) + handleError(_path); + LARGE_INTEGER li; + li.LowPart = fad.nFileSizeLow; + li.HighPart = fad.nFileSizeHigh; + return li.QuadPart; +} + + +void FileImpl::setSizeImpl(FileSizeImpl size) +{ + poco_assert (!_path.empty()); + + FileHandle fh(_path, GENERIC_WRITE, FILE_SHARE_WRITE, OPEN_EXISTING); + LARGE_INTEGER li; + li.QuadPart = size; + if (SetFilePointer(fh.get(), li.LowPart, &li.HighPart, FILE_BEGIN) == -1) + handleError(_path); + if (SetEndOfFile(fh.get()) == 0) + handleError(_path); +} + + +void FileImpl::setWriteableImpl(bool flag) +{ + poco_assert (!_path.empty()); + + DWORD attr = GetFileAttributes(_path.c_str()); + if (attr == -1) + handleError(_path); + if (flag) + attr &= ~FILE_ATTRIBUTE_READONLY; + else + attr |= FILE_ATTRIBUTE_READONLY; + if (SetFileAttributes(_path.c_str(), attr) == 0) + handleError(_path); +} + + +void FileImpl::copyToImpl(const std::string& path) const +{ + poco_assert (!_path.empty()); + + if (CopyFile(_path.c_str(), path.c_str(), FALSE) == 0) + handleError(_path); +} + + +void FileImpl::renameToImpl(const std::string& path) +{ + poco_assert (!_path.empty()); + + if (MoveFile(_path.c_str(), path.c_str()) == 0) + handleError(_path); +} + + +void FileImpl::removeImpl() +{ + poco_assert (!_path.empty()); + + if (isDirectoryImpl()) + { + if (RemoveDirectory(_path.c_str()) == 0) + handleError(_path); + } + else + { + if (DeleteFile(_path.c_str()) == 0) + handleError(_path); + } +} + + +bool FileImpl::createFileImpl() +{ + poco_assert (!_path.empty()); + + HANDLE hFile = CreateFile(_path.c_str(), GENERIC_WRITE, 0, 0, CREATE_NEW, 0, 0); + if (hFile) + { + CloseHandle(hFile); + return true; + } + else if (GetLastError() == ERROR_ALREADY_EXISTS) + return false; + else + handleError(_path); + return false; +} + + +bool FileImpl::createDirectoryImpl() +{ + poco_assert (!_path.empty()); + + if (existsImpl() && isDirectoryImpl()) + return false; + if (CreateDirectory(_path.c_str(), 0) == 0) + handleError(_path); + return true; +} + + +void FileImpl::handleError(const std::string& path) +{ + switch (GetLastError()) + { + case ERROR_FILE_NOT_FOUND: + throw FileNotFoundException(path); + case ERROR_PATH_NOT_FOUND: + case ERROR_BAD_NETPATH: + case ERROR_CANT_RESOLVE_FILENAME: + case ERROR_INVALID_DRIVE: + throw PathNotFoundException(path); + case ERROR_ACCESS_DENIED: + throw FileAccessDeniedException(path); + case ERROR_ALREADY_EXISTS: + case ERROR_FILE_EXISTS: + throw FileExistsException(path); + case ERROR_INVALID_NAME: + case ERROR_DIRECTORY: + case ERROR_FILENAME_EXCED_RANGE: + case ERROR_BAD_PATHNAME: + throw PathSyntaxException(path); + case ERROR_FILE_READ_ONLY: + throw FileReadOnlyException(path); + case ERROR_CANNOT_MAKE: + throw CreateFileException(path); + case ERROR_DIR_NOT_EMPTY: + throw FileException("directory not empty", path); + default: + throw FileException(path); + } +} + + +} // namespace Poco diff --git a/Foundation/src/File_WIN32U.cpp b/Foundation/src/File_WIN32U.cpp index bbef37384..ce4234d96 100644 --- a/Foundation/src/File_WIN32U.cpp +++ b/Foundation/src/File_WIN32U.cpp @@ -1,367 +1,367 @@ -// -// File_WIN32U.cpp -// -// $Id: //poco/1.2/Foundation/src/File_WIN32U.cpp#1 $ -// -// Library: Foundation -// Package: Filesystem -// Module: File -// -// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/File_WIN32U.h" -#include "Poco/Exception.h" -#include "Poco/UnicodeConverter.h" -#include - - -namespace Poco { - - -class FileHandle -{ -public: - FileHandle(const std::string& path, const std::wstring& upath, DWORD access, DWORD share, DWORD disp) - { - _h = CreateFileW(upath.c_str(), access, share, 0, disp, 0, 0); - if (!_h) FileImpl::handleError(path); - } - - ~FileHandle() - { - if (_h) CloseHandle(_h); - } - - HANDLE get() const - { - return _h; - } - -private: - HANDLE _h; -}; - - -FileImpl::FileImpl() -{ -} - - -FileImpl::FileImpl(const std::string& path): _path(path) -{ - std::string::size_type n = _path.size(); - if (n > 0 && (_path[n - 1] == '\\' || _path[n - 1] == '/')) - _path.resize(n - 1); - UnicodeConverter::toUTF16(_path, _upath); -} - - -FileImpl::~FileImpl() -{ -} - - -void FileImpl::swapImpl(FileImpl& file) -{ - std::swap(_path, file._path); - std::swap(_upath, file._upath); -} - - -void FileImpl::setPathImpl(const std::string& path) -{ - _path = path; - UnicodeConverter::toUTF16(_path, _upath); -} - - -bool FileImpl::existsImpl() const -{ - poco_assert (!_path.empty()); - - DWORD attr = GetFileAttributesW(_upath.c_str()); - if (attr == 0xFFFFFFFF) - { - switch (GetLastError()) - { - case ERROR_FILE_NOT_FOUND: - case ERROR_PATH_NOT_FOUND: - case ERROR_NOT_READY: - case ERROR_INVALID_DRIVE: - return false; - default: - handleError(_path); - } - } - return true; -} - - -bool FileImpl::canReadImpl() const -{ - poco_assert (!_path.empty()); - - DWORD attr = GetFileAttributesW(_upath.c_str()); - if (attr == 0xFFFFFFFF) - { - switch (GetLastError()) - { - case ERROR_ACCESS_DENIED: - return false; - default: - handleError(_path); - } - } - return true; -} - - -bool FileImpl::canWriteImpl() const -{ - poco_assert (!_path.empty()); - - DWORD attr = GetFileAttributesW(_upath.c_str()); - if (attr == 0xFFFFFFFF) - handleError(_path); - return (attr & FILE_ATTRIBUTE_READONLY) == 0; -} - - -bool FileImpl::isFileImpl() const -{ - poco_assert (!_path.empty()); - - DWORD attr = GetFileAttributesW(_upath.c_str()); - if (attr == 0xFFFFFFFF) - handleError(_path); - return (attr & FILE_ATTRIBUTE_DIRECTORY) == 0; -} - - -bool FileImpl::isDirectoryImpl() const -{ - poco_assert (!_path.empty()); - - DWORD attr = GetFileAttributesW(_upath.c_str()); - if (attr == 0xFFFFFFFF) - handleError(_path); - return (attr & FILE_ATTRIBUTE_DIRECTORY) != 0; -} - - -bool FileImpl::isLinkImpl() const -{ - return false; -} - - -Timestamp FileImpl::createdImpl() const -{ - poco_assert (!_path.empty()); - - WIN32_FILE_ATTRIBUTE_DATA fad; - if (GetFileAttributesExW(_upath.c_str(), GetFileExInfoStandard, &fad) == 0) - handleError(_path); - return Timestamp::fromFileTimeNP(fad.ftCreationTime.dwLowDateTime, fad.ftCreationTime.dwHighDateTime); -} - - -Timestamp FileImpl::getLastModifiedImpl() const -{ - poco_assert (!_path.empty()); - - WIN32_FILE_ATTRIBUTE_DATA fad; - if (GetFileAttributesExW(_upath.c_str(), GetFileExInfoStandard, &fad) == 0) - handleError(_path); - return Timestamp::fromFileTimeNP(fad.ftLastWriteTime.dwLowDateTime, fad.ftLastWriteTime.dwHighDateTime); -} - - -void FileImpl::setLastModifiedImpl(const Timestamp& ts) -{ - poco_assert (!_path.empty()); - - UInt32 low; - UInt32 high; - ts.toFileTimeNP(low, high); - FILETIME ft; - ft.dwLowDateTime = low; - ft.dwHighDateTime = high; - FileHandle fh(_path, _upath, FILE_ALL_ACCESS, FILE_SHARE_WRITE, OPEN_EXISTING); - if (SetFileTime(fh.get(), 0, &ft, &ft) == 0) - handleError(_path); -} - - -FileImpl::FileSizeImpl FileImpl::getSizeImpl() const -{ - poco_assert (!_path.empty()); - - WIN32_FILE_ATTRIBUTE_DATA fad; - if (GetFileAttributesExW(_upath.c_str(), GetFileExInfoStandard, &fad) == 0) - handleError(_path); - LARGE_INTEGER li; - li.LowPart = fad.nFileSizeLow; - li.HighPart = fad.nFileSizeHigh; - return li.QuadPart; -} - - -void FileImpl::setSizeImpl(FileSizeImpl size) -{ - poco_assert (!_path.empty()); - - FileHandle fh(_path, _upath, GENERIC_WRITE, FILE_SHARE_WRITE, OPEN_EXISTING); - LARGE_INTEGER li; - li.QuadPart = size; - if (SetFilePointer(fh.get(), li.LowPart, &li.HighPart, FILE_BEGIN) == -1) - handleError(_path); - if (SetEndOfFile(fh.get()) == 0) - handleError(_path); -} - - -void FileImpl::setWriteableImpl(bool flag) -{ - poco_assert (!_path.empty()); - - DWORD attr = GetFileAttributesW(_upath.c_str()); - if (attr == -1) - handleError(_path); - if (flag) - attr &= ~FILE_ATTRIBUTE_READONLY; - else - attr |= FILE_ATTRIBUTE_READONLY; - if (SetFileAttributesW(_upath.c_str(), attr) == 0) - handleError(_path); -} - - -void FileImpl::copyToImpl(const std::string& path) const -{ - poco_assert (!_path.empty()); - - std::wstring upath; - UnicodeConverter::toUTF16(path, upath); - if (CopyFileW(_upath.c_str(), upath.c_str(), FALSE) == 0) - handleError(_path); -} - - -void FileImpl::renameToImpl(const std::string& path) -{ - poco_assert (!_path.empty()); - - std::wstring upath; - UnicodeConverter::toUTF16(path, upath); - if (MoveFileW(_upath.c_str(), upath.c_str()) == 0) - handleError(_path); -} - - -void FileImpl::removeImpl() -{ - poco_assert (!_path.empty()); - - if (isDirectoryImpl()) - { - if (RemoveDirectoryW(_upath.c_str()) == 0) - handleError(_path); - } - else - { - if (DeleteFileW(_upath.c_str()) == 0) - handleError(_path); - } -} - - -bool FileImpl::createFileImpl() -{ - poco_assert (!_path.empty()); - - HANDLE hFile = CreateFileW(_upath.c_str(), GENERIC_WRITE, 0, 0, CREATE_NEW, 0, 0); - if (hFile) - { - CloseHandle(hFile); - return true; - } - else if (GetLastError() == ERROR_ALREADY_EXISTS) - return false; - else - handleError(_path); - return false; -} - - -bool FileImpl::createDirectoryImpl() -{ - poco_assert (!_path.empty()); - - if (existsImpl() && isDirectoryImpl()) - return false; - if (CreateDirectoryW(_upath.c_str(), 0) == 0) - handleError(_path); - return true; -} - - -void FileImpl::handleError(const std::string& path) -{ - switch (GetLastError()) - { - case ERROR_FILE_NOT_FOUND: - throw FileNotFoundException(path); - case ERROR_PATH_NOT_FOUND: - case ERROR_BAD_NETPATH: - case ERROR_CANT_RESOLVE_FILENAME: - case ERROR_INVALID_DRIVE: - throw PathNotFoundException(path); - case ERROR_ACCESS_DENIED: - throw FileAccessDeniedException(path); - case ERROR_ALREADY_EXISTS: - case ERROR_FILE_EXISTS: - throw FileExistsException(path); - case ERROR_INVALID_NAME: - case ERROR_DIRECTORY: - case ERROR_FILENAME_EXCED_RANGE: - case ERROR_BAD_PATHNAME: - throw PathSyntaxException(path); - case ERROR_FILE_READ_ONLY: - throw FileReadOnlyException(path); - case ERROR_CANNOT_MAKE: - throw CreateFileException(path); - case ERROR_DIR_NOT_EMPTY: - throw FileException("directory not empty", path); - default: - throw FileException(path); - } -} - - -} // namespace Poco +// +// File_WIN32U.cpp +// +// $Id: //poco/1.2/Foundation/src/File_WIN32U.cpp#1 $ +// +// Library: Foundation +// Package: Filesystem +// Module: File +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/File_WIN32U.h" +#include "Poco/Exception.h" +#include "Poco/UnicodeConverter.h" +#include + + +namespace Poco { + + +class FileHandle +{ +public: + FileHandle(const std::string& path, const std::wstring& upath, DWORD access, DWORD share, DWORD disp) + { + _h = CreateFileW(upath.c_str(), access, share, 0, disp, 0, 0); + if (!_h) FileImpl::handleError(path); + } + + ~FileHandle() + { + if (_h) CloseHandle(_h); + } + + HANDLE get() const + { + return _h; + } + +private: + HANDLE _h; +}; + + +FileImpl::FileImpl() +{ +} + + +FileImpl::FileImpl(const std::string& path): _path(path) +{ + std::string::size_type n = _path.size(); + if (n > 0 && (_path[n - 1] == '\\' || _path[n - 1] == '/')) + _path.resize(n - 1); + UnicodeConverter::toUTF16(_path, _upath); +} + + +FileImpl::~FileImpl() +{ +} + + +void FileImpl::swapImpl(FileImpl& file) +{ + std::swap(_path, file._path); + std::swap(_upath, file._upath); +} + + +void FileImpl::setPathImpl(const std::string& path) +{ + _path = path; + UnicodeConverter::toUTF16(_path, _upath); +} + + +bool FileImpl::existsImpl() const +{ + poco_assert (!_path.empty()); + + DWORD attr = GetFileAttributesW(_upath.c_str()); + if (attr == 0xFFFFFFFF) + { + switch (GetLastError()) + { + case ERROR_FILE_NOT_FOUND: + case ERROR_PATH_NOT_FOUND: + case ERROR_NOT_READY: + case ERROR_INVALID_DRIVE: + return false; + default: + handleError(_path); + } + } + return true; +} + + +bool FileImpl::canReadImpl() const +{ + poco_assert (!_path.empty()); + + DWORD attr = GetFileAttributesW(_upath.c_str()); + if (attr == 0xFFFFFFFF) + { + switch (GetLastError()) + { + case ERROR_ACCESS_DENIED: + return false; + default: + handleError(_path); + } + } + return true; +} + + +bool FileImpl::canWriteImpl() const +{ + poco_assert (!_path.empty()); + + DWORD attr = GetFileAttributesW(_upath.c_str()); + if (attr == 0xFFFFFFFF) + handleError(_path); + return (attr & FILE_ATTRIBUTE_READONLY) == 0; +} + + +bool FileImpl::isFileImpl() const +{ + poco_assert (!_path.empty()); + + DWORD attr = GetFileAttributesW(_upath.c_str()); + if (attr == 0xFFFFFFFF) + handleError(_path); + return (attr & FILE_ATTRIBUTE_DIRECTORY) == 0; +} + + +bool FileImpl::isDirectoryImpl() const +{ + poco_assert (!_path.empty()); + + DWORD attr = GetFileAttributesW(_upath.c_str()); + if (attr == 0xFFFFFFFF) + handleError(_path); + return (attr & FILE_ATTRIBUTE_DIRECTORY) != 0; +} + + +bool FileImpl::isLinkImpl() const +{ + return false; +} + + +Timestamp FileImpl::createdImpl() const +{ + poco_assert (!_path.empty()); + + WIN32_FILE_ATTRIBUTE_DATA fad; + if (GetFileAttributesExW(_upath.c_str(), GetFileExInfoStandard, &fad) == 0) + handleError(_path); + return Timestamp::fromFileTimeNP(fad.ftCreationTime.dwLowDateTime, fad.ftCreationTime.dwHighDateTime); +} + + +Timestamp FileImpl::getLastModifiedImpl() const +{ + poco_assert (!_path.empty()); + + WIN32_FILE_ATTRIBUTE_DATA fad; + if (GetFileAttributesExW(_upath.c_str(), GetFileExInfoStandard, &fad) == 0) + handleError(_path); + return Timestamp::fromFileTimeNP(fad.ftLastWriteTime.dwLowDateTime, fad.ftLastWriteTime.dwHighDateTime); +} + + +void FileImpl::setLastModifiedImpl(const Timestamp& ts) +{ + poco_assert (!_path.empty()); + + UInt32 low; + UInt32 high; + ts.toFileTimeNP(low, high); + FILETIME ft; + ft.dwLowDateTime = low; + ft.dwHighDateTime = high; + FileHandle fh(_path, _upath, FILE_ALL_ACCESS, FILE_SHARE_WRITE, OPEN_EXISTING); + if (SetFileTime(fh.get(), 0, &ft, &ft) == 0) + handleError(_path); +} + + +FileImpl::FileSizeImpl FileImpl::getSizeImpl() const +{ + poco_assert (!_path.empty()); + + WIN32_FILE_ATTRIBUTE_DATA fad; + if (GetFileAttributesExW(_upath.c_str(), GetFileExInfoStandard, &fad) == 0) + handleError(_path); + LARGE_INTEGER li; + li.LowPart = fad.nFileSizeLow; + li.HighPart = fad.nFileSizeHigh; + return li.QuadPart; +} + + +void FileImpl::setSizeImpl(FileSizeImpl size) +{ + poco_assert (!_path.empty()); + + FileHandle fh(_path, _upath, GENERIC_WRITE, FILE_SHARE_WRITE, OPEN_EXISTING); + LARGE_INTEGER li; + li.QuadPart = size; + if (SetFilePointer(fh.get(), li.LowPart, &li.HighPart, FILE_BEGIN) == -1) + handleError(_path); + if (SetEndOfFile(fh.get()) == 0) + handleError(_path); +} + + +void FileImpl::setWriteableImpl(bool flag) +{ + poco_assert (!_path.empty()); + + DWORD attr = GetFileAttributesW(_upath.c_str()); + if (attr == -1) + handleError(_path); + if (flag) + attr &= ~FILE_ATTRIBUTE_READONLY; + else + attr |= FILE_ATTRIBUTE_READONLY; + if (SetFileAttributesW(_upath.c_str(), attr) == 0) + handleError(_path); +} + + +void FileImpl::copyToImpl(const std::string& path) const +{ + poco_assert (!_path.empty()); + + std::wstring upath; + UnicodeConverter::toUTF16(path, upath); + if (CopyFileW(_upath.c_str(), upath.c_str(), FALSE) == 0) + handleError(_path); +} + + +void FileImpl::renameToImpl(const std::string& path) +{ + poco_assert (!_path.empty()); + + std::wstring upath; + UnicodeConverter::toUTF16(path, upath); + if (MoveFileW(_upath.c_str(), upath.c_str()) == 0) + handleError(_path); +} + + +void FileImpl::removeImpl() +{ + poco_assert (!_path.empty()); + + if (isDirectoryImpl()) + { + if (RemoveDirectoryW(_upath.c_str()) == 0) + handleError(_path); + } + else + { + if (DeleteFileW(_upath.c_str()) == 0) + handleError(_path); + } +} + + +bool FileImpl::createFileImpl() +{ + poco_assert (!_path.empty()); + + HANDLE hFile = CreateFileW(_upath.c_str(), GENERIC_WRITE, 0, 0, CREATE_NEW, 0, 0); + if (hFile) + { + CloseHandle(hFile); + return true; + } + else if (GetLastError() == ERROR_ALREADY_EXISTS) + return false; + else + handleError(_path); + return false; +} + + +bool FileImpl::createDirectoryImpl() +{ + poco_assert (!_path.empty()); + + if (existsImpl() && isDirectoryImpl()) + return false; + if (CreateDirectoryW(_upath.c_str(), 0) == 0) + handleError(_path); + return true; +} + + +void FileImpl::handleError(const std::string& path) +{ + switch (GetLastError()) + { + case ERROR_FILE_NOT_FOUND: + throw FileNotFoundException(path); + case ERROR_PATH_NOT_FOUND: + case ERROR_BAD_NETPATH: + case ERROR_CANT_RESOLVE_FILENAME: + case ERROR_INVALID_DRIVE: + throw PathNotFoundException(path); + case ERROR_ACCESS_DENIED: + throw FileAccessDeniedException(path); + case ERROR_ALREADY_EXISTS: + case ERROR_FILE_EXISTS: + throw FileExistsException(path); + case ERROR_INVALID_NAME: + case ERROR_DIRECTORY: + case ERROR_FILENAME_EXCED_RANGE: + case ERROR_BAD_PATHNAME: + throw PathSyntaxException(path); + case ERROR_FILE_READ_ONLY: + throw FileReadOnlyException(path); + case ERROR_CANNOT_MAKE: + throw CreateFileException(path); + case ERROR_DIR_NOT_EMPTY: + throw FileException("directory not empty", path); + default: + throw FileException(path); + } +} + + +} // namespace Poco diff --git a/Foundation/src/Format.cpp b/Foundation/src/Format.cpp index 51ad74ad0..8909addcb 100644 --- a/Foundation/src/Format.cpp +++ b/Foundation/src/Format.cpp @@ -1,334 +1,334 @@ -// -// Format.cpp -// -// $Id: //poco/1.2/Foundation/src/Format.cpp#1 $ -// -// Library: Foundation -// Package: Core -// Module: Format -// -// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. -// 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. -// -// 3. Redistributions in any form must be accompanied by information on -// how to obtain complete source code for this software and any -// accompanying software that uses this software. The source code -// must either be included in the distribution or be available for no -// more than the cost of distribution plus a nominal fee, and must be -// freely redistributable under reasonable conditions. For an -// executable file, complete source code means the source code for all -// modules it contains. It does not include source code for modules or -// files that typically accompany the major components of the operating -// system on which the executable file runs. -// -// 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. -// - - -#include "Poco/Format.h" -#include "Poco/Exception.h" -#include -#include - - -namespace Poco { - - -namespace -{ - void parseFlags(std::ostream& str, std::string::const_iterator& itFmt, const std::string::const_iterator& endFmt) - { - bool isFlag = true; - while (isFlag && itFmt != endFmt) - { - switch (*itFmt) - { - case '-': str.setf(std::ios_base::left); ++itFmt; break; - case '+': str.setf(std::ios_base::showpos); ++itFmt; break; - case '0': str.fill('0'); ++itFmt; break; - case '#': str.setf(std::ios_base::showpoint | std::ios_base::showbase); ++itFmt; break; - default: isFlag = false; break; - } - } - } - - - void parseWidth(std::ostream& str, std::string::const_iterator& itFmt, const std::string::const_iterator& endFmt) - { - int width = 0; - while (itFmt != endFmt && isdigit(*itFmt)) - { - width = 10*width + *itFmt - '0'; - ++itFmt; - } - if (width != 0) str.width(width); - } - - - void parsePrec(std::ostream& str, std::string::const_iterator& itFmt, const std::string::const_iterator& endFmt) - { - if (itFmt != endFmt && *itFmt == '.') - { - ++itFmt; - int prec = 0; - while (itFmt != endFmt && isdigit(*itFmt)) - { - prec = 10*prec + *itFmt - '0'; - ++itFmt; - } - if (prec != 0) str.precision(prec); - } - } - - char parseMod(std::string::const_iterator& itFmt, const std::string::const_iterator& endFmt) - { - char mod = 0; - if (itFmt != endFmt) - { - switch (*itFmt) - { - case 'l': - case 'h': - case 'L': mod = *itFmt++; break; - } - } - return mod; - } - - - void prepareFormat(std::ostream& str, char type) - { - switch (type) - { - case 'd': - case 'i': str << std::dec; break; - case 'o': str << std::oct; break; - case 'x': str << std::hex; break; - case 'X': str << std::hex << std::uppercase; break; - case 'e': str << std::scientific; break; - case 'E': str << std::scientific << std::uppercase; break; - case 'f': str << std::fixed; break; - } - } - - - void formatOne(std::string& result, std::string::const_iterator& itFmt, const std::string::const_iterator& endFmt, std::vector::const_iterator& itVal) - { - std::ostringstream str; - parseFlags(str, itFmt, endFmt); - parseWidth(str, itFmt, endFmt); - parsePrec(str, itFmt, endFmt); - char mod = parseMod(itFmt, endFmt); - if (itFmt != endFmt) - { - char type = *itFmt++; - prepareFormat(str, type); - switch (type) - { - case 'c': - str << AnyCast(*itVal++); - break; - case 'd': - case 'i': - switch (mod) - { - case 'l': str << AnyCast(*itVal++); break; - case 'L': str << AnyCast(*itVal++); break; - case 'h': str << AnyCast(*itVal++); break; - default: str << AnyCast(*itVal++); break; - } - break; - case 'o': - case 'u': - case 'x': - case 'X': - switch (mod) - { - case 'l': str << AnyCast(*itVal++); break; - case 'L': str << AnyCast(*itVal++); break; - case 'h': str << AnyCast(*itVal++); break; - default: str << AnyCast(*itVal++); break; - } - break; - case 'e': - case 'E': - case 'f': - switch (mod) - { - case 'l': str << AnyCast(*itVal++); break; - case 'L': str << AnyCast(*itVal++); break; - case 'h': str << AnyCast(*itVal++); break; - default: str << AnyCast(*itVal++); break; - } - break; - case 's': - str << RefAnyCast(*itVal++); - break; - default: - str << type; - } - } - result.append(str.str()); - } -} - - -std::string format(const std::string& fmt, const Any& value) -{ - std::string result; - format(result, fmt, value); - return result; -} - - -std::string format(const std::string& fmt, const Any& value1, const Any& value2) -{ - std::string result; - format(result, fmt, value1, value2); - return result; -} - - -std::string format(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3) -{ - std::string result; - format(result, fmt, value1, value2, value3); - return result; -} - - -std::string format(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4) -{ - std::string result; - format(result, fmt, value1, value2, value3, value4); - return result; -} - - -std::string format(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5) -{ - std::string result; - format(result, fmt, value1, value2, value3, value4, value5); - return result; -} - - -std::string format(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6) -{ - std::string result; - format(result, fmt, value1, value2, value3, value4, value5, value6); - return result; -} - - -void format(std::string& result, const std::string& fmt, const Any& value) -{ - std::vector args; - args.push_back(value); - format(result, fmt, args); -} - - -void format(std::string& result, const std::string& fmt, const Any& value1, const Any& value2) -{ - std::vector args; - args.push_back(value1); - args.push_back(value2); - format(result, fmt, args); -} - - -void format(std::string& result, const std::string& fmt, const Any& value1, const Any& value2, const Any& value3) -{ - std::vector args; - args.push_back(value1); - args.push_back(value2); - args.push_back(value3); - format(result, fmt, args); -} - - -void format(std::string& result, const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4) -{ - std::vector args; - args.push_back(value1); - args.push_back(value2); - args.push_back(value3); - args.push_back(value4); - format(result, fmt, args); -} - - -void format(std::string& result, const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5) -{ - std::vector args; - args.push_back(value1); - args.push_back(value2); - args.push_back(value3); - args.push_back(value4); - args.push_back(value5); - format(result, fmt, args); -} - - -void format(std::string& result, const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6) -{ - std::vector args; - args.push_back(value1); - args.push_back(value2); - args.push_back(value3); - args.push_back(value4); - args.push_back(value5); - args.push_back(value6); - format(result, fmt, args); -} - - -void format(std::string& result, const std::string& fmt, const std::vector& values) -{ - std::string::const_iterator itFmt = fmt.begin(); - std::string::const_iterator endFmt = fmt.end(); - std::vector::const_iterator itVal = values.begin(); - std::vector::const_iterator endVal = values.end(); - while (itFmt != endFmt) - { - switch (*itFmt) - { - case '%': - ++itFmt; - if (itFmt != endFmt && itVal != endVal) - formatOne(result, itFmt, endFmt, itVal); - else - result += *itFmt; - break; - default: - result += *itFmt; - ++itFmt; - } - } -} - - -} // namespace Poco +// +// Format.cpp +// +// $Id: //poco/1.2/Foundation/src/Format.cpp#1 $ +// +// Library: Foundation +// Package: Core +// Module: Format +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// 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. +// +// 3. Redistributions in any form must be accompanied by information on +// how to obtain complete source code for this software and any +// accompanying software that uses this software. The source code +// must either be included in the distribution or be available for no +// more than the cost of distribution plus a nominal fee, and must be +// freely redistributable under reasonable conditions. For an +// executable file, complete source code means the source code for all +// modules it contains. It does not include source code for modules or +// files that typically accompany the major components of the operating +// system on which the executable file runs. +// +// 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. +// + + +#include "Poco/Format.h" +#include "Poco/Exception.h" +#include +#include + + +namespace Poco { + + +namespace +{ + void parseFlags(std::ostream& str, std::string::const_iterator& itFmt, const std::string::const_iterator& endFmt) + { + bool isFlag = true; + while (isFlag && itFmt != endFmt) + { + switch (*itFmt) + { + case '-': str.setf(std::ios_base::left); ++itFmt; break; + case '+': str.setf(std::ios_base::showpos); ++itFmt; break; + case '0': str.fill('0'); ++itFmt; break; + case '#': str.setf(std::ios_base::showpoint | std::ios_base::showbase); ++itFmt; break; + default: isFlag = false; break; + } + } + } + + + void parseWidth(std::ostream& str, std::string::const_iterator& itFmt, const std::string::const_iterator& endFmt) + { + int width = 0; + while (itFmt != endFmt && isdigit(*itFmt)) + { + width = 10*width + *itFmt - '0'; + ++itFmt; + } + if (width != 0) str.width(width); + } + + + void parsePrec(std::ostream& str, std::string::const_iterator& itFmt, const std::string::const_iterator& endFmt) + { + if (itFmt != endFmt && *itFmt == '.') + { + ++itFmt; + int prec = 0; + while (itFmt != endFmt && isdigit(*itFmt)) + { + prec = 10*prec + *itFmt - '0'; + ++itFmt; + } + if (prec != 0) str.precision(prec); + } + } + + char parseMod(std::string::const_iterator& itFmt, const std::string::const_iterator& endFmt) + { + char mod = 0; + if (itFmt != endFmt) + { + switch (*itFmt) + { + case 'l': + case 'h': + case 'L': mod = *itFmt++; break; + } + } + return mod; + } + + + void prepareFormat(std::ostream& str, char type) + { + switch (type) + { + case 'd': + case 'i': str << std::dec; break; + case 'o': str << std::oct; break; + case 'x': str << std::hex; break; + case 'X': str << std::hex << std::uppercase; break; + case 'e': str << std::scientific; break; + case 'E': str << std::scientific << std::uppercase; break; + case 'f': str << std::fixed; break; + } + } + + + void formatOne(std::string& result, std::string::const_iterator& itFmt, const std::string::const_iterator& endFmt, std::vector::const_iterator& itVal) + { + std::ostringstream str; + parseFlags(str, itFmt, endFmt); + parseWidth(str, itFmt, endFmt); + parsePrec(str, itFmt, endFmt); + char mod = parseMod(itFmt, endFmt); + if (itFmt != endFmt) + { + char type = *itFmt++; + prepareFormat(str, type); + switch (type) + { + case 'c': + str << AnyCast(*itVal++); + break; + case 'd': + case 'i': + switch (mod) + { + case 'l': str << AnyCast(*itVal++); break; + case 'L': str << AnyCast(*itVal++); break; + case 'h': str << AnyCast(*itVal++); break; + default: str << AnyCast(*itVal++); break; + } + break; + case 'o': + case 'u': + case 'x': + case 'X': + switch (mod) + { + case 'l': str << AnyCast(*itVal++); break; + case 'L': str << AnyCast(*itVal++); break; + case 'h': str << AnyCast(*itVal++); break; + default: str << AnyCast(*itVal++); break; + } + break; + case 'e': + case 'E': + case 'f': + switch (mod) + { + case 'l': str << AnyCast(*itVal++); break; + case 'L': str << AnyCast(*itVal++); break; + case 'h': str << AnyCast(*itVal++); break; + default: str << AnyCast(*itVal++); break; + } + break; + case 's': + str << RefAnyCast(*itVal++); + break; + default: + str << type; + } + } + result.append(str.str()); + } +} + + +std::string format(const std::string& fmt, const Any& value) +{ + std::string result; + format(result, fmt, value); + return result; +} + + +std::string format(const std::string& fmt, const Any& value1, const Any& value2) +{ + std::string result; + format(result, fmt, value1, value2); + return result; +} + + +std::string format(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3) +{ + std::string result; + format(result, fmt, value1, value2, value3); + return result; +} + + +std::string format(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4) +{ + std::string result; + format(result, fmt, value1, value2, value3, value4); + return result; +} + + +std::string format(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5) +{ + std::string result; + format(result, fmt, value1, value2, value3, value4, value5); + return result; +} + + +std::string format(const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6) +{ + std::string result; + format(result, fmt, value1, value2, value3, value4, value5, value6); + return result; +} + + +void format(std::string& result, const std::string& fmt, const Any& value) +{ + std::vector args; + args.push_back(value); + format(result, fmt, args); +} + + +void format(std::string& result, const std::string& fmt, const Any& value1, const Any& value2) +{ + std::vector args; + args.push_back(value1); + args.push_back(value2); + format(result, fmt, args); +} + + +void format(std::string& result, const std::string& fmt, const Any& value1, const Any& value2, const Any& value3) +{ + std::vector args; + args.push_back(value1); + args.push_back(value2); + args.push_back(value3); + format(result, fmt, args); +} + + +void format(std::string& result, const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4) +{ + std::vector args; + args.push_back(value1); + args.push_back(value2); + args.push_back(value3); + args.push_back(value4); + format(result, fmt, args); +} + + +void format(std::string& result, const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5) +{ + std::vector args; + args.push_back(value1); + args.push_back(value2); + args.push_back(value3); + args.push_back(value4); + args.push_back(value5); + format(result, fmt, args); +} + + +void format(std::string& result, const std::string& fmt, const Any& value1, const Any& value2, const Any& value3, const Any& value4, const Any& value5, const Any& value6) +{ + std::vector args; + args.push_back(value1); + args.push_back(value2); + args.push_back(value3); + args.push_back(value4); + args.push_back(value5); + args.push_back(value6); + format(result, fmt, args); +} + + +void format(std::string& result, const std::string& fmt, const std::vector& values) +{ + std::string::const_iterator itFmt = fmt.begin(); + std::string::const_iterator endFmt = fmt.end(); + std::vector::const_iterator itVal = values.begin(); + std::vector::const_iterator endVal = values.end(); + while (itFmt != endFmt) + { + switch (*itFmt) + { + case '%': + ++itFmt; + if (itFmt != endFmt && itVal != endVal) + formatOne(result, itFmt, endFmt, itVal); + else + result += *itFmt; + break; + default: + result += *itFmt; + ++itFmt; + } + } +} + + +} // namespace Poco diff --git a/Foundation/src/Formatter.cpp b/Foundation/src/Formatter.cpp index 0cad7b5f6..615548e49 100644 --- a/Foundation/src/Formatter.cpp +++ b/Foundation/src/Formatter.cpp @@ -1,66 +1,66 @@ -// -// Formatter.cpp -// -// $Id: //poco/1.2/Foundation/src/Formatter.cpp#1 $ -// -// Library: Foundation -// Package: Logging -// Module: Formatter -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/Formatter.h" -#include "Poco/Exception.h" - - -namespace Poco { - - -Formatter::Formatter() -{ -} - - -Formatter::~Formatter() -{ -} - - -void Formatter::setProperty(const std::string& name, const std::string& value) -{ - throw PropertyNotSupportedException(); -} - - -std::string Formatter::getProperty(const std::string& name) const -{ - throw PropertyNotSupportedException(); -} - - -} // namespace Poco +// +// Formatter.cpp +// +// $Id: //poco/1.2/Foundation/src/Formatter.cpp#1 $ +// +// Library: Foundation +// Package: Logging +// Module: Formatter +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/Formatter.h" +#include "Poco/Exception.h" + + +namespace Poco { + + +Formatter::Formatter() +{ +} + + +Formatter::~Formatter() +{ +} + + +void Formatter::setProperty(const std::string& name, const std::string& value) +{ + throw PropertyNotSupportedException(); +} + + +std::string Formatter::getProperty(const std::string& name) const +{ + throw PropertyNotSupportedException(); +} + + +} // namespace Poco diff --git a/Foundation/src/FormattingChannel.cpp b/Foundation/src/FormattingChannel.cpp index b27e43c46..7f054f21b 100644 --- a/Foundation/src/FormattingChannel.cpp +++ b/Foundation/src/FormattingChannel.cpp @@ -1,148 +1,148 @@ -// -// FormattingChannel.cpp -// -// $Id: //poco/1.2/Foundation/src/FormattingChannel.cpp#2 $ -// -// Library: Foundation -// Package: Logging -// Module: Formatter -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/FormattingChannel.h" -#include "Poco/Formatter.h" -#include "Poco/Message.h" -#include "Poco/LoggingRegistry.h" - - -namespace Poco { - - -FormattingChannel::FormattingChannel(): - _pFormatter(0), - _pChannel(0) -{ -} - - -FormattingChannel::FormattingChannel(Formatter* pFormatter): - _pFormatter(pFormatter), - _pChannel(0) -{ - if (_pFormatter) _pFormatter->duplicate(); -} - - -FormattingChannel::FormattingChannel(Formatter* pFormatter, Channel* pChannel): - _pFormatter(pFormatter), - _pChannel(pChannel) -{ - if (_pFormatter) _pFormatter->duplicate(); - if (_pChannel) _pChannel->duplicate(); -} - - -FormattingChannel::~FormattingChannel() -{ - if (_pChannel) _pChannel->release(); - if (_pFormatter) _pFormatter->release(); -} - - -void FormattingChannel::setFormatter(Formatter* pFormatter) -{ - if (_pFormatter) _pFormatter->release(); - _pFormatter = pFormatter; - if (_pFormatter) _pFormatter->duplicate(); -} - - -Formatter* FormattingChannel::getFormatter() const -{ - return _pFormatter; -} - - -void FormattingChannel::setChannel(Channel* pChannel) -{ - if (_pChannel) _pChannel->release(); - _pChannel = pChannel; - if (_pChannel) _pChannel->duplicate(); -} - - -Channel* FormattingChannel::getChannel() const -{ - return _pChannel; -} - - -void FormattingChannel::log(const Message& msg) -{ - if (_pChannel) - { - if (_pFormatter) - { - std::string text; - _pFormatter->format(msg, text); - _pChannel->log(Message(msg, text)); - } - else - { - _pChannel->log(msg); - } - } -}; - - -void FormattingChannel::setProperty(const std::string& name, const std::string& value) -{ - if (name == "channel") - setChannel(LoggingRegistry::defaultRegistry().channelForName(value)); - else if (name == "formatter") - setFormatter(LoggingRegistry::defaultRegistry().formatterForName(value)); - else if (_pChannel) - _pChannel->setProperty(name, value); -} - - -void FormattingChannel::open() -{ - if (_pChannel) - _pChannel->open(); -} - - -void FormattingChannel::close() -{ - if (_pChannel) - _pChannel->close(); -} - - -} // namespace Poco +// +// FormattingChannel.cpp +// +// $Id: //poco/1.2/Foundation/src/FormattingChannel.cpp#2 $ +// +// Library: Foundation +// Package: Logging +// Module: Formatter +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/FormattingChannel.h" +#include "Poco/Formatter.h" +#include "Poco/Message.h" +#include "Poco/LoggingRegistry.h" + + +namespace Poco { + + +FormattingChannel::FormattingChannel(): + _pFormatter(0), + _pChannel(0) +{ +} + + +FormattingChannel::FormattingChannel(Formatter* pFormatter): + _pFormatter(pFormatter), + _pChannel(0) +{ + if (_pFormatter) _pFormatter->duplicate(); +} + + +FormattingChannel::FormattingChannel(Formatter* pFormatter, Channel* pChannel): + _pFormatter(pFormatter), + _pChannel(pChannel) +{ + if (_pFormatter) _pFormatter->duplicate(); + if (_pChannel) _pChannel->duplicate(); +} + + +FormattingChannel::~FormattingChannel() +{ + if (_pChannel) _pChannel->release(); + if (_pFormatter) _pFormatter->release(); +} + + +void FormattingChannel::setFormatter(Formatter* pFormatter) +{ + if (_pFormatter) _pFormatter->release(); + _pFormatter = pFormatter; + if (_pFormatter) _pFormatter->duplicate(); +} + + +Formatter* FormattingChannel::getFormatter() const +{ + return _pFormatter; +} + + +void FormattingChannel::setChannel(Channel* pChannel) +{ + if (_pChannel) _pChannel->release(); + _pChannel = pChannel; + if (_pChannel) _pChannel->duplicate(); +} + + +Channel* FormattingChannel::getChannel() const +{ + return _pChannel; +} + + +void FormattingChannel::log(const Message& msg) +{ + if (_pChannel) + { + if (_pFormatter) + { + std::string text; + _pFormatter->format(msg, text); + _pChannel->log(Message(msg, text)); + } + else + { + _pChannel->log(msg); + } + } +}; + + +void FormattingChannel::setProperty(const std::string& name, const std::string& value) +{ + if (name == "channel") + setChannel(LoggingRegistry::defaultRegistry().channelForName(value)); + else if (name == "formatter") + setFormatter(LoggingRegistry::defaultRegistry().formatterForName(value)); + else if (_pChannel) + _pChannel->setProperty(name, value); +} + + +void FormattingChannel::open() +{ + if (_pChannel) + _pChannel->open(); +} + + +void FormattingChannel::close() +{ + if (_pChannel) + _pChannel->close(); +} + + +} // namespace Poco diff --git a/Foundation/src/Glob.cpp b/Foundation/src/Glob.cpp index 29b289a6e..be1e9d657 100644 --- a/Foundation/src/Glob.cpp +++ b/Foundation/src/Glob.cpp @@ -1,242 +1,242 @@ -// -// Glob.cpp -// -// $Id: //poco/1.2/Foundation/src/Glob.cpp#1 $ -// -// Library: Foundation -// Package: Filesystem -// Module: Glob -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/Glob.h" -#include "Poco/Path.h" -#include "Poco/Exception.h" -#include "Poco/DirectoryIterator.h" -#include "Poco/File.h" - - -namespace Poco { - - -Glob::Glob(const std::string& pattern, int options): - _pattern(pattern), - _options(options) -{ - poco_assert (!_pattern.empty()); -} - - -Glob::~Glob() -{ -} - - -bool Glob::match(const std::string& subject) -{ - std::string::const_iterator itp = _pattern.begin(); - std::string::const_iterator endp = _pattern.end(); - std::string::const_iterator its = subject.begin(); - std::string::const_iterator ends = subject.end(); - - if ((_options & GLOB_DOT_SPECIAL) && its != ends && *its == '.' && (*itp == '?' || *itp == '*')) - return false; - else - return match(itp, endp, its, ends); -} - - -void Glob::glob(const std::string& pathPattern, std::set& files, int options) -{ - glob(Path(Path::expand(pathPattern), Path::PATH_GUESS), files, options); -} - - -void Glob::glob(const char* pathPattern, std::set& files, int options) -{ - glob(Path(Path::expand(pathPattern), Path::PATH_GUESS), files, options); -} - - -void Glob::glob(const Path& pathPattern, std::set& files, int options) -{ - Path pattern(pathPattern); - pattern.makeDirectory(); // to simplify pattern handling later on - Path base(pattern); - Path absBase(base); - absBase.makeAbsolute(); - while (base.depth() > 0 && base[base.depth() - 1] != "..") - { - base.popDirectory(); - absBase.popDirectory(); - } - if (pathPattern.isDirectory()) options |= GLOB_DIRS_ONLY; - collect(pattern, absBase, base, pathPattern[base.depth()], files, options); -} - - -bool Glob::match(std::string::const_iterator& itp, const std::string::const_iterator& endp, std::string::const_iterator& its, const std::string::const_iterator& ends) -{ - while (itp != endp) - { - if (its == ends) - { - while (itp != endp && *itp == '*') ++itp; - break; - } - switch (*itp) - { - case '?': - ++itp; ++its; - break; - case '*': - if (++itp != endp) - { - while (its != ends && !matchAfterAsterisk(itp, endp, its, ends)) ++its; - return its != ends; - } - return true; - case '[': - if (++itp != endp) - { - bool invert = *itp == '!'; - if (invert) ++itp; - if (itp != endp) - { - bool mtch = matchSet(itp, endp, *its++); - if (invert && mtch || !invert && !mtch) return false; - break; - } - } - throw SyntaxException("bad range syntax in glob pattern"); - case '\\': - if (++itp == endp) throw SyntaxException("backslash must be followed by character in glob pattern"); - // fallthrough - default: - if (*itp != *its) return false; - ++itp; ++its; - } - } - return itp == endp && its == ends; -} - - -bool Glob::matchAfterAsterisk(std::string::const_iterator itp, const std::string::const_iterator& endp, std::string::const_iterator its, const std::string::const_iterator& ends) -{ - return match(itp, endp, its, ends); -} - - -bool Glob::matchSet(std::string::const_iterator& itp, const std::string::const_iterator& endp, char c) -{ - while (itp != endp) - { - switch (*itp) - { - case ']': - ++itp; - return false; - case '\\': - if (++itp == endp) throw SyntaxException("backslash must be followed by character in glob pattern"); - } - char first = *itp; - char last = first; - if (++itp != endp && *itp == '-') - { - if (++itp != endp) - last = *itp++; - else - throw SyntaxException("bad range syntax in glob pattern"); - } - if (first <= c && c <= last) - { - while (itp != endp) - { - switch (*itp) - { - case ']': - ++itp; - return true; - case '\\': - if (++itp == endp) break; - default: - ++itp; - } - } - throw SyntaxException("range must be terminated by closing bracket in glob pattern"); - } - } - return false; -} - - -void Glob::collect(const Path& pathPattern, const Path& base, const Path& current, const std::string& pattern, std::set& files, int options) -{ - try - { - std::string pp = pathPattern.toString(); - std::string basep = base.toString(); - std::string curp = current.toString(); - Glob g(pattern, options); - DirectoryIterator it(base); - DirectoryIterator end; - while (it != end) - { - const std::string& name = it.name(); - if (g.match(name)) - { - Path p(current); - if (p.depth() < pathPattern.depth() - 1) - { - p.pushDirectory(name); - collect(pathPattern, it.path(), p, pathPattern[p.depth()], files, options); - } - else - { - p.setFileName(name); - if (File(p).isDirectory()) - { - p.makeDirectory(); - files.insert(p.toString()); - } - else if (!(options & GLOB_DIRS_ONLY)) - { - files.insert(p.toString()); - } - } - } - ++it; - } - } - catch (Exception&) - { - } -} - - -} // namespace Poco +// +// Glob.cpp +// +// $Id: //poco/1.2/Foundation/src/Glob.cpp#1 $ +// +// Library: Foundation +// Package: Filesystem +// Module: Glob +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/Glob.h" +#include "Poco/Path.h" +#include "Poco/Exception.h" +#include "Poco/DirectoryIterator.h" +#include "Poco/File.h" + + +namespace Poco { + + +Glob::Glob(const std::string& pattern, int options): + _pattern(pattern), + _options(options) +{ + poco_assert (!_pattern.empty()); +} + + +Glob::~Glob() +{ +} + + +bool Glob::match(const std::string& subject) +{ + std::string::const_iterator itp = _pattern.begin(); + std::string::const_iterator endp = _pattern.end(); + std::string::const_iterator its = subject.begin(); + std::string::const_iterator ends = subject.end(); + + if ((_options & GLOB_DOT_SPECIAL) && its != ends && *its == '.' && (*itp == '?' || *itp == '*')) + return false; + else + return match(itp, endp, its, ends); +} + + +void Glob::glob(const std::string& pathPattern, std::set& files, int options) +{ + glob(Path(Path::expand(pathPattern), Path::PATH_GUESS), files, options); +} + + +void Glob::glob(const char* pathPattern, std::set& files, int options) +{ + glob(Path(Path::expand(pathPattern), Path::PATH_GUESS), files, options); +} + + +void Glob::glob(const Path& pathPattern, std::set& files, int options) +{ + Path pattern(pathPattern); + pattern.makeDirectory(); // to simplify pattern handling later on + Path base(pattern); + Path absBase(base); + absBase.makeAbsolute(); + while (base.depth() > 0 && base[base.depth() - 1] != "..") + { + base.popDirectory(); + absBase.popDirectory(); + } + if (pathPattern.isDirectory()) options |= GLOB_DIRS_ONLY; + collect(pattern, absBase, base, pathPattern[base.depth()], files, options); +} + + +bool Glob::match(std::string::const_iterator& itp, const std::string::const_iterator& endp, std::string::const_iterator& its, const std::string::const_iterator& ends) +{ + while (itp != endp) + { + if (its == ends) + { + while (itp != endp && *itp == '*') ++itp; + break; + } + switch (*itp) + { + case '?': + ++itp; ++its; + break; + case '*': + if (++itp != endp) + { + while (its != ends && !matchAfterAsterisk(itp, endp, its, ends)) ++its; + return its != ends; + } + return true; + case '[': + if (++itp != endp) + { + bool invert = *itp == '!'; + if (invert) ++itp; + if (itp != endp) + { + bool mtch = matchSet(itp, endp, *its++); + if (invert && mtch || !invert && !mtch) return false; + break; + } + } + throw SyntaxException("bad range syntax in glob pattern"); + case '\\': + if (++itp == endp) throw SyntaxException("backslash must be followed by character in glob pattern"); + // fallthrough + default: + if (*itp != *its) return false; + ++itp; ++its; + } + } + return itp == endp && its == ends; +} + + +bool Glob::matchAfterAsterisk(std::string::const_iterator itp, const std::string::const_iterator& endp, std::string::const_iterator its, const std::string::const_iterator& ends) +{ + return match(itp, endp, its, ends); +} + + +bool Glob::matchSet(std::string::const_iterator& itp, const std::string::const_iterator& endp, char c) +{ + while (itp != endp) + { + switch (*itp) + { + case ']': + ++itp; + return false; + case '\\': + if (++itp == endp) throw SyntaxException("backslash must be followed by character in glob pattern"); + } + char first = *itp; + char last = first; + if (++itp != endp && *itp == '-') + { + if (++itp != endp) + last = *itp++; + else + throw SyntaxException("bad range syntax in glob pattern"); + } + if (first <= c && c <= last) + { + while (itp != endp) + { + switch (*itp) + { + case ']': + ++itp; + return true; + case '\\': + if (++itp == endp) break; + default: + ++itp; + } + } + throw SyntaxException("range must be terminated by closing bracket in glob pattern"); + } + } + return false; +} + + +void Glob::collect(const Path& pathPattern, const Path& base, const Path& current, const std::string& pattern, std::set& files, int options) +{ + try + { + std::string pp = pathPattern.toString(); + std::string basep = base.toString(); + std::string curp = current.toString(); + Glob g(pattern, options); + DirectoryIterator it(base); + DirectoryIterator end; + while (it != end) + { + const std::string& name = it.name(); + if (g.match(name)) + { + Path p(current); + if (p.depth() < pathPattern.depth() - 1) + { + p.pushDirectory(name); + collect(pathPattern, it.path(), p, pathPattern[p.depth()], files, options); + } + else + { + p.setFileName(name); + if (File(p).isDirectory()) + { + p.makeDirectory(); + files.insert(p.toString()); + } + else if (!(options & GLOB_DIRS_ONLY)) + { + files.insert(p.toString()); + } + } + } + ++it; + } + } + catch (Exception&) + { + } +} + + +} // namespace Poco diff --git a/Foundation/src/HashStatistic.cpp b/Foundation/src/HashStatistic.cpp index fc1e400c3..0de7113e3 100644 --- a/Foundation/src/HashStatistic.cpp +++ b/Foundation/src/HashStatistic.cpp @@ -1,86 +1,86 @@ -// -// HashStatistic.cpp -// -// $Id: //poco/1.2/Foundation/src/HashStatistic.cpp#1 $ -// -// Library: Foundation -// Package: Core -// Module: HashStatistic -// -// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/HashStatistic.h" -#include - -namespace Poco { - - -HashStatistic::HashStatistic( - UInt32 tableSize, - UInt32 numEntries, - UInt32 numZeroEntries, - UInt32 maxEntry, - std::vector details): - _sizeOfTable(tableSize), - _numberOfEntries(numEntries), - _numZeroEntries(numZeroEntries), - _maxEntriesPerHash(maxEntry), - _detailedEntriesPerHash(details) -{ -} - - -HashStatistic::~HashStatistic() -{ -} - - -std::string HashStatistic::toString() const -{ - std::ostringstream str; - str << "HashTable of size " << _sizeOfTable << " containing " << _numberOfEntries << " entries:\n"; - str << " NumberOfZeroEntries: " << _numZeroEntries << "\n"; - str << " MaxEntry: " << _maxEntriesPerHash << "\n"; - str << " AvgEntry: " << avgEntriesPerHash() << ", excl Zero slots: " << avgEntriesPerHashExclZeroEntries() << "\n"; - str << " DetailedStatistics: \n"; - for (int i = 0; i < _detailedEntriesPerHash.size(); ++i) - { - // 10 entries per line - if (i % 10 == 0) - { - str << "\n " << i << ":"; - } - str << " " << _detailedEntriesPerHash[i]; - } - str << "\n"; - str.flush(); - return str.str(); -} - - -} // namespace Poco +// +// HashStatistic.cpp +// +// $Id: //poco/1.2/Foundation/src/HashStatistic.cpp#1 $ +// +// Library: Foundation +// Package: Core +// Module: HashStatistic +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/HashStatistic.h" +#include + +namespace Poco { + + +HashStatistic::HashStatistic( + UInt32 tableSize, + UInt32 numEntries, + UInt32 numZeroEntries, + UInt32 maxEntry, + std::vector details): + _sizeOfTable(tableSize), + _numberOfEntries(numEntries), + _numZeroEntries(numZeroEntries), + _maxEntriesPerHash(maxEntry), + _detailedEntriesPerHash(details) +{ +} + + +HashStatistic::~HashStatistic() +{ +} + + +std::string HashStatistic::toString() const +{ + std::ostringstream str; + str << "HashTable of size " << _sizeOfTable << " containing " << _numberOfEntries << " entries:\n"; + str << " NumberOfZeroEntries: " << _numZeroEntries << "\n"; + str << " MaxEntry: " << _maxEntriesPerHash << "\n"; + str << " AvgEntry: " << avgEntriesPerHash() << ", excl Zero slots: " << avgEntriesPerHashExclZeroEntries() << "\n"; + str << " DetailedStatistics: \n"; + for (int i = 0; i < _detailedEntriesPerHash.size(); ++i) + { + // 10 entries per line + if (i % 10 == 0) + { + str << "\n " << i << ":"; + } + str << " " << _detailedEntriesPerHash[i]; + } + str << "\n"; + str.flush(); + return str.str(); +} + + +} // namespace Poco diff --git a/Foundation/src/HexBinaryDecoder.cpp b/Foundation/src/HexBinaryDecoder.cpp index 7b78b1e71..d7c6862d1 100644 --- a/Foundation/src/HexBinaryDecoder.cpp +++ b/Foundation/src/HexBinaryDecoder.cpp @@ -1,115 +1,115 @@ -// -// HexBinaryDecoder.cpp -// -// $Id: //poco/1.2/Foundation/src/HexBinaryDecoder.cpp#1 $ -// -// Library: Foundation -// Package: Streams -// Module: HexBinary -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/HexBinaryDecoder.h" -#include "Poco/Exception.h" - - -namespace Poco { - - -HexBinaryDecoderBuf::HexBinaryDecoderBuf(std::istream& istr): _istr(istr) -{ -} - - -HexBinaryDecoderBuf::~HexBinaryDecoderBuf() -{ -} - - -int HexBinaryDecoderBuf::readFromDevice() -{ - int c; - int n; - if ((n = readOne()) == -1) return -1; - if (n >= '0' && n <= '9') - c = n - '0'; - else if (n >= 'A' && n <= 'F') - c = n - 'A' + 10; - else if (n >= 'a' && n <= 'f') - c = n - 'a' + 10; - else throw DataFormatException(); - c <<= 4; - if ((n = readOne()) == -1) return -1; - if (n >= '0' && n <= '9') - c |= n - '0'; - else if (n >= 'A' && n <= 'F') - c |= n - 'A' + 10; - else if (n >= 'a' && n <= 'f') - c |= n - 'a' + 10; - else throw DataFormatException(); - return c; -} - - -int HexBinaryDecoderBuf::readOne() -{ - int ch = _istr.get(); - while (ch == ' ' || ch == '\r' || ch == '\t' || ch == '\n') - ch = _istr.get(); - return ch; -} - - -HexBinaryDecoderIOS::HexBinaryDecoderIOS(std::istream& istr): _buf(istr) -{ - poco_ios_init(&_buf); -} - - -HexBinaryDecoderIOS::~HexBinaryDecoderIOS() -{ -} - - -HexBinaryDecoderBuf* HexBinaryDecoderIOS::rdbuf() -{ - return &_buf; -} - - -HexBinaryDecoder::HexBinaryDecoder(std::istream& istr): HexBinaryDecoderIOS(istr), std::istream(&_buf) -{ -} - - -HexBinaryDecoder::~HexBinaryDecoder() -{ -} - - -} // namespace Poco +// +// HexBinaryDecoder.cpp +// +// $Id: //poco/1.2/Foundation/src/HexBinaryDecoder.cpp#1 $ +// +// Library: Foundation +// Package: Streams +// Module: HexBinary +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/HexBinaryDecoder.h" +#include "Poco/Exception.h" + + +namespace Poco { + + +HexBinaryDecoderBuf::HexBinaryDecoderBuf(std::istream& istr): _istr(istr) +{ +} + + +HexBinaryDecoderBuf::~HexBinaryDecoderBuf() +{ +} + + +int HexBinaryDecoderBuf::readFromDevice() +{ + int c; + int n; + if ((n = readOne()) == -1) return -1; + if (n >= '0' && n <= '9') + c = n - '0'; + else if (n >= 'A' && n <= 'F') + c = n - 'A' + 10; + else if (n >= 'a' && n <= 'f') + c = n - 'a' + 10; + else throw DataFormatException(); + c <<= 4; + if ((n = readOne()) == -1) return -1; + if (n >= '0' && n <= '9') + c |= n - '0'; + else if (n >= 'A' && n <= 'F') + c |= n - 'A' + 10; + else if (n >= 'a' && n <= 'f') + c |= n - 'a' + 10; + else throw DataFormatException(); + return c; +} + + +int HexBinaryDecoderBuf::readOne() +{ + int ch = _istr.get(); + while (ch == ' ' || ch == '\r' || ch == '\t' || ch == '\n') + ch = _istr.get(); + return ch; +} + + +HexBinaryDecoderIOS::HexBinaryDecoderIOS(std::istream& istr): _buf(istr) +{ + poco_ios_init(&_buf); +} + + +HexBinaryDecoderIOS::~HexBinaryDecoderIOS() +{ +} + + +HexBinaryDecoderBuf* HexBinaryDecoderIOS::rdbuf() +{ + return &_buf; +} + + +HexBinaryDecoder::HexBinaryDecoder(std::istream& istr): HexBinaryDecoderIOS(istr), std::istream(&_buf) +{ +} + + +HexBinaryDecoder::~HexBinaryDecoder() +{ +} + + +} // namespace Poco diff --git a/Foundation/src/HexBinaryEncoder.cpp b/Foundation/src/HexBinaryEncoder.cpp index 143d949ea..df3711068 100644 --- a/Foundation/src/HexBinaryEncoder.cpp +++ b/Foundation/src/HexBinaryEncoder.cpp @@ -1,140 +1,140 @@ -// -// HexBinaryEncoder.cpp -// -// $Id: //poco/1.2/Foundation/src/HexBinaryEncoder.cpp#1 $ -// -// Library: Foundation -// Package: Streams -// Module: HexBinary -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/HexBinaryEncoder.h" - - -namespace Poco { - - -HexBinaryEncoderBuf::HexBinaryEncoderBuf(std::ostream& ostr): - _pos(0), - _lineLength(72), - _uppercase(0), - _ostr(ostr) -{ -} - - -HexBinaryEncoderBuf::~HexBinaryEncoderBuf() -{ - try - { - close(); - } - catch (...) - { - } -} - - -void HexBinaryEncoderBuf::setLineLength(int lineLength) -{ - poco_assert (lineLength > 0); - - _lineLength = lineLength; -} - - -int HexBinaryEncoderBuf::getLineLength() const -{ - return _lineLength; -} - - -void HexBinaryEncoderBuf::setUppercase(bool flag) -{ - _uppercase = flag ? 16 : 0; -} - - -int HexBinaryEncoderBuf::writeToDevice(char c) -{ - static const char digits[] = "0123456789abcdef0123456789ABCDEF"; - _ostr.put(digits[_uppercase + ((c >> 4) & 0xF)]); - ++_pos; - _ostr.put(digits[_uppercase + (c & 0xF)]); - if (++_pos >= _lineLength) - { - _ostr << std::endl; - _pos = 0; - } - return _ostr ? charToInt(c) : -1; -} - - -int HexBinaryEncoderBuf::close() -{ - sync(); - _ostr.flush(); - return _ostr ? 0 : -1; -} - - -HexBinaryEncoderIOS::HexBinaryEncoderIOS(std::ostream& ostr): _buf(ostr) -{ - poco_ios_init(&_buf); -} - - -HexBinaryEncoderIOS::~HexBinaryEncoderIOS() -{ -} - - -int HexBinaryEncoderIOS::close() -{ - return _buf.close(); -} - - -HexBinaryEncoderBuf* HexBinaryEncoderIOS::rdbuf() -{ - return &_buf; -} - - -HexBinaryEncoder::HexBinaryEncoder(std::ostream& ostr): HexBinaryEncoderIOS(ostr), std::ostream(&_buf) -{ -} - - -HexBinaryEncoder::~HexBinaryEncoder() -{ -} - - -} // namespace Poco +// +// HexBinaryEncoder.cpp +// +// $Id: //poco/1.2/Foundation/src/HexBinaryEncoder.cpp#1 $ +// +// Library: Foundation +// Package: Streams +// Module: HexBinary +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/HexBinaryEncoder.h" + + +namespace Poco { + + +HexBinaryEncoderBuf::HexBinaryEncoderBuf(std::ostream& ostr): + _pos(0), + _lineLength(72), + _uppercase(0), + _ostr(ostr) +{ +} + + +HexBinaryEncoderBuf::~HexBinaryEncoderBuf() +{ + try + { + close(); + } + catch (...) + { + } +} + + +void HexBinaryEncoderBuf::setLineLength(int lineLength) +{ + poco_assert (lineLength > 0); + + _lineLength = lineLength; +} + + +int HexBinaryEncoderBuf::getLineLength() const +{ + return _lineLength; +} + + +void HexBinaryEncoderBuf::setUppercase(bool flag) +{ + _uppercase = flag ? 16 : 0; +} + + +int HexBinaryEncoderBuf::writeToDevice(char c) +{ + static const char digits[] = "0123456789abcdef0123456789ABCDEF"; + _ostr.put(digits[_uppercase + ((c >> 4) & 0xF)]); + ++_pos; + _ostr.put(digits[_uppercase + (c & 0xF)]); + if (++_pos >= _lineLength) + { + _ostr << std::endl; + _pos = 0; + } + return _ostr ? charToInt(c) : -1; +} + + +int HexBinaryEncoderBuf::close() +{ + sync(); + _ostr.flush(); + return _ostr ? 0 : -1; +} + + +HexBinaryEncoderIOS::HexBinaryEncoderIOS(std::ostream& ostr): _buf(ostr) +{ + poco_ios_init(&_buf); +} + + +HexBinaryEncoderIOS::~HexBinaryEncoderIOS() +{ +} + + +int HexBinaryEncoderIOS::close() +{ + return _buf.close(); +} + + +HexBinaryEncoderBuf* HexBinaryEncoderIOS::rdbuf() +{ + return &_buf; +} + + +HexBinaryEncoder::HexBinaryEncoder(std::ostream& ostr): HexBinaryEncoderIOS(ostr), std::ostream(&_buf) +{ +} + + +HexBinaryEncoder::~HexBinaryEncoder() +{ +} + + +} // namespace Poco diff --git a/Foundation/src/InflatingStream.cpp b/Foundation/src/InflatingStream.cpp index 46d806bee..8726c8d45 100644 --- a/Foundation/src/InflatingStream.cpp +++ b/Foundation/src/InflatingStream.cpp @@ -1,253 +1,253 @@ -// -// InflatingStream.cpp -// -// $Id: //poco/1.2/Foundation/src/InflatingStream.cpp#1 $ -// -// Library: Foundation -// Package: Streams -// Module: ZLibStream -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/InflatingStream.h" -#include "Poco/Exception.h" - - -namespace Poco { - - -InflatingStreamBuf::InflatingStreamBuf(std::istream& istr, StreamType type): - BufferedStreamBuf(STREAM_BUFFER_SIZE, std::ios::in), - _pIstr(&istr), - _pOstr(0), - _eof(false) -{ - _zstr.zalloc = Z_NULL; - _zstr.zfree = Z_NULL; - _zstr.opaque = Z_NULL; - _zstr.next_in = 0; - _zstr.avail_in = 0; - _zstr.next_out = 0; - _zstr.avail_out = 0; - - int rc = inflateInit2(&_zstr, 15 + (type == STREAM_GZIP ? 16 : 0)); - if (rc != Z_OK) throw IOException(zError(rc)); - - _buffer = new char[INFLATE_BUFFER_SIZE]; -} - - -InflatingStreamBuf::InflatingStreamBuf(std::ostream& ostr, StreamType type): - BufferedStreamBuf(STREAM_BUFFER_SIZE, std::ios::out), - _pIstr(0), - _pOstr(&ostr), - _eof(false) -{ - _zstr.zalloc = Z_NULL; - _zstr.zfree = Z_NULL; - _zstr.opaque = Z_NULL; - _zstr.next_in = 0; - _zstr.avail_in = 0; - _zstr.next_out = 0; - _zstr.avail_out = 0; - - int rc = inflateInit2(&_zstr, 15 + (type == STREAM_GZIP ? 16 : 0)); - if (rc != Z_OK) throw IOException(zError(rc)); - - _buffer = new char[INFLATE_BUFFER_SIZE]; -} - - -InflatingStreamBuf::~InflatingStreamBuf() -{ - try - { - close(); - } - catch (...) - { - } - delete [] _buffer; -} - - -int InflatingStreamBuf::close() -{ - sync(); - if (_pIstr || _pOstr) - { - int rc = inflateEnd(&_zstr); - if (rc != Z_OK) throw IOException(zError(rc)); - _pIstr = 0; - _pOstr = 0; - } - return 0; -} - - -int InflatingStreamBuf::readFromDevice(char* buffer, std::streamsize length) -{ - if (_eof || !_pIstr) return 0; - - if (_zstr.avail_in == 0) - { - int n = 0; - if (_pIstr->good()) - { - _pIstr->read(_buffer, INFLATE_BUFFER_SIZE); - n = _pIstr->gcount(); - } - if (n == 0) return 0; - _zstr.next_in = (unsigned char*) _buffer; - _zstr.avail_in = n; - } - _zstr.next_out = (unsigned char*) buffer; - _zstr.avail_out = length; - for (;;) - { - int rc = inflate(&_zstr, Z_NO_FLUSH); - if (rc == Z_STREAM_END) - { - _eof = true; - return length - _zstr.avail_out; - } - if (rc != Z_OK) throw IOException(zError(rc)); - if (_zstr.avail_out == 0) - return length; - if (_zstr.avail_in == 0) - { - int n = 0; - if (_pIstr->good()) - { - _pIstr->read(_buffer, INFLATE_BUFFER_SIZE); - n = _pIstr->gcount(); - } - if (n > 0) - { - _zstr.next_in = (unsigned char*) _buffer; - _zstr.avail_in = n; - } - } - } -} - - -int InflatingStreamBuf::writeToDevice(const char* buffer, std::streamsize length) -{ - if (length == 0 || !_pOstr) return 0; - - _zstr.next_in = (unsigned char*) buffer; - _zstr.avail_in = length; - _zstr.next_out = (unsigned char*) _buffer; - _zstr.avail_out = INFLATE_BUFFER_SIZE; - for (;;) - { - int rc = inflate(&_zstr, Z_NO_FLUSH); - if (rc == Z_STREAM_END) - { - _pOstr->write(_buffer, INFLATE_BUFFER_SIZE - _zstr.avail_out); - if (!_pOstr->good()) throw IOException(zError(rc)); - break; - } - if (rc != Z_OK) throw IOException(zError(rc)); - if (_zstr.avail_out == 0) - { - _pOstr->write(_buffer, INFLATE_BUFFER_SIZE); - if (!_pOstr->good()) throw IOException(zError(rc)); - _zstr.next_out = (unsigned char*) _buffer; - _zstr.avail_out = INFLATE_BUFFER_SIZE; - } - if (_zstr.avail_in == 0) - { - _pOstr->write(_buffer, INFLATE_BUFFER_SIZE - _zstr.avail_out); - if (!_pOstr->good()) throw IOException(zError(rc)); - _zstr.next_out = (unsigned char*) _buffer; - _zstr.avail_out = INFLATE_BUFFER_SIZE; - break; - } - } - return length; -} - - -InflatingIOS::InflatingIOS(std::ostream& ostr, InflatingStreamBuf::StreamType type): - _buf(ostr, type) -{ - poco_ios_init(&_buf); -} - - -InflatingIOS::InflatingIOS(std::istream& istr, InflatingStreamBuf::StreamType type): - _buf(istr, type) -{ - poco_ios_init(&_buf); -} - - -InflatingIOS::~InflatingIOS() -{ -} - - -InflatingStreamBuf* InflatingIOS::rdbuf() -{ - return &_buf; -} - - -InflatingOutputStream::InflatingOutputStream(std::ostream& ostr, InflatingStreamBuf::StreamType type): - InflatingIOS(ostr, type), - std::ostream(&_buf) -{ -} - - -InflatingOutputStream::~InflatingOutputStream() -{ -} - - -int InflatingOutputStream::close() -{ - return _buf.close(); -} - - -InflatingInputStream::InflatingInputStream(std::istream& istr, InflatingStreamBuf::StreamType type): - InflatingIOS(istr, type), - std::istream(&_buf) -{ -} - - -InflatingInputStream::~InflatingInputStream() -{ -} - - -} // namespace Poco +// +// InflatingStream.cpp +// +// $Id: //poco/1.2/Foundation/src/InflatingStream.cpp#1 $ +// +// Library: Foundation +// Package: Streams +// Module: ZLibStream +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/InflatingStream.h" +#include "Poco/Exception.h" + + +namespace Poco { + + +InflatingStreamBuf::InflatingStreamBuf(std::istream& istr, StreamType type): + BufferedStreamBuf(STREAM_BUFFER_SIZE, std::ios::in), + _pIstr(&istr), + _pOstr(0), + _eof(false) +{ + _zstr.zalloc = Z_NULL; + _zstr.zfree = Z_NULL; + _zstr.opaque = Z_NULL; + _zstr.next_in = 0; + _zstr.avail_in = 0; + _zstr.next_out = 0; + _zstr.avail_out = 0; + + int rc = inflateInit2(&_zstr, 15 + (type == STREAM_GZIP ? 16 : 0)); + if (rc != Z_OK) throw IOException(zError(rc)); + + _buffer = new char[INFLATE_BUFFER_SIZE]; +} + + +InflatingStreamBuf::InflatingStreamBuf(std::ostream& ostr, StreamType type): + BufferedStreamBuf(STREAM_BUFFER_SIZE, std::ios::out), + _pIstr(0), + _pOstr(&ostr), + _eof(false) +{ + _zstr.zalloc = Z_NULL; + _zstr.zfree = Z_NULL; + _zstr.opaque = Z_NULL; + _zstr.next_in = 0; + _zstr.avail_in = 0; + _zstr.next_out = 0; + _zstr.avail_out = 0; + + int rc = inflateInit2(&_zstr, 15 + (type == STREAM_GZIP ? 16 : 0)); + if (rc != Z_OK) throw IOException(zError(rc)); + + _buffer = new char[INFLATE_BUFFER_SIZE]; +} + + +InflatingStreamBuf::~InflatingStreamBuf() +{ + try + { + close(); + } + catch (...) + { + } + delete [] _buffer; +} + + +int InflatingStreamBuf::close() +{ + sync(); + if (_pIstr || _pOstr) + { + int rc = inflateEnd(&_zstr); + if (rc != Z_OK) throw IOException(zError(rc)); + _pIstr = 0; + _pOstr = 0; + } + return 0; +} + + +int InflatingStreamBuf::readFromDevice(char* buffer, std::streamsize length) +{ + if (_eof || !_pIstr) return 0; + + if (_zstr.avail_in == 0) + { + int n = 0; + if (_pIstr->good()) + { + _pIstr->read(_buffer, INFLATE_BUFFER_SIZE); + n = _pIstr->gcount(); + } + if (n == 0) return 0; + _zstr.next_in = (unsigned char*) _buffer; + _zstr.avail_in = n; + } + _zstr.next_out = (unsigned char*) buffer; + _zstr.avail_out = length; + for (;;) + { + int rc = inflate(&_zstr, Z_NO_FLUSH); + if (rc == Z_STREAM_END) + { + _eof = true; + return length - _zstr.avail_out; + } + if (rc != Z_OK) throw IOException(zError(rc)); + if (_zstr.avail_out == 0) + return length; + if (_zstr.avail_in == 0) + { + int n = 0; + if (_pIstr->good()) + { + _pIstr->read(_buffer, INFLATE_BUFFER_SIZE); + n = _pIstr->gcount(); + } + if (n > 0) + { + _zstr.next_in = (unsigned char*) _buffer; + _zstr.avail_in = n; + } + } + } +} + + +int InflatingStreamBuf::writeToDevice(const char* buffer, std::streamsize length) +{ + if (length == 0 || !_pOstr) return 0; + + _zstr.next_in = (unsigned char*) buffer; + _zstr.avail_in = length; + _zstr.next_out = (unsigned char*) _buffer; + _zstr.avail_out = INFLATE_BUFFER_SIZE; + for (;;) + { + int rc = inflate(&_zstr, Z_NO_FLUSH); + if (rc == Z_STREAM_END) + { + _pOstr->write(_buffer, INFLATE_BUFFER_SIZE - _zstr.avail_out); + if (!_pOstr->good()) throw IOException(zError(rc)); + break; + } + if (rc != Z_OK) throw IOException(zError(rc)); + if (_zstr.avail_out == 0) + { + _pOstr->write(_buffer, INFLATE_BUFFER_SIZE); + if (!_pOstr->good()) throw IOException(zError(rc)); + _zstr.next_out = (unsigned char*) _buffer; + _zstr.avail_out = INFLATE_BUFFER_SIZE; + } + if (_zstr.avail_in == 0) + { + _pOstr->write(_buffer, INFLATE_BUFFER_SIZE - _zstr.avail_out); + if (!_pOstr->good()) throw IOException(zError(rc)); + _zstr.next_out = (unsigned char*) _buffer; + _zstr.avail_out = INFLATE_BUFFER_SIZE; + break; + } + } + return length; +} + + +InflatingIOS::InflatingIOS(std::ostream& ostr, InflatingStreamBuf::StreamType type): + _buf(ostr, type) +{ + poco_ios_init(&_buf); +} + + +InflatingIOS::InflatingIOS(std::istream& istr, InflatingStreamBuf::StreamType type): + _buf(istr, type) +{ + poco_ios_init(&_buf); +} + + +InflatingIOS::~InflatingIOS() +{ +} + + +InflatingStreamBuf* InflatingIOS::rdbuf() +{ + return &_buf; +} + + +InflatingOutputStream::InflatingOutputStream(std::ostream& ostr, InflatingStreamBuf::StreamType type): + InflatingIOS(ostr, type), + std::ostream(&_buf) +{ +} + + +InflatingOutputStream::~InflatingOutputStream() +{ +} + + +int InflatingOutputStream::close() +{ + return _buf.close(); +} + + +InflatingInputStream::InflatingInputStream(std::istream& istr, InflatingStreamBuf::StreamType type): + InflatingIOS(istr, type), + std::istream(&_buf) +{ +} + + +InflatingInputStream::~InflatingInputStream() +{ +} + + +} // namespace Poco diff --git a/Foundation/src/Latin1Encoding.cpp b/Foundation/src/Latin1Encoding.cpp index ffd685bfd..4dde6f58b 100644 --- a/Foundation/src/Latin1Encoding.cpp +++ b/Foundation/src/Latin1Encoding.cpp @@ -1,97 +1,97 @@ -// -// Latin1Encoding.cpp -// -// $Id: //poco/1.2/Foundation/src/Latin1Encoding.cpp#1 $ -// -// Library: Foundation -// Package: Text -// Module: Latin1Encoding -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/Latin1Encoding.h" - - -namespace Poco { - - -const TextEncoding::CharacterMap Latin1Encoding::_charMap = -{ - /* 00 */ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, - /* 10 */ 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, - /* 20 */ 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, - /* 30 */ 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, - /* 40 */ 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, - /* 50 */ 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, - /* 60 */ 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, - /* 70 */ 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, - /* 80 */ 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, - /* 90 */ 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, - /* a0 */ 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, - /* b0 */ 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, - /* c0 */ 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, - /* d0 */ 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, - /* e0 */ 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, - /* f0 */ 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, -}; - - -Latin1Encoding::Latin1Encoding() -{ -} - - -Latin1Encoding::~Latin1Encoding() -{ -} - - -const TextEncoding::CharacterMap& Latin1Encoding::characterMap() const -{ - return _charMap; -} - - -int Latin1Encoding::convert(const unsigned char* bytes) const -{ - return *bytes; -} - - -int Latin1Encoding::convert(int ch, unsigned char* bytes, int length) const -{ - if (ch >= 0 && ch <= 255) - { - *bytes = (unsigned char) ch; - return 1; - } - else return 0; -} - - -} // namespace Poco +// +// Latin1Encoding.cpp +// +// $Id: //poco/1.2/Foundation/src/Latin1Encoding.cpp#1 $ +// +// Library: Foundation +// Package: Text +// Module: Latin1Encoding +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/Latin1Encoding.h" + + +namespace Poco { + + +const TextEncoding::CharacterMap Latin1Encoding::_charMap = +{ + /* 00 */ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, + /* 10 */ 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, + /* 20 */ 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, + /* 30 */ 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, + /* 40 */ 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, + /* 50 */ 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, + /* 60 */ 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, + /* 70 */ 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, + /* 80 */ 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, + /* 90 */ 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, + /* a0 */ 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, + /* b0 */ 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, + /* c0 */ 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, + /* d0 */ 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, + /* e0 */ 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, + /* f0 */ 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, +}; + + +Latin1Encoding::Latin1Encoding() +{ +} + + +Latin1Encoding::~Latin1Encoding() +{ +} + + +const TextEncoding::CharacterMap& Latin1Encoding::characterMap() const +{ + return _charMap; +} + + +int Latin1Encoding::convert(const unsigned char* bytes) const +{ + return *bytes; +} + + +int Latin1Encoding::convert(int ch, unsigned char* bytes, int length) const +{ + if (ch >= 0 && ch <= 255) + { + *bytes = (unsigned char) ch; + return 1; + } + else return 0; +} + + +} // namespace Poco diff --git a/Foundation/src/Latin9Encoding.cpp b/Foundation/src/Latin9Encoding.cpp index cd22aa9b6..819c544fc 100644 --- a/Foundation/src/Latin9Encoding.cpp +++ b/Foundation/src/Latin9Encoding.cpp @@ -1,108 +1,108 @@ -// -// Latin9Encoding.cpp -// -// $Id: //poco/1.2/Foundation/src/Latin9Encoding.cpp#1 $ -// -// Library: Foundation -// Package: Text -// Module: Latin9Encoding -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/Latin9Encoding.h" - - -namespace Poco { - - -const TextEncoding::CharacterMap Latin9Encoding::_charMap = -{ - /* 00 */ 0x0000, 0x0001, 0x0002, 0x0003, 0x0004, 0x0005, 0x0006, 0x0007, 0x0008, 0x0009, 0x000a, 0x000b, 0x000c, 0x000d, 0x000e, 0x000f, - /* 10 */ 0x0010, 0x0011, 0x0012, 0x0013, 0x0014, 0x0015, 0x0016, 0x0017, 0x0018, 0x0019, 0x001a, 0x001b, 0x001c, 0x001d, 0x001e, 0x001f, - /* 20 */ 0x0020, 0x0021, 0x0022, 0x0023, 0x0024, 0x0025, 0x0026, 0x0027, 0x0028, 0x0029, 0x002a, 0x002b, 0x002c, 0x002d, 0x002e, 0x002f, - /* 30 */ 0x0030, 0x0031, 0x0032, 0x0033, 0x0034, 0x0035, 0x0036, 0x0037, 0x0038, 0x0039, 0x003a, 0x003b, 0x003c, 0x003d, 0x003e, 0x003f, - /* 40 */ 0x0040, 0x0041, 0x0042, 0x0043, 0x0044, 0x0045, 0x0046, 0x0047, 0x0048, 0x0049, 0x004a, 0x004b, 0x004c, 0x004d, 0x004e, 0x004f, - /* 50 */ 0x0050, 0x0051, 0x0052, 0x0053, 0x0054, 0x0055, 0x0056, 0x0057, 0x0058, 0x0059, 0x005a, 0x005b, 0x005c, 0x005d, 0x005e, 0x005f, - /* 60 */ 0x0060, 0x0061, 0x0062, 0x0063, 0x0064, 0x0065, 0x0066, 0x0067, 0x0068, 0x0069, 0x006a, 0x006b, 0x006c, 0x006d, 0x006e, 0x006f, - /* 70 */ 0x0070, 0x0071, 0x0072, 0x0073, 0x0074, 0x0075, 0x0076, 0x0077, 0x0078, 0x0079, 0x007a, 0x007b, 0x007c, 0x007d, 0x007e, 0x007f, - /* 80 */ 0x0080, 0x0081, 0x0082, 0x0083, 0x0084, 0x0085, 0x0086, 0x0087, 0x0088, 0x0089, 0x008a, 0x008b, 0x008c, 0x008d, 0x008e, 0x008f, - /* 90 */ 0x0090, 0x0091, 0x0092, 0x0093, 0x0094, 0x0095, 0x0096, 0x0097, 0x0098, 0x0099, 0x009a, 0x009b, 0x009c, 0x009d, 0x009e, 0x009f, - /* a0 */ 0x00a0, 0x00a1, 0x00a2, 0x00a3, 0x20ac, 0x00a5, 0x0160, 0x00a7, 0x0161, 0x00a9, 0x00aa, 0x00ab, 0x00ac, 0x00ad, 0x00ae, 0x00af, - /* b0 */ 0x00b0, 0x00b1, 0x00b2, 0x00b3, 0x017d, 0x00b5, 0x00b6, 0x00b7, 0x017e, 0x00b9, 0x00ba, 0x00bb, 0x0152, 0x0153, 0x0178, 0x00bf, - /* c0 */ 0x00c0, 0x00c1, 0x00c2, 0x00c3, 0x00c4, 0x00c5, 0x00c6, 0x00c7, 0x00c8, 0x00c9, 0x00ca, 0x00cb, 0x00cc, 0x00cd, 0x00ce, 0x00cf, - /* d0 */ 0x00d0, 0x00d1, 0x00d2, 0x00d3, 0x00d4, 0x00d5, 0x00d6, 0x00d7, 0x00d8, 0x00d9, 0x00da, 0x00db, 0x00dc, 0x00dd, 0x00de, 0x00df, - /* e0 */ 0x00e0, 0x00e1, 0x00e2, 0x00e3, 0x00e4, 0x00e5, 0x00e6, 0x00e7, 0x00e8, 0x00e9, 0x00ea, 0x00eb, 0x00ec, 0x00ed, 0x00ee, 0x00ef, - /* f0 */ 0x00f0, 0x00f1, 0x00f2, 0x00f3, 0x00f4, 0x00f5, 0x00f6, 0x00f7, 0x00f8, 0x00f9, 0x00fa, 0x00fb, 0x00fc, 0x00fd, 0x00fe, 0x00ff, -}; - - -Latin9Encoding::Latin9Encoding() -{ -} - - -Latin9Encoding::~Latin9Encoding() -{ -} - - -const TextEncoding::CharacterMap& Latin9Encoding::characterMap() const -{ - return _charMap; -} - - -int Latin9Encoding::convert(const unsigned char* bytes) const -{ - return *bytes; -} - - -int Latin9Encoding::convert(int ch, unsigned char* bytes, int length) const -{ - if (ch >= 0 && ch <= 255) - { - *bytes = ch; - return 1; - } - else switch (ch) - { - case 0x0152: *bytes = 0xbc; return 1; - case 0x0153: *bytes = 0xbd; return 1; - case 0x0160: *bytes = 0xa6; return 1; - case 0x0161: *bytes = 0xa8; return 1; - case 0x017d: *bytes = 0xb4; return 1; - case 0x017e: *bytes = 0xb8; return 1; - case 0x0178: *bytes = 0xbe; return 1; - case 0x20ac: *bytes = 0xa4; return 1; - default: return 0; - } -} - - -} // namespace Poco +// +// Latin9Encoding.cpp +// +// $Id: //poco/1.2/Foundation/src/Latin9Encoding.cpp#1 $ +// +// Library: Foundation +// Package: Text +// Module: Latin9Encoding +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/Latin9Encoding.h" + + +namespace Poco { + + +const TextEncoding::CharacterMap Latin9Encoding::_charMap = +{ + /* 00 */ 0x0000, 0x0001, 0x0002, 0x0003, 0x0004, 0x0005, 0x0006, 0x0007, 0x0008, 0x0009, 0x000a, 0x000b, 0x000c, 0x000d, 0x000e, 0x000f, + /* 10 */ 0x0010, 0x0011, 0x0012, 0x0013, 0x0014, 0x0015, 0x0016, 0x0017, 0x0018, 0x0019, 0x001a, 0x001b, 0x001c, 0x001d, 0x001e, 0x001f, + /* 20 */ 0x0020, 0x0021, 0x0022, 0x0023, 0x0024, 0x0025, 0x0026, 0x0027, 0x0028, 0x0029, 0x002a, 0x002b, 0x002c, 0x002d, 0x002e, 0x002f, + /* 30 */ 0x0030, 0x0031, 0x0032, 0x0033, 0x0034, 0x0035, 0x0036, 0x0037, 0x0038, 0x0039, 0x003a, 0x003b, 0x003c, 0x003d, 0x003e, 0x003f, + /* 40 */ 0x0040, 0x0041, 0x0042, 0x0043, 0x0044, 0x0045, 0x0046, 0x0047, 0x0048, 0x0049, 0x004a, 0x004b, 0x004c, 0x004d, 0x004e, 0x004f, + /* 50 */ 0x0050, 0x0051, 0x0052, 0x0053, 0x0054, 0x0055, 0x0056, 0x0057, 0x0058, 0x0059, 0x005a, 0x005b, 0x005c, 0x005d, 0x005e, 0x005f, + /* 60 */ 0x0060, 0x0061, 0x0062, 0x0063, 0x0064, 0x0065, 0x0066, 0x0067, 0x0068, 0x0069, 0x006a, 0x006b, 0x006c, 0x006d, 0x006e, 0x006f, + /* 70 */ 0x0070, 0x0071, 0x0072, 0x0073, 0x0074, 0x0075, 0x0076, 0x0077, 0x0078, 0x0079, 0x007a, 0x007b, 0x007c, 0x007d, 0x007e, 0x007f, + /* 80 */ 0x0080, 0x0081, 0x0082, 0x0083, 0x0084, 0x0085, 0x0086, 0x0087, 0x0088, 0x0089, 0x008a, 0x008b, 0x008c, 0x008d, 0x008e, 0x008f, + /* 90 */ 0x0090, 0x0091, 0x0092, 0x0093, 0x0094, 0x0095, 0x0096, 0x0097, 0x0098, 0x0099, 0x009a, 0x009b, 0x009c, 0x009d, 0x009e, 0x009f, + /* a0 */ 0x00a0, 0x00a1, 0x00a2, 0x00a3, 0x20ac, 0x00a5, 0x0160, 0x00a7, 0x0161, 0x00a9, 0x00aa, 0x00ab, 0x00ac, 0x00ad, 0x00ae, 0x00af, + /* b0 */ 0x00b0, 0x00b1, 0x00b2, 0x00b3, 0x017d, 0x00b5, 0x00b6, 0x00b7, 0x017e, 0x00b9, 0x00ba, 0x00bb, 0x0152, 0x0153, 0x0178, 0x00bf, + /* c0 */ 0x00c0, 0x00c1, 0x00c2, 0x00c3, 0x00c4, 0x00c5, 0x00c6, 0x00c7, 0x00c8, 0x00c9, 0x00ca, 0x00cb, 0x00cc, 0x00cd, 0x00ce, 0x00cf, + /* d0 */ 0x00d0, 0x00d1, 0x00d2, 0x00d3, 0x00d4, 0x00d5, 0x00d6, 0x00d7, 0x00d8, 0x00d9, 0x00da, 0x00db, 0x00dc, 0x00dd, 0x00de, 0x00df, + /* e0 */ 0x00e0, 0x00e1, 0x00e2, 0x00e3, 0x00e4, 0x00e5, 0x00e6, 0x00e7, 0x00e8, 0x00e9, 0x00ea, 0x00eb, 0x00ec, 0x00ed, 0x00ee, 0x00ef, + /* f0 */ 0x00f0, 0x00f1, 0x00f2, 0x00f3, 0x00f4, 0x00f5, 0x00f6, 0x00f7, 0x00f8, 0x00f9, 0x00fa, 0x00fb, 0x00fc, 0x00fd, 0x00fe, 0x00ff, +}; + + +Latin9Encoding::Latin9Encoding() +{ +} + + +Latin9Encoding::~Latin9Encoding() +{ +} + + +const TextEncoding::CharacterMap& Latin9Encoding::characterMap() const +{ + return _charMap; +} + + +int Latin9Encoding::convert(const unsigned char* bytes) const +{ + return *bytes; +} + + +int Latin9Encoding::convert(int ch, unsigned char* bytes, int length) const +{ + if (ch >= 0 && ch <= 255) + { + *bytes = ch; + return 1; + } + else switch (ch) + { + case 0x0152: *bytes = 0xbc; return 1; + case 0x0153: *bytes = 0xbd; return 1; + case 0x0160: *bytes = 0xa6; return 1; + case 0x0161: *bytes = 0xa8; return 1; + case 0x017d: *bytes = 0xb4; return 1; + case 0x017e: *bytes = 0xb8; return 1; + case 0x0178: *bytes = 0xbe; return 1; + case 0x20ac: *bytes = 0xa4; return 1; + default: return 0; + } +} + + +} // namespace Poco diff --git a/Foundation/src/LineEndingConverter.cpp b/Foundation/src/LineEndingConverter.cpp index 1247668af..307ab6217 100644 --- a/Foundation/src/LineEndingConverter.cpp +++ b/Foundation/src/LineEndingConverter.cpp @@ -1,204 +1,204 @@ -// -// LineEndingConverter.cpp -// -// $Id: //poco/1.2/Foundation/src/LineEndingConverter.cpp#1 $ -// -// Library: Foundation -// Package: Streams -// Module: LineEndingConverter -// -// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/LineEndingConverter.h" - - -namespace Poco { - - -#if defined(_WIN32) -#define POCO_DEFAULT_NEWLINE_CHARS "\r\n" -#else -#define POCO_DEFAULT_NEWLINE_CHARS "\n" -#endif - - -const std::string LineEnding::NEWLINE_DEFAULT(POCO_DEFAULT_NEWLINE_CHARS); -const std::string LineEnding::NEWLINE_CR("\r"); -const std::string LineEnding::NEWLINE_CRLF("\r\n"); -const std::string LineEnding::NEWLINE_LF("\n"); - - -LineEndingConverterStreamBuf::LineEndingConverterStreamBuf(std::istream& istr): - _pIstr(&istr), - _pOstr(0), - _newLine(LineEnding::NEWLINE_DEFAULT), - _lastChar(0) -{ - _it = _newLine.end(); -} - - -LineEndingConverterStreamBuf::LineEndingConverterStreamBuf(std::ostream& ostr): - _pIstr(0), - _pOstr(&ostr), - _newLine(LineEnding::NEWLINE_DEFAULT), - _lastChar(0) -{ - _it = _newLine.end(); -} - - -LineEndingConverterStreamBuf::~LineEndingConverterStreamBuf() -{ -} - - -void LineEndingConverterStreamBuf::setNewLine(const std::string& newLineCharacters) -{ - _newLine = newLineCharacters; - _it = _newLine.end(); -} - - -const std::string& LineEndingConverterStreamBuf::getNewLine() const -{ - return _newLine; -} - - -int LineEndingConverterStreamBuf::readFromDevice() -{ - poco_assert_dbg (_pIstr); - - while (_it == _newLine.end()) - { - int c = _pIstr->get(); - if (c == '\r') - { - if (_pIstr->peek() == '\n') _pIstr->get(); - _it = _newLine.begin(); - } - else if (c == '\n') - { - _it = _newLine.begin(); - } - else return c; - } - return *_it++; -} - - -int LineEndingConverterStreamBuf::writeToDevice(char c) -{ - poco_assert_dbg (_pOstr); - - if (c == '\r' || c == '\n' && _lastChar != '\r') - _pOstr->write(_newLine.data(), (std::streamsize) _newLine.length()); - if (c != '\n' && c != '\r') - _pOstr->put(c); - _lastChar = c; - return charToInt(c); -} - - -LineEndingConverterIOS::LineEndingConverterIOS(std::istream& istr): _buf(istr) -{ - poco_ios_init(&_buf); -} - - -LineEndingConverterIOS::LineEndingConverterIOS(std::ostream& ostr): _buf(ostr) -{ - poco_ios_init(&_buf); -} - - -LineEndingConverterIOS::~LineEndingConverterIOS() -{ -} - - -void LineEndingConverterIOS::setNewLine(const std::string& newLineCharacters) -{ - _buf.setNewLine(newLineCharacters); -} - - -const std::string& LineEndingConverterIOS::getNewLine() const -{ - return _buf.getNewLine(); -} - - -LineEndingConverterStreamBuf* LineEndingConverterIOS::rdbuf() -{ - return &_buf; -} - - -InputLineEndingConverter::InputLineEndingConverter(std::istream& istr): - LineEndingConverterIOS(istr), - std::istream(&_buf) -{ -} - - -InputLineEndingConverter::InputLineEndingConverter(std::istream& istr, const std::string& newLineCharacters): - LineEndingConverterIOS(istr), - std::istream(&_buf) -{ - setNewLine(newLineCharacters); -} - - -InputLineEndingConverter::~InputLineEndingConverter() -{ -} - - -OutputLineEndingConverter::OutputLineEndingConverter(std::ostream& ostr): - LineEndingConverterIOS(ostr), - std::ostream(&_buf) -{ -} - - -OutputLineEndingConverter::OutputLineEndingConverter(std::ostream& ostr, const std::string& newLineCharacters): - LineEndingConverterIOS(ostr), - std::ostream(&_buf) -{ - setNewLine(newLineCharacters); -} - - -OutputLineEndingConverter::~OutputLineEndingConverter() -{ -} - - -} // namespace Poco +// +// LineEndingConverter.cpp +// +// $Id: //poco/1.2/Foundation/src/LineEndingConverter.cpp#1 $ +// +// Library: Foundation +// Package: Streams +// Module: LineEndingConverter +// +// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/LineEndingConverter.h" + + +namespace Poco { + + +#if defined(_WIN32) +#define POCO_DEFAULT_NEWLINE_CHARS "\r\n" +#else +#define POCO_DEFAULT_NEWLINE_CHARS "\n" +#endif + + +const std::string LineEnding::NEWLINE_DEFAULT(POCO_DEFAULT_NEWLINE_CHARS); +const std::string LineEnding::NEWLINE_CR("\r"); +const std::string LineEnding::NEWLINE_CRLF("\r\n"); +const std::string LineEnding::NEWLINE_LF("\n"); + + +LineEndingConverterStreamBuf::LineEndingConverterStreamBuf(std::istream& istr): + _pIstr(&istr), + _pOstr(0), + _newLine(LineEnding::NEWLINE_DEFAULT), + _lastChar(0) +{ + _it = _newLine.end(); +} + + +LineEndingConverterStreamBuf::LineEndingConverterStreamBuf(std::ostream& ostr): + _pIstr(0), + _pOstr(&ostr), + _newLine(LineEnding::NEWLINE_DEFAULT), + _lastChar(0) +{ + _it = _newLine.end(); +} + + +LineEndingConverterStreamBuf::~LineEndingConverterStreamBuf() +{ +} + + +void LineEndingConverterStreamBuf::setNewLine(const std::string& newLineCharacters) +{ + _newLine = newLineCharacters; + _it = _newLine.end(); +} + + +const std::string& LineEndingConverterStreamBuf::getNewLine() const +{ + return _newLine; +} + + +int LineEndingConverterStreamBuf::readFromDevice() +{ + poco_assert_dbg (_pIstr); + + while (_it == _newLine.end()) + { + int c = _pIstr->get(); + if (c == '\r') + { + if (_pIstr->peek() == '\n') _pIstr->get(); + _it = _newLine.begin(); + } + else if (c == '\n') + { + _it = _newLine.begin(); + } + else return c; + } + return *_it++; +} + + +int LineEndingConverterStreamBuf::writeToDevice(char c) +{ + poco_assert_dbg (_pOstr); + + if (c == '\r' || c == '\n' && _lastChar != '\r') + _pOstr->write(_newLine.data(), (std::streamsize) _newLine.length()); + if (c != '\n' && c != '\r') + _pOstr->put(c); + _lastChar = c; + return charToInt(c); +} + + +LineEndingConverterIOS::LineEndingConverterIOS(std::istream& istr): _buf(istr) +{ + poco_ios_init(&_buf); +} + + +LineEndingConverterIOS::LineEndingConverterIOS(std::ostream& ostr): _buf(ostr) +{ + poco_ios_init(&_buf); +} + + +LineEndingConverterIOS::~LineEndingConverterIOS() +{ +} + + +void LineEndingConverterIOS::setNewLine(const std::string& newLineCharacters) +{ + _buf.setNewLine(newLineCharacters); +} + + +const std::string& LineEndingConverterIOS::getNewLine() const +{ + return _buf.getNewLine(); +} + + +LineEndingConverterStreamBuf* LineEndingConverterIOS::rdbuf() +{ + return &_buf; +} + + +InputLineEndingConverter::InputLineEndingConverter(std::istream& istr): + LineEndingConverterIOS(istr), + std::istream(&_buf) +{ +} + + +InputLineEndingConverter::InputLineEndingConverter(std::istream& istr, const std::string& newLineCharacters): + LineEndingConverterIOS(istr), + std::istream(&_buf) +{ + setNewLine(newLineCharacters); +} + + +InputLineEndingConverter::~InputLineEndingConverter() +{ +} + + +OutputLineEndingConverter::OutputLineEndingConverter(std::ostream& ostr): + LineEndingConverterIOS(ostr), + std::ostream(&_buf) +{ +} + + +OutputLineEndingConverter::OutputLineEndingConverter(std::ostream& ostr, const std::string& newLineCharacters): + LineEndingConverterIOS(ostr), + std::ostream(&_buf) +{ + setNewLine(newLineCharacters); +} + + +OutputLineEndingConverter::~OutputLineEndingConverter() +{ +} + + +} // namespace Poco diff --git a/Foundation/src/LocalDateTime.cpp b/Foundation/src/LocalDateTime.cpp index 435b4a469..b3ac86db8 100644 --- a/Foundation/src/LocalDateTime.cpp +++ b/Foundation/src/LocalDateTime.cpp @@ -1,253 +1,253 @@ -// -// LocalDateTime.cpp -// -// $Id: //poco/1.2/Foundation/src/LocalDateTime.cpp#1 $ -// -// Library: Foundation -// Package: DateTime -// Module: LocalDateTime -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/LocalDateTime.h" -#include "Poco/Timezone.h" -#include "Poco/Timespan.h" -#include - - -namespace Poco { - - -LocalDateTime::LocalDateTime(): - _tzd(Timezone::tzd()) -{ - _dateTime += Timespan(((Timestamp::TimeDiff) _tzd)*Timespan::SECONDS); -} - - -LocalDateTime::LocalDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int microsecond): - _dateTime(year, month, day, hour, minute, second, millisecond, microsecond), - _tzd(Timezone::tzd()) -{ -} - - -LocalDateTime::LocalDateTime(int tzd, int year, int month, int day, int hour, int minute, int second, int millisecond, int microsecond): - _dateTime(year, month, day, hour, minute, second, millisecond, microsecond), - _tzd(tzd) -{ -} - - -LocalDateTime::LocalDateTime(double julianDay): - _dateTime(julianDay), - _tzd(Timezone::tzd()) -{ - _dateTime += Timespan(((Timestamp::TimeDiff) _tzd)*Timespan::SECONDS); -} - - -LocalDateTime::LocalDateTime(int tzd, double julianDay): - _dateTime(julianDay), - _tzd(tzd) -{ - _dateTime += Timespan(((Timestamp::TimeDiff) _tzd)*Timespan::SECONDS); -} - - -LocalDateTime::LocalDateTime(const DateTime& dateTime): - _dateTime(dateTime), - _tzd(Timezone::tzd()) -{ - _dateTime += Timespan(((Timestamp::TimeDiff) _tzd)*Timespan::SECONDS); -} - - -LocalDateTime::LocalDateTime(int tzd, const DateTime& dateTime): - _dateTime(dateTime), - _tzd(tzd) -{ - _dateTime += Timespan(((Timestamp::TimeDiff) _tzd)*Timespan::SECONDS); -} - - -LocalDateTime::LocalDateTime(const LocalDateTime& dateTime): - _dateTime(dateTime._dateTime), - _tzd(dateTime._tzd) -{ -} - - -LocalDateTime::LocalDateTime(Timestamp::UtcTimeVal utcTime, Timestamp::TimeDiff diff, int tzd): - _dateTime(utcTime, diff), - _tzd(tzd) -{ -} - - -LocalDateTime::~LocalDateTime() -{ -} - - -LocalDateTime& LocalDateTime::operator = (const LocalDateTime& dateTime) -{ - if (&dateTime != this) - { - _dateTime = dateTime._dateTime; - _tzd = dateTime._tzd; - } - return *this; -} - - -LocalDateTime& LocalDateTime::operator = (const Timestamp& timestamp) -{ - if (timestamp != this->timestamp()) - _dateTime = timestamp; - - return *this; -} - - -LocalDateTime& LocalDateTime::operator = (double julianDay) -{ - _tzd = Timezone::tzd(); - _dateTime = julianDay; - _dateTime += Timespan(((Timestamp::TimeDiff) _tzd)*Timespan::SECONDS); - return *this; -} - - -LocalDateTime& LocalDateTime::assign(int year, int month, int day, int hour, int minute, int second, int millisecond, int microseconds) -{ - _dateTime.assign(year, month, day, hour, minute, second, millisecond, microseconds); - _tzd = Timezone::tzd(); - return *this; -} - - -LocalDateTime& LocalDateTime::assign(int tzd, int year, int month, int day, int hour, int minute, int second, int millisecond, int microseconds) -{ - _dateTime.assign(year, month, day, hour, minute, second, millisecond, microseconds); - _tzd = tzd; - return *this; -} - - -LocalDateTime& LocalDateTime::assign(int tzd, double julianDay) -{ - _tzd = tzd; - _dateTime = julianDay; - _dateTime += Timespan(((Timestamp::TimeDiff) _tzd)*Timespan::SECONDS); - return *this; -} - - -void LocalDateTime::swap(LocalDateTime& dateTime) -{ - _dateTime.swap(dateTime._dateTime); - std::swap(_tzd, dateTime._tzd); -} - - -DateTime LocalDateTime::utc() const -{ - return DateTime(_dateTime.utcTime(), -((Timestamp::TimeDiff) _tzd)*Timespan::SECONDS); -} - - -bool LocalDateTime::operator == (const LocalDateTime& dateTime) const -{ - return utcTime() == dateTime.utcTime(); -} - - -bool LocalDateTime::operator != (const LocalDateTime& dateTime) const -{ - return utcTime() != dateTime.utcTime(); -} - - -bool LocalDateTime::operator < (const LocalDateTime& dateTime) const -{ - return utcTime() < dateTime.utcTime(); -} - - -bool LocalDateTime::operator <= (const LocalDateTime& dateTime) const -{ - return utcTime() <= dateTime.utcTime(); -} - - -bool LocalDateTime::operator > (const LocalDateTime& dateTime) const -{ - return utcTime() > dateTime.utcTime(); -} - - -bool LocalDateTime::operator >= (const LocalDateTime& dateTime) const -{ - return utcTime() >= dateTime.utcTime(); -} - - -LocalDateTime LocalDateTime::operator + (const Timespan& span) const -{ - return LocalDateTime(_dateTime.utcTime(), span.totalMicroseconds(), _tzd); -} - - -LocalDateTime LocalDateTime::operator - (const Timespan& span) const -{ - return LocalDateTime(_dateTime.utcTime(), -span.totalMicroseconds(), _tzd); -} - - -Timespan LocalDateTime::operator - (const LocalDateTime& dateTime) const -{ - return Timespan((utcTime() - dateTime.utcTime())/10); -} - - -LocalDateTime& LocalDateTime::operator += (const Timespan& span) -{ - _dateTime += span; - return *this; -} - - -LocalDateTime& LocalDateTime::operator -= (const Timespan& span) -{ - _dateTime -= span; - return *this; -} - - -} // namespace Poco +// +// LocalDateTime.cpp +// +// $Id: //poco/1.2/Foundation/src/LocalDateTime.cpp#1 $ +// +// Library: Foundation +// Package: DateTime +// Module: LocalDateTime +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/LocalDateTime.h" +#include "Poco/Timezone.h" +#include "Poco/Timespan.h" +#include + + +namespace Poco { + + +LocalDateTime::LocalDateTime(): + _tzd(Timezone::tzd()) +{ + _dateTime += Timespan(((Timestamp::TimeDiff) _tzd)*Timespan::SECONDS); +} + + +LocalDateTime::LocalDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int microsecond): + _dateTime(year, month, day, hour, minute, second, millisecond, microsecond), + _tzd(Timezone::tzd()) +{ +} + + +LocalDateTime::LocalDateTime(int tzd, int year, int month, int day, int hour, int minute, int second, int millisecond, int microsecond): + _dateTime(year, month, day, hour, minute, second, millisecond, microsecond), + _tzd(tzd) +{ +} + + +LocalDateTime::LocalDateTime(double julianDay): + _dateTime(julianDay), + _tzd(Timezone::tzd()) +{ + _dateTime += Timespan(((Timestamp::TimeDiff) _tzd)*Timespan::SECONDS); +} + + +LocalDateTime::LocalDateTime(int tzd, double julianDay): + _dateTime(julianDay), + _tzd(tzd) +{ + _dateTime += Timespan(((Timestamp::TimeDiff) _tzd)*Timespan::SECONDS); +} + + +LocalDateTime::LocalDateTime(const DateTime& dateTime): + _dateTime(dateTime), + _tzd(Timezone::tzd()) +{ + _dateTime += Timespan(((Timestamp::TimeDiff) _tzd)*Timespan::SECONDS); +} + + +LocalDateTime::LocalDateTime(int tzd, const DateTime& dateTime): + _dateTime(dateTime), + _tzd(tzd) +{ + _dateTime += Timespan(((Timestamp::TimeDiff) _tzd)*Timespan::SECONDS); +} + + +LocalDateTime::LocalDateTime(const LocalDateTime& dateTime): + _dateTime(dateTime._dateTime), + _tzd(dateTime._tzd) +{ +} + + +LocalDateTime::LocalDateTime(Timestamp::UtcTimeVal utcTime, Timestamp::TimeDiff diff, int tzd): + _dateTime(utcTime, diff), + _tzd(tzd) +{ +} + + +LocalDateTime::~LocalDateTime() +{ +} + + +LocalDateTime& LocalDateTime::operator = (const LocalDateTime& dateTime) +{ + if (&dateTime != this) + { + _dateTime = dateTime._dateTime; + _tzd = dateTime._tzd; + } + return *this; +} + + +LocalDateTime& LocalDateTime::operator = (const Timestamp& timestamp) +{ + if (timestamp != this->timestamp()) + _dateTime = timestamp; + + return *this; +} + + +LocalDateTime& LocalDateTime::operator = (double julianDay) +{ + _tzd = Timezone::tzd(); + _dateTime = julianDay; + _dateTime += Timespan(((Timestamp::TimeDiff) _tzd)*Timespan::SECONDS); + return *this; +} + + +LocalDateTime& LocalDateTime::assign(int year, int month, int day, int hour, int minute, int second, int millisecond, int microseconds) +{ + _dateTime.assign(year, month, day, hour, minute, second, millisecond, microseconds); + _tzd = Timezone::tzd(); + return *this; +} + + +LocalDateTime& LocalDateTime::assign(int tzd, int year, int month, int day, int hour, int minute, int second, int millisecond, int microseconds) +{ + _dateTime.assign(year, month, day, hour, minute, second, millisecond, microseconds); + _tzd = tzd; + return *this; +} + + +LocalDateTime& LocalDateTime::assign(int tzd, double julianDay) +{ + _tzd = tzd; + _dateTime = julianDay; + _dateTime += Timespan(((Timestamp::TimeDiff) _tzd)*Timespan::SECONDS); + return *this; +} + + +void LocalDateTime::swap(LocalDateTime& dateTime) +{ + _dateTime.swap(dateTime._dateTime); + std::swap(_tzd, dateTime._tzd); +} + + +DateTime LocalDateTime::utc() const +{ + return DateTime(_dateTime.utcTime(), -((Timestamp::TimeDiff) _tzd)*Timespan::SECONDS); +} + + +bool LocalDateTime::operator == (const LocalDateTime& dateTime) const +{ + return utcTime() == dateTime.utcTime(); +} + + +bool LocalDateTime::operator != (const LocalDateTime& dateTime) const +{ + return utcTime() != dateTime.utcTime(); +} + + +bool LocalDateTime::operator < (const LocalDateTime& dateTime) const +{ + return utcTime() < dateTime.utcTime(); +} + + +bool LocalDateTime::operator <= (const LocalDateTime& dateTime) const +{ + return utcTime() <= dateTime.utcTime(); +} + + +bool LocalDateTime::operator > (const LocalDateTime& dateTime) const +{ + return utcTime() > dateTime.utcTime(); +} + + +bool LocalDateTime::operator >= (const LocalDateTime& dateTime) const +{ + return utcTime() >= dateTime.utcTime(); +} + + +LocalDateTime LocalDateTime::operator + (const Timespan& span) const +{ + return LocalDateTime(_dateTime.utcTime(), span.totalMicroseconds(), _tzd); +} + + +LocalDateTime LocalDateTime::operator - (const Timespan& span) const +{ + return LocalDateTime(_dateTime.utcTime(), -span.totalMicroseconds(), _tzd); +} + + +Timespan LocalDateTime::operator - (const LocalDateTime& dateTime) const +{ + return Timespan((utcTime() - dateTime.utcTime())/10); +} + + +LocalDateTime& LocalDateTime::operator += (const Timespan& span) +{ + _dateTime += span; + return *this; +} + + +LocalDateTime& LocalDateTime::operator -= (const Timespan& span) +{ + _dateTime -= span; + return *this; +} + + +} // namespace Poco diff --git a/Foundation/src/LogFile.cpp b/Foundation/src/LogFile.cpp index 909b8cb08..6f12a9df7 100644 --- a/Foundation/src/LogFile.cpp +++ b/Foundation/src/LogFile.cpp @@ -1,64 +1,64 @@ -// -// LogFile.cpp -// -// $Id: //poco/1.2/Foundation/src/LogFile.cpp#1 $ -// -// Library: Foundation -// Package: Logging -// Module: LogFile -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/LogFile.h" - - -#if defined(POCO_OS_FAMILY_WINDOWS) && defined(POCO_WIN32_UTF8) -#include "LogFile_WIN32U.cpp" -#elif defined(POCO_OS_FAMILY_WINDOWS) -#include "LogFile_WIN32.cpp" -#elif defined(POCO_OS_FAMILY_VMS) -#include "LogFile_VMS.cpp" -#else -#include "LogFile_STD.cpp" -#endif - - -namespace Poco { - - -LogFile::LogFile(const std::string& path): LogFileImpl(path) -{ -} - - -LogFile::~LogFile() -{ -} - - -} // namespace Poco +// +// LogFile.cpp +// +// $Id: //poco/1.2/Foundation/src/LogFile.cpp#1 $ +// +// Library: Foundation +// Package: Logging +// Module: LogFile +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/LogFile.h" + + +#if defined(POCO_OS_FAMILY_WINDOWS) && defined(POCO_WIN32_UTF8) +#include "LogFile_WIN32U.cpp" +#elif defined(POCO_OS_FAMILY_WINDOWS) +#include "LogFile_WIN32.cpp" +#elif defined(POCO_OS_FAMILY_VMS) +#include "LogFile_VMS.cpp" +#else +#include "LogFile_STD.cpp" +#endif + + +namespace Poco { + + +LogFile::LogFile(const std::string& path): LogFileImpl(path) +{ +} + + +LogFile::~LogFile() +{ +} + + +} // namespace Poco diff --git a/Foundation/src/LogFile_STD.cpp b/Foundation/src/LogFile_STD.cpp index d1242d0e6..d90addc61 100644 --- a/Foundation/src/LogFile_STD.cpp +++ b/Foundation/src/LogFile_STD.cpp @@ -1,86 +1,86 @@ -// -// LogFile_STD.cpp -// -// $Id: //poco/1.2/Foundation/src/LogFile_STD.cpp#1 $ -// -// Library: Foundation -// Package: Logging -// Module: LogFile -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/LogFile_STD.h" -#include "Poco/File.h" -#include "Poco/Exception.h" - - -namespace Poco { - - -LogFileImpl::LogFileImpl(const std::string& path): _path(path) -{ - _str.open(path.c_str(), std::ios::app | std::ios::ate); - if (!_str.good()) throw OpenFileException(path); - if (sizeImpl() == 0) - _creationDate = File(path).getLastModified(); - else - _creationDate = File(path).created(); -} - - -LogFileImpl::~LogFileImpl() -{ -} - - -void LogFileImpl::writeImpl(const std::string& text) -{ - _str << text << std::endl; - if (!_str.good()) throw WriteFileException(_path); -} - - -UInt64 LogFileImpl::sizeImpl() const -{ - return (UInt64) _str.tellp(); -} - - -Timestamp LogFileImpl::creationDateImpl() const -{ - return _creationDate; -} - - -const std::string& LogFileImpl::pathImpl() const -{ - return _path; -} - - -} // namespace Poco +// +// LogFile_STD.cpp +// +// $Id: //poco/1.2/Foundation/src/LogFile_STD.cpp#1 $ +// +// Library: Foundation +// Package: Logging +// Module: LogFile +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/LogFile_STD.h" +#include "Poco/File.h" +#include "Poco/Exception.h" + + +namespace Poco { + + +LogFileImpl::LogFileImpl(const std::string& path): _path(path) +{ + _str.open(path.c_str(), std::ios::app | std::ios::ate); + if (!_str.good()) throw OpenFileException(path); + if (sizeImpl() == 0) + _creationDate = File(path).getLastModified(); + else + _creationDate = File(path).created(); +} + + +LogFileImpl::~LogFileImpl() +{ +} + + +void LogFileImpl::writeImpl(const std::string& text) +{ + _str << text << std::endl; + if (!_str.good()) throw WriteFileException(_path); +} + + +UInt64 LogFileImpl::sizeImpl() const +{ + return (UInt64) _str.tellp(); +} + + +Timestamp LogFileImpl::creationDateImpl() const +{ + return _creationDate; +} + + +const std::string& LogFileImpl::pathImpl() const +{ + return _path; +} + + +} // namespace Poco diff --git a/Foundation/src/LogFile_VMS.cpp b/Foundation/src/LogFile_VMS.cpp index 1d9ebd38b..b748e9060 100644 --- a/Foundation/src/LogFile_VMS.cpp +++ b/Foundation/src/LogFile_VMS.cpp @@ -1,91 +1,91 @@ -// -// LogFile_VMS.cpp -// -// $Id: //poco/1.2/Foundation/src/LogFile_VMS.cpp#1 $ -// -// Library: Foundation -// Package: Logging -// Module: LogFile -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/LogFile_VMS.h" -#include "Poco/File.h" -#include "Poco/Exception.h" - - -namespace Poco { - - -LogFileImpl::LogFileImpl(const std::string& path): _path(path) -{ - _file = fopen(path.c_str(), "a", "ctx=rec,bin", "shr=get", "fop=dfw", "alq=500", "deq=500"); - if (!_file) throw OpenFileException(path); - if (size() == 0) - _creationDate = File(path).getLastModified(); - else - _creationDate = File(path).created(); -} - - -LogFileImpl::~LogFileImpl() -{ - fclose(_file); -} - - -void LogFileImpl::writeImpl(const std::string& text) -{ - int rc = fputs(text.c_str(), _file); - if (rc == EOF) throw WriteFileException(_path); - rc = fputc('\n', _file); - if (rc == EOF) throw WriteFileException(_path); - rc = fflush(_file); - if (rc == EOF) throw WriteFileException(_path); -} - - -UInt64 LogFileImpl::sizeImpl() const -{ - return (UInt64) ftell(_file); -} - - -Timestamp LogFileImpl::creationDateImpl() const -{ - return _creationDate; -} - - -const std::string& LogFileImpl::pathImpl() const -{ - return _path; -} - - -} // namespace Poco +// +// LogFile_VMS.cpp +// +// $Id: //poco/1.2/Foundation/src/LogFile_VMS.cpp#1 $ +// +// Library: Foundation +// Package: Logging +// Module: LogFile +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/LogFile_VMS.h" +#include "Poco/File.h" +#include "Poco/Exception.h" + + +namespace Poco { + + +LogFileImpl::LogFileImpl(const std::string& path): _path(path) +{ + _file = fopen(path.c_str(), "a", "ctx=rec,bin", "shr=get", "fop=dfw", "alq=500", "deq=500"); + if (!_file) throw OpenFileException(path); + if (size() == 0) + _creationDate = File(path).getLastModified(); + else + _creationDate = File(path).created(); +} + + +LogFileImpl::~LogFileImpl() +{ + fclose(_file); +} + + +void LogFileImpl::writeImpl(const std::string& text) +{ + int rc = fputs(text.c_str(), _file); + if (rc == EOF) throw WriteFileException(_path); + rc = fputc('\n', _file); + if (rc == EOF) throw WriteFileException(_path); + rc = fflush(_file); + if (rc == EOF) throw WriteFileException(_path); +} + + +UInt64 LogFileImpl::sizeImpl() const +{ + return (UInt64) ftell(_file); +} + + +Timestamp LogFileImpl::creationDateImpl() const +{ + return _creationDate; +} + + +const std::string& LogFileImpl::pathImpl() const +{ + return _path; +} + + +} // namespace Poco diff --git a/Foundation/src/LogFile_WIN32.cpp b/Foundation/src/LogFile_WIN32.cpp index 53552a7f0..77f7d8c33 100644 --- a/Foundation/src/LogFile_WIN32.cpp +++ b/Foundation/src/LogFile_WIN32.cpp @@ -1,109 +1,109 @@ -// -// LogFile_WIN32.cpp -// -// $Id: //poco/1.2/Foundation/src/LogFile_WIN32.cpp#1 $ -// -// Library: Foundation -// Package: Logging -// Module: LogFile -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/LogFile_WIN32.h" -#include "Poco/File.h" -#include "Poco/Exception.h" - - -namespace Poco { - - -LogFileImpl::LogFileImpl(const std::string& path): _path(path) -{ - _hFile = CreateFile(path.c_str(), GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); - if (_hFile == INVALID_HANDLE_VALUE) throw OpenFileException(path); - SetFilePointer(_hFile, 0, 0, FILE_END); - // There seems to be a strange "optimization" in the Windows NTFS - // filesystem that causes it to reuse directory entries of deleted - // files. Example: - // 1. create a file named "test.dat" - // note the file's creation date - // 2. delete the file "test.dat" - // 3. wait a few seconds - // 4. create a file named "test.dat" - // the new file will have the same creation - // date as the old one. - // We work around this bug by taking the file's - // modification date as a reference when the - // file is empty. - if (sizeImpl() == 0) - _creationDate = File(path).getLastModified(); - else - _creationDate = File(path).created(); -} - - -LogFileImpl::~LogFileImpl() -{ - CloseHandle(_hFile); -} - - -void LogFileImpl::writeImpl(const std::string& text) -{ - DWORD bytesWritten; - BOOL res = WriteFile(_hFile, text.data(), (DWORD) text.size(), &bytesWritten, NULL); - if (!res) throw WriteFileException(_path); - res = WriteFile(_hFile, "\r\n", 2, &bytesWritten, NULL); - if (!res) throw WriteFileException(_path); - res = FlushFileBuffers(_hFile); - if (!res) throw WriteFileException(_path); -} - - -UInt64 LogFileImpl::sizeImpl() const -{ - LARGE_INTEGER li; - li.HighPart = 0; - li.LowPart = SetFilePointer(_hFile, 0, &li.HighPart, FILE_CURRENT); - return li.QuadPart; -} - - -Timestamp LogFileImpl::creationDateImpl() const -{ - return _creationDate; -} - - -const std::string& LogFileImpl::pathImpl() const -{ - return _path; -} - - -} // namespace Poco +// +// LogFile_WIN32.cpp +// +// $Id: //poco/1.2/Foundation/src/LogFile_WIN32.cpp#1 $ +// +// Library: Foundation +// Package: Logging +// Module: LogFile +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/LogFile_WIN32.h" +#include "Poco/File.h" +#include "Poco/Exception.h" + + +namespace Poco { + + +LogFileImpl::LogFileImpl(const std::string& path): _path(path) +{ + _hFile = CreateFile(path.c_str(), GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); + if (_hFile == INVALID_HANDLE_VALUE) throw OpenFileException(path); + SetFilePointer(_hFile, 0, 0, FILE_END); + // There seems to be a strange "optimization" in the Windows NTFS + // filesystem that causes it to reuse directory entries of deleted + // files. Example: + // 1. create a file named "test.dat" + // note the file's creation date + // 2. delete the file "test.dat" + // 3. wait a few seconds + // 4. create a file named "test.dat" + // the new file will have the same creation + // date as the old one. + // We work around this bug by taking the file's + // modification date as a reference when the + // file is empty. + if (sizeImpl() == 0) + _creationDate = File(path).getLastModified(); + else + _creationDate = File(path).created(); +} + + +LogFileImpl::~LogFileImpl() +{ + CloseHandle(_hFile); +} + + +void LogFileImpl::writeImpl(const std::string& text) +{ + DWORD bytesWritten; + BOOL res = WriteFile(_hFile, text.data(), (DWORD) text.size(), &bytesWritten, NULL); + if (!res) throw WriteFileException(_path); + res = WriteFile(_hFile, "\r\n", 2, &bytesWritten, NULL); + if (!res) throw WriteFileException(_path); + res = FlushFileBuffers(_hFile); + if (!res) throw WriteFileException(_path); +} + + +UInt64 LogFileImpl::sizeImpl() const +{ + LARGE_INTEGER li; + li.HighPart = 0; + li.LowPart = SetFilePointer(_hFile, 0, &li.HighPart, FILE_CURRENT); + return li.QuadPart; +} + + +Timestamp LogFileImpl::creationDateImpl() const +{ + return _creationDate; +} + + +const std::string& LogFileImpl::pathImpl() const +{ + return _path; +} + + +} // namespace Poco diff --git a/Foundation/src/LogFile_WIN32U.cpp b/Foundation/src/LogFile_WIN32U.cpp index 921fdcad8..459fbec22 100644 --- a/Foundation/src/LogFile_WIN32U.cpp +++ b/Foundation/src/LogFile_WIN32U.cpp @@ -1,112 +1,112 @@ -// -// LogFile_WIN32U.cpp -// -// $Id: //poco/1.2/Foundation/src/LogFile_WIN32U.cpp#1 $ -// -// Library: Foundation -// Package: Logging -// Module: LogFile -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/LogFile_WIN32U.h" -#include "Poco/File.h" -#include "Poco/Exception.h" -#include "Poco/UnicodeConverter.h" - - -namespace Poco { - - -LogFileImpl::LogFileImpl(const std::string& path): _path(path) -{ - std::wstring upath; - UnicodeConverter::toUTF16(path, upath); - _hFile = CreateFileW(upath.c_str(), GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); - if (_hFile == INVALID_HANDLE_VALUE) throw OpenFileException(path); - SetFilePointer(_hFile, 0, 0, FILE_END); - // There seems to be a strange "optimization" in the Windows NTFS - // filesystem that causes it to reuse directory entries of deleted - // files. Example: - // 1. create a file named "test.dat" - // note the file's creation date - // 2. delete the file "test.dat" - // 3. wait a few seconds - // 4. create a file named "test.dat" - // the new file will have the same creation - // date as the old one. - // We work around this bug by taking the file's - // modification date as a reference when the - // file is empty. - if (sizeImpl() == 0) - _creationDate = File(path).getLastModified(); - else - _creationDate = File(path).created(); -} - - -LogFileImpl::~LogFileImpl() -{ - CloseHandle(_hFile); -} - - -void LogFileImpl::writeImpl(const std::string& text) -{ - DWORD bytesWritten; - BOOL res = WriteFile(_hFile, text.data(), (DWORD) text.size(), &bytesWritten, NULL); - if (!res) throw WriteFileException(_path); - res = WriteFile(_hFile, "\r\n", 2, &bytesWritten, NULL); - if (!res) throw WriteFileException(_path); - res = FlushFileBuffers(_hFile); - if (!res) throw WriteFileException(_path); -} - - -UInt64 LogFileImpl::sizeImpl() const -{ - LARGE_INTEGER li; - li.HighPart = 0; - li.LowPart = SetFilePointer(_hFile, 0, &li.HighPart, FILE_CURRENT); - return li.QuadPart; -} - - -Timestamp LogFileImpl::creationDateImpl() const -{ - return _creationDate; -} - - -const std::string& LogFileImpl::pathImpl() const -{ - return _path; -} - - -} // namespace Poco +// +// LogFile_WIN32U.cpp +// +// $Id: //poco/1.2/Foundation/src/LogFile_WIN32U.cpp#1 $ +// +// Library: Foundation +// Package: Logging +// Module: LogFile +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/LogFile_WIN32U.h" +#include "Poco/File.h" +#include "Poco/Exception.h" +#include "Poco/UnicodeConverter.h" + + +namespace Poco { + + +LogFileImpl::LogFileImpl(const std::string& path): _path(path) +{ + std::wstring upath; + UnicodeConverter::toUTF16(path, upath); + _hFile = CreateFileW(upath.c_str(), GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); + if (_hFile == INVALID_HANDLE_VALUE) throw OpenFileException(path); + SetFilePointer(_hFile, 0, 0, FILE_END); + // There seems to be a strange "optimization" in the Windows NTFS + // filesystem that causes it to reuse directory entries of deleted + // files. Example: + // 1. create a file named "test.dat" + // note the file's creation date + // 2. delete the file "test.dat" + // 3. wait a few seconds + // 4. create a file named "test.dat" + // the new file will have the same creation + // date as the old one. + // We work around this bug by taking the file's + // modification date as a reference when the + // file is empty. + if (sizeImpl() == 0) + _creationDate = File(path).getLastModified(); + else + _creationDate = File(path).created(); +} + + +LogFileImpl::~LogFileImpl() +{ + CloseHandle(_hFile); +} + + +void LogFileImpl::writeImpl(const std::string& text) +{ + DWORD bytesWritten; + BOOL res = WriteFile(_hFile, text.data(), (DWORD) text.size(), &bytesWritten, NULL); + if (!res) throw WriteFileException(_path); + res = WriteFile(_hFile, "\r\n", 2, &bytesWritten, NULL); + if (!res) throw WriteFileException(_path); + res = FlushFileBuffers(_hFile); + if (!res) throw WriteFileException(_path); +} + + +UInt64 LogFileImpl::sizeImpl() const +{ + LARGE_INTEGER li; + li.HighPart = 0; + li.LowPart = SetFilePointer(_hFile, 0, &li.HighPart, FILE_CURRENT); + return li.QuadPart; +} + + +Timestamp LogFileImpl::creationDateImpl() const +{ + return _creationDate; +} + + +const std::string& LogFileImpl::pathImpl() const +{ + return _path; +} + + +} // namespace Poco diff --git a/Foundation/src/LogStream.cpp b/Foundation/src/LogStream.cpp index 1594c062f..2d43d43e4 100644 --- a/Foundation/src/LogStream.cpp +++ b/Foundation/src/LogStream.cpp @@ -1,181 +1,181 @@ -// -// LogStream.cpp -// -// $Id: //poco/1.2/Foundation/src/LogStream.cpp#1 $ -// -// Library: Foundation -// Package: Logging -// Module: LogStream -// -// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/LogStream.h" - - -namespace Poco { - - -// -// LogStreamBuf -// - - -LogStreamBuf::LogStreamBuf(Logger& logger, Message::Priority priority): - _logger(logger), - _priority(priority) -{ -} - - -LogStreamBuf::~LogStreamBuf() -{ -} - - -void LogStreamBuf::setPriority(Message::Priority priority) -{ - _priority = priority; -} - - -int LogStreamBuf::writeToDevice(char c) -{ - if (c == '\n' || c == '\r') - { - Message msg(_logger.name(), _message, _priority); - _message.clear(); - _logger.log(msg); - } - else _message += c; - return c; -} - - -// -// LogIOS -// - - -LogIOS::LogIOS(Logger& logger, Message::Priority priority): - _buf(logger, priority) -{ - poco_ios_init(&_buf); -} - - -LogIOS::~LogIOS() -{ -} - - -LogStreamBuf* LogIOS::rdbuf() -{ - return &_buf; -} - - -// -// LogStream -// - - -LogStream::LogStream(Logger& logger, Message::Priority priority): - LogIOS(logger, priority), - std::ostream(&_buf) -{ -} - - -LogStream::LogStream(const std::string& loggerName, Message::Priority priority): - LogIOS(Logger::get(loggerName), priority), - std::ostream(&_buf) -{ -} - - -LogStream::~LogStream() -{ -} - - -LogStream& LogStream::fatal() -{ - return priority(Message::PRIO_FATAL); -} - - -LogStream& LogStream::critical() -{ - return priority(Message::PRIO_CRITICAL); -} - - -LogStream& LogStream::error() -{ - return priority(Message::PRIO_ERROR); -} - - -LogStream& LogStream::warning() -{ - return priority(Message::PRIO_WARNING); -} - - -LogStream& LogStream::notice() -{ - return priority(Message::PRIO_NOTICE); -} - - -LogStream& LogStream::information() -{ - return priority(Message::PRIO_INFORMATION); -} - - -LogStream& LogStream::debug() -{ - return priority(Message::PRIO_DEBUG); -} - - -LogStream& LogStream::trace() -{ - return priority(Message::PRIO_TRACE); -} - - -LogStream& LogStream::priority(Message::Priority priority) -{ - _buf.setPriority(priority); - return *this; -} - - -} // namespace Poco +// +// LogStream.cpp +// +// $Id: //poco/1.2/Foundation/src/LogStream.cpp#1 $ +// +// Library: Foundation +// Package: Logging +// Module: LogStream +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/LogStream.h" + + +namespace Poco { + + +// +// LogStreamBuf +// + + +LogStreamBuf::LogStreamBuf(Logger& logger, Message::Priority priority): + _logger(logger), + _priority(priority) +{ +} + + +LogStreamBuf::~LogStreamBuf() +{ +} + + +void LogStreamBuf::setPriority(Message::Priority priority) +{ + _priority = priority; +} + + +int LogStreamBuf::writeToDevice(char c) +{ + if (c == '\n' || c == '\r') + { + Message msg(_logger.name(), _message, _priority); + _message.clear(); + _logger.log(msg); + } + else _message += c; + return c; +} + + +// +// LogIOS +// + + +LogIOS::LogIOS(Logger& logger, Message::Priority priority): + _buf(logger, priority) +{ + poco_ios_init(&_buf); +} + + +LogIOS::~LogIOS() +{ +} + + +LogStreamBuf* LogIOS::rdbuf() +{ + return &_buf; +} + + +// +// LogStream +// + + +LogStream::LogStream(Logger& logger, Message::Priority priority): + LogIOS(logger, priority), + std::ostream(&_buf) +{ +} + + +LogStream::LogStream(const std::string& loggerName, Message::Priority priority): + LogIOS(Logger::get(loggerName), priority), + std::ostream(&_buf) +{ +} + + +LogStream::~LogStream() +{ +} + + +LogStream& LogStream::fatal() +{ + return priority(Message::PRIO_FATAL); +} + + +LogStream& LogStream::critical() +{ + return priority(Message::PRIO_CRITICAL); +} + + +LogStream& LogStream::error() +{ + return priority(Message::PRIO_ERROR); +} + + +LogStream& LogStream::warning() +{ + return priority(Message::PRIO_WARNING); +} + + +LogStream& LogStream::notice() +{ + return priority(Message::PRIO_NOTICE); +} + + +LogStream& LogStream::information() +{ + return priority(Message::PRIO_INFORMATION); +} + + +LogStream& LogStream::debug() +{ + return priority(Message::PRIO_DEBUG); +} + + +LogStream& LogStream::trace() +{ + return priority(Message::PRIO_TRACE); +} + + +LogStream& LogStream::priority(Message::Priority priority) +{ + _buf.setPriority(priority); + return *this; +} + + +} // namespace Poco diff --git a/Foundation/src/Logger.cpp b/Foundation/src/Logger.cpp index 5a28089ce..881b7343d 100644 --- a/Foundation/src/Logger.cpp +++ b/Foundation/src/Logger.cpp @@ -1,458 +1,458 @@ -// -// Logger.cpp -// -// $Id: //poco/1.2/Foundation/src/Logger.cpp#2 $ -// -// Library: Foundation -// Package: Logging -// Module: Logger -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/Logger.h" -#include "Poco/Formatter.h" -#include "Poco/LoggingRegistry.h" -#include "Poco/Exception.h" -#include "Poco/NumberFormatter.h" - - -namespace Poco { - - -Logger::LoggerMap* Logger::_pLoggerMap = 0; -Mutex Logger::_mapMtx; -const std::string Logger::ROOT; - - -Logger::Logger(const std::string& name, Channel* pChannel, int level): _name(name), _pChannel(pChannel), _level(level) -{ - if (pChannel) pChannel->duplicate(); -} - - -Logger::~Logger() -{ - if (_pChannel) _pChannel->release(); -} - - -void Logger::setChannel(Channel* pChannel) -{ - if (_pChannel) _pChannel->release(); - _pChannel = pChannel; - if (_pChannel) _pChannel->duplicate(); -} - - -Channel* Logger::getChannel() const -{ - return _pChannel; -} - - -void Logger::setLevel(int level) -{ - _level = level; -} - - -void Logger::setLevel(const std::string& level) -{ - if (level == "fatal") - setLevel(Message::PRIO_FATAL); - else if (level == "critical") - setLevel(Message::PRIO_CRITICAL); - else if (level == "error") - setLevel(Message::PRIO_ERROR); - else if (level == "warning") - setLevel(Message::PRIO_WARNING); - else if (level == "notice") - setLevel(Message::PRIO_NOTICE); - else if (level == "information") - setLevel(Message::PRIO_INFORMATION); - else if (level == "debug") - setLevel(Message::PRIO_DEBUG); - else if (level == "trace") - setLevel(Message::PRIO_TRACE); - else - throw InvalidArgumentException("Not a valid log level", level); -} - - -void Logger::setProperty(const std::string& name, const std::string& value) -{ - if (name == "channel") - setChannel(LoggingRegistry::defaultRegistry().channelForName(value)); - else if (name == "level") - setLevel(value); - else - Channel::setProperty(name, value); -} - - -void Logger::log(const Message& msg) -{ - if (_level >= msg.getPriority() && _pChannel) - { - _pChannel->log(msg); - } -} - - -void Logger::log(const Exception& exc) -{ - error(exc.displayText()); -} - - -void Logger::dump(const std::string& msg, const void* buffer, int length, Message::Priority prio) -{ - if (_level >= prio && _pChannel) - { - std::string text(msg); - formatDump(text, buffer, length); - _pChannel->log(Message(_name, text, prio)); - } -} - - -void Logger::setLevel(const std::string& name, int level) -{ - Mutex::ScopedLock lock(_mapMtx); - - if (_pLoggerMap) - { - std::string::size_type len = name.length(); - for (LoggerMap::iterator it = _pLoggerMap->begin(); it != _pLoggerMap->end(); ++it) - { - if (len == 0 || it->first.compare(0, len, name) == 0 && (it->first.length() == len || it->first[len] == '.')) - it->second->setLevel(level); - } - } -} - - -void Logger::setChannel(const std::string& name, Channel* pChannel) -{ - Mutex::ScopedLock lock(_mapMtx); - - if (_pLoggerMap) - { - std::string::size_type len = name.length(); - for (LoggerMap::iterator it = _pLoggerMap->begin(); it != _pLoggerMap->end(); ++it) - { - if (len == 0 || it->first.compare(0, len, name) == 0 && (it->first.length() == len || it->first[len] == '.')) - it->second->setChannel(pChannel); - } - } -} - - -void Logger::setProperty(const std::string& loggerName, const std::string& propertyName, const std::string& value) -{ - Mutex::ScopedLock lock(_mapMtx); - - if (_pLoggerMap) - { - std::string::size_type len = loggerName.length(); - for (LoggerMap::iterator it = _pLoggerMap->begin(); it != _pLoggerMap->end(); ++it) - { - if (len == 0 || it->first.compare(0, len, loggerName) == 0 && (it->first.length() == len || it->first[len] == '.')) - it->second->setProperty(propertyName, value); - } - } -} - - -std::string Logger::format(const std::string& fmt, const std::string& arg) -{ - std::string args[] = - { - arg - }; - return format(fmt, 1, args); -} - - -std::string Logger::format(const std::string& fmt, const std::string& arg0, const std::string& arg1) -{ - std::string args[] = - { - arg0, - arg1 - }; - return format(fmt, 2, args); -} - - -std::string Logger::format(const std::string& fmt, const std::string& arg0, const std::string& arg1, const std::string& arg2) -{ - std::string args[] = - { - arg0, - arg1, - arg2 - }; - return format(fmt, 3, args); -} - - -std::string Logger::format(const std::string& fmt, const std::string& arg0, const std::string& arg1, const std::string& arg2, const std::string& arg3) -{ - std::string args[] = - { - arg0, - arg1, - arg2, - arg3 - }; - return format(fmt, 4, args); -} - - -std::string Logger::format(const std::string& fmt, int argc, std::string argv[]) -{ - std::string result; - std::string::const_iterator it = fmt.begin(); - while (it != fmt.end()) - { - if (*it == '$') - { - ++it; - if (*it == '$') - { - result += '$'; - } - else if (*it >= '0' && *it <= '9') - { - int i = *it - '0'; - if (i < argc) - result += argv[i]; - } - else - { - result += '$'; - result += *it; - } - } - else result += *it; - ++it; - } - return result; -} - - -void Logger::formatDump(std::string& message, const void* buffer, int length) -{ - const int BYTES_PER_LINE = 16; - - message.reserve(message.size() + length*6); - if (!message.empty()) message.append("\n"); - unsigned char* base = (unsigned char*) buffer; - int addr = 0; - while (addr < length) - { - if (addr > 0) message.append("\n"); - message.append(NumberFormatter::formatHex(addr, 4)); - message.append(" "); - int offset = 0; - while (addr + offset < length && offset < BYTES_PER_LINE) - { - message.append(NumberFormatter::formatHex(base[addr + offset], 2)); - message.append(offset == 7 ? " " : " "); - ++offset; - } - if (offset < 7) message.append(" "); - while (offset < BYTES_PER_LINE) { message.append(" "); ++offset; } - message.append(" "); - offset = 0; - while (addr + offset < length && offset < BYTES_PER_LINE) - { - unsigned char c = base[addr + offset]; - message += (c >= 32 && c < 127) ? (char) c : '.'; - ++offset; - } - addr += BYTES_PER_LINE; - } -} - - -Logger& Logger::get(const std::string& name) -{ - Mutex::ScopedLock lock(_mapMtx); - - return unsafeGet(name); -} - - -Logger& Logger::unsafeGet(const std::string& name) -{ - Logger* pLogger = find(name); - if (!pLogger) - { - if (name == ROOT) - { - pLogger = new Logger(name, 0, Message::PRIO_INFORMATION); - } - else - { - Logger& par = parent(name); - pLogger = new Logger(name, par.getChannel(), par.getLevel()); - } - add(pLogger); - } - return *pLogger; -} - - -Logger& Logger::create(const std::string& name, Channel* pChannel, int level) -{ - Mutex::ScopedLock lock(_mapMtx); - - if (find(name)) throw ExistsException(); - Logger* pLogger = new Logger(name, pChannel, level); - add(pLogger); - return *pLogger; -} - - -Logger& Logger::root() -{ - Mutex::ScopedLock lock(_mapMtx); - - return unsafeGet(ROOT); -} - - -Logger* Logger::has(const std::string& name) -{ - Mutex::ScopedLock lock(_mapMtx); - - return find(name); -} - - -void Logger::shutdown() -{ - Mutex::ScopedLock lock(_mapMtx); - - if (_pLoggerMap) - { - for (LoggerMap::iterator it = _pLoggerMap->begin(); it != _pLoggerMap->end(); ++it) - { - it->second->release(); - } - delete _pLoggerMap; - _pLoggerMap = 0; - } -} - - -Logger* Logger::find(const std::string& name) -{ - if (_pLoggerMap) - { - LoggerMap::iterator it = _pLoggerMap->find(name); - if (it != _pLoggerMap->end()) - return it->second; - } - return 0; -} - - -void Logger::destroy(const std::string& name) -{ - Mutex::ScopedLock lock(_mapMtx); - - if (_pLoggerMap) - { - LoggerMap::iterator it = _pLoggerMap->find(name); - if (it != _pLoggerMap->end()) - { - it->second->release(); - _pLoggerMap->erase(it); - } - } -} - - -void Logger::names(std::vector& names) -{ - Mutex::ScopedLock lock(_mapMtx); - - names.clear(); - if (_pLoggerMap) - { - for (LoggerMap::const_iterator it = _pLoggerMap->begin(); it != _pLoggerMap->end(); ++it) - { - names.push_back(it->first); - } - } -} - - -Logger& Logger::parent(const std::string& name) -{ - std::string::size_type pos = name.rfind('.'); - if (pos != std::string::npos) - { - std::string pname = name.substr(0, pos); - Logger* pParent = find(pname); - if (pParent) - return *pParent; - else - return parent(pname); - } - else return unsafeGet(ROOT); -} - - -class AutoLoggerShutdown -{ -public: - AutoLoggerShutdown() - { - } - ~AutoLoggerShutdown() - { - Logger::shutdown(); - } -}; - - -void Logger::add(Logger* pLogger) -{ - static AutoLoggerShutdown als; - - if (!_pLoggerMap) - _pLoggerMap = new LoggerMap; - _pLoggerMap->insert(LoggerMap::value_type(pLogger->name(), pLogger)); -} - - -} // namespace Poco +// +// Logger.cpp +// +// $Id: //poco/1.2/Foundation/src/Logger.cpp#2 $ +// +// Library: Foundation +// Package: Logging +// Module: Logger +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/Logger.h" +#include "Poco/Formatter.h" +#include "Poco/LoggingRegistry.h" +#include "Poco/Exception.h" +#include "Poco/NumberFormatter.h" + + +namespace Poco { + + +Logger::LoggerMap* Logger::_pLoggerMap = 0; +Mutex Logger::_mapMtx; +const std::string Logger::ROOT; + + +Logger::Logger(const std::string& name, Channel* pChannel, int level): _name(name), _pChannel(pChannel), _level(level) +{ + if (pChannel) pChannel->duplicate(); +} + + +Logger::~Logger() +{ + if (_pChannel) _pChannel->release(); +} + + +void Logger::setChannel(Channel* pChannel) +{ + if (_pChannel) _pChannel->release(); + _pChannel = pChannel; + if (_pChannel) _pChannel->duplicate(); +} + + +Channel* Logger::getChannel() const +{ + return _pChannel; +} + + +void Logger::setLevel(int level) +{ + _level = level; +} + + +void Logger::setLevel(const std::string& level) +{ + if (level == "fatal") + setLevel(Message::PRIO_FATAL); + else if (level == "critical") + setLevel(Message::PRIO_CRITICAL); + else if (level == "error") + setLevel(Message::PRIO_ERROR); + else if (level == "warning") + setLevel(Message::PRIO_WARNING); + else if (level == "notice") + setLevel(Message::PRIO_NOTICE); + else if (level == "information") + setLevel(Message::PRIO_INFORMATION); + else if (level == "debug") + setLevel(Message::PRIO_DEBUG); + else if (level == "trace") + setLevel(Message::PRIO_TRACE); + else + throw InvalidArgumentException("Not a valid log level", level); +} + + +void Logger::setProperty(const std::string& name, const std::string& value) +{ + if (name == "channel") + setChannel(LoggingRegistry::defaultRegistry().channelForName(value)); + else if (name == "level") + setLevel(value); + else + Channel::setProperty(name, value); +} + + +void Logger::log(const Message& msg) +{ + if (_level >= msg.getPriority() && _pChannel) + { + _pChannel->log(msg); + } +} + + +void Logger::log(const Exception& exc) +{ + error(exc.displayText()); +} + + +void Logger::dump(const std::string& msg, const void* buffer, int length, Message::Priority prio) +{ + if (_level >= prio && _pChannel) + { + std::string text(msg); + formatDump(text, buffer, length); + _pChannel->log(Message(_name, text, prio)); + } +} + + +void Logger::setLevel(const std::string& name, int level) +{ + Mutex::ScopedLock lock(_mapMtx); + + if (_pLoggerMap) + { + std::string::size_type len = name.length(); + for (LoggerMap::iterator it = _pLoggerMap->begin(); it != _pLoggerMap->end(); ++it) + { + if (len == 0 || it->first.compare(0, len, name) == 0 && (it->first.length() == len || it->first[len] == '.')) + it->second->setLevel(level); + } + } +} + + +void Logger::setChannel(const std::string& name, Channel* pChannel) +{ + Mutex::ScopedLock lock(_mapMtx); + + if (_pLoggerMap) + { + std::string::size_type len = name.length(); + for (LoggerMap::iterator it = _pLoggerMap->begin(); it != _pLoggerMap->end(); ++it) + { + if (len == 0 || it->first.compare(0, len, name) == 0 && (it->first.length() == len || it->first[len] == '.')) + it->second->setChannel(pChannel); + } + } +} + + +void Logger::setProperty(const std::string& loggerName, const std::string& propertyName, const std::string& value) +{ + Mutex::ScopedLock lock(_mapMtx); + + if (_pLoggerMap) + { + std::string::size_type len = loggerName.length(); + for (LoggerMap::iterator it = _pLoggerMap->begin(); it != _pLoggerMap->end(); ++it) + { + if (len == 0 || it->first.compare(0, len, loggerName) == 0 && (it->first.length() == len || it->first[len] == '.')) + it->second->setProperty(propertyName, value); + } + } +} + + +std::string Logger::format(const std::string& fmt, const std::string& arg) +{ + std::string args[] = + { + arg + }; + return format(fmt, 1, args); +} + + +std::string Logger::format(const std::string& fmt, const std::string& arg0, const std::string& arg1) +{ + std::string args[] = + { + arg0, + arg1 + }; + return format(fmt, 2, args); +} + + +std::string Logger::format(const std::string& fmt, const std::string& arg0, const std::string& arg1, const std::string& arg2) +{ + std::string args[] = + { + arg0, + arg1, + arg2 + }; + return format(fmt, 3, args); +} + + +std::string Logger::format(const std::string& fmt, const std::string& arg0, const std::string& arg1, const std::string& arg2, const std::string& arg3) +{ + std::string args[] = + { + arg0, + arg1, + arg2, + arg3 + }; + return format(fmt, 4, args); +} + + +std::string Logger::format(const std::string& fmt, int argc, std::string argv[]) +{ + std::string result; + std::string::const_iterator it = fmt.begin(); + while (it != fmt.end()) + { + if (*it == '$') + { + ++it; + if (*it == '$') + { + result += '$'; + } + else if (*it >= '0' && *it <= '9') + { + int i = *it - '0'; + if (i < argc) + result += argv[i]; + } + else + { + result += '$'; + result += *it; + } + } + else result += *it; + ++it; + } + return result; +} + + +void Logger::formatDump(std::string& message, const void* buffer, int length) +{ + const int BYTES_PER_LINE = 16; + + message.reserve(message.size() + length*6); + if (!message.empty()) message.append("\n"); + unsigned char* base = (unsigned char*) buffer; + int addr = 0; + while (addr < length) + { + if (addr > 0) message.append("\n"); + message.append(NumberFormatter::formatHex(addr, 4)); + message.append(" "); + int offset = 0; + while (addr + offset < length && offset < BYTES_PER_LINE) + { + message.append(NumberFormatter::formatHex(base[addr + offset], 2)); + message.append(offset == 7 ? " " : " "); + ++offset; + } + if (offset < 7) message.append(" "); + while (offset < BYTES_PER_LINE) { message.append(" "); ++offset; } + message.append(" "); + offset = 0; + while (addr + offset < length && offset < BYTES_PER_LINE) + { + unsigned char c = base[addr + offset]; + message += (c >= 32 && c < 127) ? (char) c : '.'; + ++offset; + } + addr += BYTES_PER_LINE; + } +} + + +Logger& Logger::get(const std::string& name) +{ + Mutex::ScopedLock lock(_mapMtx); + + return unsafeGet(name); +} + + +Logger& Logger::unsafeGet(const std::string& name) +{ + Logger* pLogger = find(name); + if (!pLogger) + { + if (name == ROOT) + { + pLogger = new Logger(name, 0, Message::PRIO_INFORMATION); + } + else + { + Logger& par = parent(name); + pLogger = new Logger(name, par.getChannel(), par.getLevel()); + } + add(pLogger); + } + return *pLogger; +} + + +Logger& Logger::create(const std::string& name, Channel* pChannel, int level) +{ + Mutex::ScopedLock lock(_mapMtx); + + if (find(name)) throw ExistsException(); + Logger* pLogger = new Logger(name, pChannel, level); + add(pLogger); + return *pLogger; +} + + +Logger& Logger::root() +{ + Mutex::ScopedLock lock(_mapMtx); + + return unsafeGet(ROOT); +} + + +Logger* Logger::has(const std::string& name) +{ + Mutex::ScopedLock lock(_mapMtx); + + return find(name); +} + + +void Logger::shutdown() +{ + Mutex::ScopedLock lock(_mapMtx); + + if (_pLoggerMap) + { + for (LoggerMap::iterator it = _pLoggerMap->begin(); it != _pLoggerMap->end(); ++it) + { + it->second->release(); + } + delete _pLoggerMap; + _pLoggerMap = 0; + } +} + + +Logger* Logger::find(const std::string& name) +{ + if (_pLoggerMap) + { + LoggerMap::iterator it = _pLoggerMap->find(name); + if (it != _pLoggerMap->end()) + return it->second; + } + return 0; +} + + +void Logger::destroy(const std::string& name) +{ + Mutex::ScopedLock lock(_mapMtx); + + if (_pLoggerMap) + { + LoggerMap::iterator it = _pLoggerMap->find(name); + if (it != _pLoggerMap->end()) + { + it->second->release(); + _pLoggerMap->erase(it); + } + } +} + + +void Logger::names(std::vector& names) +{ + Mutex::ScopedLock lock(_mapMtx); + + names.clear(); + if (_pLoggerMap) + { + for (LoggerMap::const_iterator it = _pLoggerMap->begin(); it != _pLoggerMap->end(); ++it) + { + names.push_back(it->first); + } + } +} + + +Logger& Logger::parent(const std::string& name) +{ + std::string::size_type pos = name.rfind('.'); + if (pos != std::string::npos) + { + std::string pname = name.substr(0, pos); + Logger* pParent = find(pname); + if (pParent) + return *pParent; + else + return parent(pname); + } + else return unsafeGet(ROOT); +} + + +class AutoLoggerShutdown +{ +public: + AutoLoggerShutdown() + { + } + ~AutoLoggerShutdown() + { + Logger::shutdown(); + } +}; + + +void Logger::add(Logger* pLogger) +{ + static AutoLoggerShutdown als; + + if (!_pLoggerMap) + _pLoggerMap = new LoggerMap; + _pLoggerMap->insert(LoggerMap::value_type(pLogger->name(), pLogger)); +} + + +} // namespace Poco diff --git a/Foundation/src/LoggingFactory.cpp b/Foundation/src/LoggingFactory.cpp index d596a8c78..e36a19e93 100644 --- a/Foundation/src/LoggingFactory.cpp +++ b/Foundation/src/LoggingFactory.cpp @@ -1,125 +1,125 @@ -// -// LoggingFactory.cpp -// -// $Id: //poco/1.2/Foundation/src/LoggingFactory.cpp#1 $ -// -// Library: Foundation -// Package: Logging -// Module: LoggingFactory -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/LoggingFactory.h" -#include "Poco/SingletonHolder.h" -#include "Poco/AsyncChannel.h" -#include "Poco/ConsoleChannel.h" -#include "Poco/FileChannel.h" -#include "Poco/FormattingChannel.h" -#include "Poco/SplitterChannel.h" -#include "Poco/NullChannel.h" -#if defined(POCO_OS_FAMILY_UNIX) -#include "Poco/SyslogChannel.h" -#endif -#if defined(POCO_OS_FAMILY_VMS) -#include "Poco/OpcomChannel.h" -#endif -#if defined(POCO_OS_FAMILY_WINDOWS) -#include "Poco/EventLogChannel.h" -#endif -#include "Poco/PatternFormatter.h" - - -namespace Poco { - - -LoggingFactory::LoggingFactory() -{ - registerBuiltins(); -} - - -LoggingFactory::~LoggingFactory() -{ -} - - -void LoggingFactory::registerChannelClass(const std::string& className, ChannelInstantiator* pFactory) -{ - _channelFactory.registerClass(className, pFactory); -} - - -void LoggingFactory::registerFormatterClass(const std::string& className, FormatterFactory* pFactory) -{ - _formatterFactory.registerClass(className, pFactory); -} - - -Channel* LoggingFactory::createChannel(const std::string& className) const -{ - return _channelFactory.createInstance(className); -} - - -Formatter* LoggingFactory::createFormatter(const std::string& className) const -{ - return _formatterFactory.createInstance(className); -} - - -LoggingFactory& LoggingFactory::defaultFactory() -{ - static SingletonHolder sh; - return *sh.get(); -} - - -void LoggingFactory::registerBuiltins() -{ - _channelFactory.registerClass("AsyncChannel", new Instantiator); - _channelFactory.registerClass("ConsoleChannel", new Instantiator); - _channelFactory.registerClass("FileChannel", new Instantiator); - _channelFactory.registerClass("FormattingChannel", new Instantiator); - _channelFactory.registerClass("SplitterChannel", new Instantiator); - _channelFactory.registerClass("NullChannel", new Instantiator); - -#if defined(POCO_OS_FAMILY_UNIX) - _channelFactory.registerClass("SyslogChannel", new Instantiator); -#endif -#if defined(POCO_OS_FAMILY_VMS) - _channelFactory.registerClass("OpcomChannel", new Instantiator); -#endif -#if defined(POCO_OS_FAMILY_WINDOWS) - _channelFactory.registerClass("EventLogChannel", new Instantiator); -#endif - - _formatterFactory.registerClass("PatternFormatter", new Instantiator); -} - - -} // namespace Poco +// +// LoggingFactory.cpp +// +// $Id: //poco/1.2/Foundation/src/LoggingFactory.cpp#1 $ +// +// Library: Foundation +// Package: Logging +// Module: LoggingFactory +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/LoggingFactory.h" +#include "Poco/SingletonHolder.h" +#include "Poco/AsyncChannel.h" +#include "Poco/ConsoleChannel.h" +#include "Poco/FileChannel.h" +#include "Poco/FormattingChannel.h" +#include "Poco/SplitterChannel.h" +#include "Poco/NullChannel.h" +#if defined(POCO_OS_FAMILY_UNIX) +#include "Poco/SyslogChannel.h" +#endif +#if defined(POCO_OS_FAMILY_VMS) +#include "Poco/OpcomChannel.h" +#endif +#if defined(POCO_OS_FAMILY_WINDOWS) +#include "Poco/EventLogChannel.h" +#endif +#include "Poco/PatternFormatter.h" + + +namespace Poco { + + +LoggingFactory::LoggingFactory() +{ + registerBuiltins(); +} + + +LoggingFactory::~LoggingFactory() +{ +} + + +void LoggingFactory::registerChannelClass(const std::string& className, ChannelInstantiator* pFactory) +{ + _channelFactory.registerClass(className, pFactory); +} + + +void LoggingFactory::registerFormatterClass(const std::string& className, FormatterFactory* pFactory) +{ + _formatterFactory.registerClass(className, pFactory); +} + + +Channel* LoggingFactory::createChannel(const std::string& className) const +{ + return _channelFactory.createInstance(className); +} + + +Formatter* LoggingFactory::createFormatter(const std::string& className) const +{ + return _formatterFactory.createInstance(className); +} + + +LoggingFactory& LoggingFactory::defaultFactory() +{ + static SingletonHolder sh; + return *sh.get(); +} + + +void LoggingFactory::registerBuiltins() +{ + _channelFactory.registerClass("AsyncChannel", new Instantiator); + _channelFactory.registerClass("ConsoleChannel", new Instantiator); + _channelFactory.registerClass("FileChannel", new Instantiator); + _channelFactory.registerClass("FormattingChannel", new Instantiator); + _channelFactory.registerClass("SplitterChannel", new Instantiator); + _channelFactory.registerClass("NullChannel", new Instantiator); + +#if defined(POCO_OS_FAMILY_UNIX) + _channelFactory.registerClass("SyslogChannel", new Instantiator); +#endif +#if defined(POCO_OS_FAMILY_VMS) + _channelFactory.registerClass("OpcomChannel", new Instantiator); +#endif +#if defined(POCO_OS_FAMILY_WINDOWS) + _channelFactory.registerClass("EventLogChannel", new Instantiator); +#endif + + _formatterFactory.registerClass("PatternFormatter", new Instantiator); +} + + +} // namespace Poco diff --git a/Foundation/src/LoggingRegistry.cpp b/Foundation/src/LoggingRegistry.cpp index 814ab1059..ffa6a82b2 100644 --- a/Foundation/src/LoggingRegistry.cpp +++ b/Foundation/src/LoggingRegistry.cpp @@ -1,134 +1,134 @@ -// -// LoggingRegistry.cpp -// -// $Id: //poco/1.2/Foundation/src/LoggingRegistry.cpp#2 $ -// -// Library: Foundation -// Package: Logging -// Module: LoggingRegistry -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/LoggingRegistry.h" -#include "Poco/SingletonHolder.h" - - -namespace Poco { - - -LoggingRegistry::LoggingRegistry() -{ -} - - -LoggingRegistry::~LoggingRegistry() -{ -} - - -Channel* LoggingRegistry::channelForName(const std::string& name) const -{ - FastMutex::ScopedLock lock(_mutex); - - ChannelMap::const_iterator it = _channelMap.find(name); - if (it != _channelMap.end()) - return const_cast(it->second.get()); - else - throw NotFoundException("logging channel", name); -} - - -Formatter* LoggingRegistry::formatterForName(const std::string& name) const -{ - FastMutex::ScopedLock lock(_mutex); - - FormatterMap::const_iterator it = _formatterMap.find(name); - if (it != _formatterMap.end()) - return const_cast(it->second.get()); - else - throw NotFoundException("logging formatter", name); -} - - -void LoggingRegistry::registerChannel(const std::string& name, Channel* pChannel) -{ - FastMutex::ScopedLock lock(_mutex); - - _channelMap[name] = ChannelPtr(pChannel, true); -} - - -void LoggingRegistry::registerFormatter(const std::string& name, Formatter* pFormatter) -{ - FastMutex::ScopedLock lock(_mutex); - - _formatterMap[name] = FormatterPtr(pFormatter, true); -} - - -void LoggingRegistry::unregisterChannel(const std::string& name) -{ - FastMutex::ScopedLock lock(_mutex); - - ChannelMap::iterator it = _channelMap.find(name); - if (it != _channelMap.end()) - _channelMap.erase(it); - else - throw NotFoundException("logging channel", name); -} - - -void LoggingRegistry::unregisterFormatter(const std::string& name) -{ - FastMutex::ScopedLock lock(_mutex); - - FormatterMap::iterator it = _formatterMap.find(name); - if (it != _formatterMap.end()) - _formatterMap.erase(it); - else - throw NotFoundException("logging formatter", name); -} - - -void LoggingRegistry::clear() -{ - FastMutex::ScopedLock lock(_mutex); - - _channelMap.clear(); - _formatterMap.clear(); -} - - -LoggingRegistry& LoggingRegistry::defaultRegistry() -{ - static SingletonHolder sh; - return *sh.get(); -} - - -} // namespace Poco +// +// LoggingRegistry.cpp +// +// $Id: //poco/1.2/Foundation/src/LoggingRegistry.cpp#2 $ +// +// Library: Foundation +// Package: Logging +// Module: LoggingRegistry +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/LoggingRegistry.h" +#include "Poco/SingletonHolder.h" + + +namespace Poco { + + +LoggingRegistry::LoggingRegistry() +{ +} + + +LoggingRegistry::~LoggingRegistry() +{ +} + + +Channel* LoggingRegistry::channelForName(const std::string& name) const +{ + FastMutex::ScopedLock lock(_mutex); + + ChannelMap::const_iterator it = _channelMap.find(name); + if (it != _channelMap.end()) + return const_cast(it->second.get()); + else + throw NotFoundException("logging channel", name); +} + + +Formatter* LoggingRegistry::formatterForName(const std::string& name) const +{ + FastMutex::ScopedLock lock(_mutex); + + FormatterMap::const_iterator it = _formatterMap.find(name); + if (it != _formatterMap.end()) + return const_cast(it->second.get()); + else + throw NotFoundException("logging formatter", name); +} + + +void LoggingRegistry::registerChannel(const std::string& name, Channel* pChannel) +{ + FastMutex::ScopedLock lock(_mutex); + + _channelMap[name] = ChannelPtr(pChannel, true); +} + + +void LoggingRegistry::registerFormatter(const std::string& name, Formatter* pFormatter) +{ + FastMutex::ScopedLock lock(_mutex); + + _formatterMap[name] = FormatterPtr(pFormatter, true); +} + + +void LoggingRegistry::unregisterChannel(const std::string& name) +{ + FastMutex::ScopedLock lock(_mutex); + + ChannelMap::iterator it = _channelMap.find(name); + if (it != _channelMap.end()) + _channelMap.erase(it); + else + throw NotFoundException("logging channel", name); +} + + +void LoggingRegistry::unregisterFormatter(const std::string& name) +{ + FastMutex::ScopedLock lock(_mutex); + + FormatterMap::iterator it = _formatterMap.find(name); + if (it != _formatterMap.end()) + _formatterMap.erase(it); + else + throw NotFoundException("logging formatter", name); +} + + +void LoggingRegistry::clear() +{ + FastMutex::ScopedLock lock(_mutex); + + _channelMap.clear(); + _formatterMap.clear(); +} + + +LoggingRegistry& LoggingRegistry::defaultRegistry() +{ + static SingletonHolder sh; + return *sh.get(); +} + + +} // namespace Poco diff --git a/Foundation/src/MD2Engine.cpp b/Foundation/src/MD2Engine.cpp index 47e9364de..d26d37699 100644 --- a/Foundation/src/MD2Engine.cpp +++ b/Foundation/src/MD2Engine.cpp @@ -1,216 +1,216 @@ -// -// MD2Engine.cpp -// -// $Id: //poco/1.2/Foundation/src/MD2Engine.cpp#1 $ -// -// Library: Foundation -// Package: Crypt -// Module: MD2Engine -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// -// -// MD2 (RFC 1319) algorithm: -// Copyright (C) 1990-2, RSA Data Security, Inc. Created 1990. All -// rights reserved. -// -// License to copy and use this software is granted for -// non-commercial Internet Privacy-Enhanced Mail provided that it is -// identified as the "RSA Data Security, Inc. MD2 Message Digest -// Algorithm" in all material mentioning or referencing this software -// or this function. -// -// RSA Data Security, Inc. makes no representations concerning either -// the merchantability of this software or the suitability of this -// software for any particular purpose. It is provided "as is" -// without express or implied warranty of any kind. -// -// These notices must be retained in any copies of any part of this -// documentation and/or software. -// - - -#include "Poco/MD2Engine.h" -#include - - -namespace Poco { - - -MD2Engine::MD2Engine() -{ - _digest.reserve(16); - reset(); -} - - -MD2Engine::~MD2Engine() -{ - reset(); -} - - -void MD2Engine::updateImpl(const void* input_, unsigned inputLen) -{ - const unsigned char* input = (const unsigned char*) input_; - unsigned int i, index, partLen; - - /* Update number of bytes mod 16 */ - index = _context.count; - _context.count = (index + inputLen) & 0xf; - - partLen = 16 - index; - - /* Transform as many times as possible. */ - if (inputLen >= partLen) - { - memcpy(&_context.buffer[index], input, partLen); - transform(_context.state, _context.checksum, _context.buffer); - - for (i = partLen; i + 15 < inputLen; i += 16) - transform(_context.state, _context.checksum, &input[i]); - - index = 0; - } - else i = 0; - - /* Buffer remaining input */ - memcpy(&_context.buffer[index], &input[i], inputLen-i); -} - - -unsigned MD2Engine::digestLength() const -{ - return DIGEST_SIZE; -} - - -void MD2Engine::reset() -{ - memset(&_context, 0, sizeof(_context)); -} - - -const DigestEngine::Digest& MD2Engine::digest() -{ - static const unsigned char* PADDING[] = - { - (unsigned char*) "", - (unsigned char*) "\001", - (unsigned char*) "\002\002", - (unsigned char*) "\003\003\003", - (unsigned char*) "\004\004\004\004", - (unsigned char*) "\005\005\005\005\005", - (unsigned char*) "\006\006\006\006\006\006", - (unsigned char*) "\007\007\007\007\007\007\007", - (unsigned char*) "\010\010\010\010\010\010\010\010", - (unsigned char*) "\011\011\011\011\011\011\011\011\011", - (unsigned char*) "\012\012\012\012\012\012\012\012\012\012", - (unsigned char*) "\013\013\013\013\013\013\013\013\013\013\013", - (unsigned char*) "\014\014\014\014\014\014\014\014\014\014\014\014", - (unsigned char*) "\015\015\015\015\015\015\015\015\015\015\015\015\015", - (unsigned char *) "\016\016\016\016\016\016\016\016\016\016\016\016\016\016", - (unsigned char *) "\017\017\017\017\017\017\017\017\017\017\017\017\017\017\017", - (unsigned char *) "\020\020\020\020\020\020\020\020\020\020\020\020\020\020\020\020" - }; - unsigned int index, padLen; - - /* Pad out to multiple of 16. */ - index = _context.count; - padLen = 16 - index; - update((const char*) PADDING[padLen], padLen); - - /* Extend with checksum */ - update((const char*) _context.checksum, 16); - - /* Store state in digest */ - _digest.clear(); - _digest.insert(_digest.begin(), _context.state, _context.state + 16); - - /* Zeroize sensitive information. */ - memset(&_context, 0, sizeof(_context)); - reset(); - return _digest; -} - - -void MD2Engine::transform(unsigned char state[16], unsigned char checksum[16], const unsigned char block[16]) -{ - // Permutation of 0..255 constructed from the digits of pi. It gives a - // "random" nonlinear byte substitution operation. - static const unsigned char PI_SUBST[256] = - { - 41, 46, 67, 201, 162, 216, 124, 1, 61, 54, 84, 161, 236, 240, 6, - 19, 98, 167, 5, 243, 192, 199, 115, 140, 152, 147, 43, 217, 188, - 76, 130, 202, 30, 155, 87, 60, 253, 212, 224, 22, 103, 66, 111, 24, - 138, 23, 229, 18, 190, 78, 196, 214, 218, 158, 222, 73, 160, 251, - 245, 142, 187, 47, 238, 122, 169, 104, 121, 145, 21, 178, 7, 63, - 148, 194, 16, 137, 11, 34, 95, 33, 128, 127, 93, 154, 90, 144, 50, - 39, 53, 62, 204, 231, 191, 247, 151, 3, 255, 25, 48, 179, 72, 165, - 181, 209, 215, 94, 146, 42, 172, 86, 170, 198, 79, 184, 56, 210, - 150, 164, 125, 182, 118, 252, 107, 226, 156, 116, 4, 241, 69, 157, - 112, 89, 100, 113, 135, 32, 134, 91, 207, 101, 230, 45, 168, 2, 27, - 96, 37, 173, 174, 176, 185, 246, 28, 70, 97, 105, 52, 64, 126, 15, - 85, 71, 163, 35, 221, 81, 175, 58, 195, 92, 249, 206, 186, 197, - 234, 38, 44, 83, 13, 110, 133, 40, 132, 9, 211, 223, 205, 244, 65, - 129, 77, 82, 106, 220, 55, 200, 108, 193, 171, 250, 36, 225, 123, - 8, 12, 189, 177, 74, 120, 136, 149, 139, 227, 99, 232, 109, 233, - 203, 213, 254, 59, 0, 29, 57, 242, 239, 183, 14, 102, 88, 208, 228, - 166, 119, 114, 248, 235, 117, 75, 10, 49, 68, 80, 180, 143, 237, - 31, 26, 219, 153, 141, 51, 159, 17, 131, 20 - }; - unsigned int i, j, t; - unsigned char x[48]; - - /* Form encryption block from state, block, state ^ block. */ - memcpy(x, state, 16); - memcpy(x+16, block, 16); - for (i = 0; i < 16; i++) - x[i+32] = state[i] ^ block[i]; - - /* Encrypt block (18 rounds). */ - t = 0; - for (i = 0; i < 18; i++) - { - for (j = 0; j < 48; j++) - t = x[j] ^= PI_SUBST[t]; - t = (t + i) & 0xff; - } - - /* Save new state */ - memcpy(state, x, 16); - - /* Update checksum. */ - t = checksum[15]; - for (i = 0; i < 16; i++) - t = checksum[i] ^= PI_SUBST[block[i] ^ t]; - - /* Zeroize sensitive information. */ - memset(x, 0, sizeof(x)); -} - - -} // namespace Poco +// +// MD2Engine.cpp +// +// $Id: //poco/1.2/Foundation/src/MD2Engine.cpp#1 $ +// +// Library: Foundation +// Package: Crypt +// Module: MD2Engine +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// +// +// MD2 (RFC 1319) algorithm: +// Copyright (C) 1990-2, RSA Data Security, Inc. Created 1990. All +// rights reserved. +// +// License to copy and use this software is granted for +// non-commercial Internet Privacy-Enhanced Mail provided that it is +// identified as the "RSA Data Security, Inc. MD2 Message Digest +// Algorithm" in all material mentioning or referencing this software +// or this function. +// +// RSA Data Security, Inc. makes no representations concerning either +// the merchantability of this software or the suitability of this +// software for any particular purpose. It is provided "as is" +// without express or implied warranty of any kind. +// +// These notices must be retained in any copies of any part of this +// documentation and/or software. +// + + +#include "Poco/MD2Engine.h" +#include + + +namespace Poco { + + +MD2Engine::MD2Engine() +{ + _digest.reserve(16); + reset(); +} + + +MD2Engine::~MD2Engine() +{ + reset(); +} + + +void MD2Engine::updateImpl(const void* input_, unsigned inputLen) +{ + const unsigned char* input = (const unsigned char*) input_; + unsigned int i, index, partLen; + + /* Update number of bytes mod 16 */ + index = _context.count; + _context.count = (index + inputLen) & 0xf; + + partLen = 16 - index; + + /* Transform as many times as possible. */ + if (inputLen >= partLen) + { + memcpy(&_context.buffer[index], input, partLen); + transform(_context.state, _context.checksum, _context.buffer); + + for (i = partLen; i + 15 < inputLen; i += 16) + transform(_context.state, _context.checksum, &input[i]); + + index = 0; + } + else i = 0; + + /* Buffer remaining input */ + memcpy(&_context.buffer[index], &input[i], inputLen-i); +} + + +unsigned MD2Engine::digestLength() const +{ + return DIGEST_SIZE; +} + + +void MD2Engine::reset() +{ + memset(&_context, 0, sizeof(_context)); +} + + +const DigestEngine::Digest& MD2Engine::digest() +{ + static const unsigned char* PADDING[] = + { + (unsigned char*) "", + (unsigned char*) "\001", + (unsigned char*) "\002\002", + (unsigned char*) "\003\003\003", + (unsigned char*) "\004\004\004\004", + (unsigned char*) "\005\005\005\005\005", + (unsigned char*) "\006\006\006\006\006\006", + (unsigned char*) "\007\007\007\007\007\007\007", + (unsigned char*) "\010\010\010\010\010\010\010\010", + (unsigned char*) "\011\011\011\011\011\011\011\011\011", + (unsigned char*) "\012\012\012\012\012\012\012\012\012\012", + (unsigned char*) "\013\013\013\013\013\013\013\013\013\013\013", + (unsigned char*) "\014\014\014\014\014\014\014\014\014\014\014\014", + (unsigned char*) "\015\015\015\015\015\015\015\015\015\015\015\015\015", + (unsigned char *) "\016\016\016\016\016\016\016\016\016\016\016\016\016\016", + (unsigned char *) "\017\017\017\017\017\017\017\017\017\017\017\017\017\017\017", + (unsigned char *) "\020\020\020\020\020\020\020\020\020\020\020\020\020\020\020\020" + }; + unsigned int index, padLen; + + /* Pad out to multiple of 16. */ + index = _context.count; + padLen = 16 - index; + update((const char*) PADDING[padLen], padLen); + + /* Extend with checksum */ + update((const char*) _context.checksum, 16); + + /* Store state in digest */ + _digest.clear(); + _digest.insert(_digest.begin(), _context.state, _context.state + 16); + + /* Zeroize sensitive information. */ + memset(&_context, 0, sizeof(_context)); + reset(); + return _digest; +} + + +void MD2Engine::transform(unsigned char state[16], unsigned char checksum[16], const unsigned char block[16]) +{ + // Permutation of 0..255 constructed from the digits of pi. It gives a + // "random" nonlinear byte substitution operation. + static const unsigned char PI_SUBST[256] = + { + 41, 46, 67, 201, 162, 216, 124, 1, 61, 54, 84, 161, 236, 240, 6, + 19, 98, 167, 5, 243, 192, 199, 115, 140, 152, 147, 43, 217, 188, + 76, 130, 202, 30, 155, 87, 60, 253, 212, 224, 22, 103, 66, 111, 24, + 138, 23, 229, 18, 190, 78, 196, 214, 218, 158, 222, 73, 160, 251, + 245, 142, 187, 47, 238, 122, 169, 104, 121, 145, 21, 178, 7, 63, + 148, 194, 16, 137, 11, 34, 95, 33, 128, 127, 93, 154, 90, 144, 50, + 39, 53, 62, 204, 231, 191, 247, 151, 3, 255, 25, 48, 179, 72, 165, + 181, 209, 215, 94, 146, 42, 172, 86, 170, 198, 79, 184, 56, 210, + 150, 164, 125, 182, 118, 252, 107, 226, 156, 116, 4, 241, 69, 157, + 112, 89, 100, 113, 135, 32, 134, 91, 207, 101, 230, 45, 168, 2, 27, + 96, 37, 173, 174, 176, 185, 246, 28, 70, 97, 105, 52, 64, 126, 15, + 85, 71, 163, 35, 221, 81, 175, 58, 195, 92, 249, 206, 186, 197, + 234, 38, 44, 83, 13, 110, 133, 40, 132, 9, 211, 223, 205, 244, 65, + 129, 77, 82, 106, 220, 55, 200, 108, 193, 171, 250, 36, 225, 123, + 8, 12, 189, 177, 74, 120, 136, 149, 139, 227, 99, 232, 109, 233, + 203, 213, 254, 59, 0, 29, 57, 242, 239, 183, 14, 102, 88, 208, 228, + 166, 119, 114, 248, 235, 117, 75, 10, 49, 68, 80, 180, 143, 237, + 31, 26, 219, 153, 141, 51, 159, 17, 131, 20 + }; + unsigned int i, j, t; + unsigned char x[48]; + + /* Form encryption block from state, block, state ^ block. */ + memcpy(x, state, 16); + memcpy(x+16, block, 16); + for (i = 0; i < 16; i++) + x[i+32] = state[i] ^ block[i]; + + /* Encrypt block (18 rounds). */ + t = 0; + for (i = 0; i < 18; i++) + { + for (j = 0; j < 48; j++) + t = x[j] ^= PI_SUBST[t]; + t = (t + i) & 0xff; + } + + /* Save new state */ + memcpy(state, x, 16); + + /* Update checksum. */ + t = checksum[15]; + for (i = 0; i < 16; i++) + t = checksum[i] ^= PI_SUBST[block[i] ^ t]; + + /* Zeroize sensitive information. */ + memset(x, 0, sizeof(x)); +} + + +} // namespace Poco diff --git a/Foundation/src/MD4Engine.cpp b/Foundation/src/MD4Engine.cpp index 40e765f29..7e8866317 100644 --- a/Foundation/src/MD4Engine.cpp +++ b/Foundation/src/MD4Engine.cpp @@ -1,300 +1,300 @@ -// -// MD4Engine.cpp -// -// $Id: //poco/1.2/Foundation/src/MD4Engine.cpp#1 $ -// -// Library: Foundation -// Package: Crypt -// Module: MD4Engine -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// -// -// MD4 (RFC 1320) algorithm: -// Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All -// rights reserved. -// -// License to copy and use this software is granted provided that it -// is identified as the "RSA Data Security, Inc. MD4 Message-Digest -// Algorithm" in all material mentioning or referencing this software -// or this function. -// -// License is also granted to make and use derivative works provided -// that such works are identified as "derived from the RSA Data -// Security, Inc. MD4 Message-Digest Algorithm" in all material -// mentioning or referencing the derived work. -// -// RSA Data Security, Inc. makes no representations concerning either -// the merchantability of this software or the suitability of this -// software for any particular purpose. It is provided "as is" -// without express or implied warranty of any kind. -// -// These notices must be retained in any copies of any part of this -// documentation and/or software. -// - - -#include "Poco/MD4Engine.h" -#include - - -namespace Poco { - - -MD4Engine::MD4Engine() -{ - _digest.reserve(16); - reset(); -} - - -MD4Engine::~MD4Engine() -{ - reset(); -} - - -void MD4Engine::updateImpl(const void* input_, unsigned inputLen) -{ - const unsigned char* input = (const unsigned char*) input_; - unsigned int i, index, partLen; - - /* Compute number of bytes mod 64 */ - index = (unsigned int)((_context.count[0] >> 3) & 0x3F); - - /* Update number of bits */ - if ((_context.count[0] += ((UInt32) inputLen << 3)) < ((UInt32) inputLen << 3)) - _context.count[1]++; - _context.count[1] += ((UInt32) inputLen >> 29); - - partLen = 64 - index; - - /* Transform as many times as possible. */ - if (inputLen >= partLen) - { - memcpy(&_context.buffer[index], input, partLen); - transform(_context.state, _context.buffer); - - for (i = partLen; i + 63 < inputLen; i += 64) - transform(_context.state, &input[i]); - - index = 0; - } - else i = 0; - - /* Buffer remaining input */ - memcpy(&_context.buffer[index], &input[i], inputLen-i); -} - - -unsigned MD4Engine::digestLength() const -{ - return DIGEST_SIZE; -} - - -void MD4Engine::reset() -{ - memset(&_context, 0, sizeof(_context)); - _context.count[0] = _context.count[1] = 0; - _context.state[0] = 0x67452301; - _context.state[1] = 0xefcdab89; - _context.state[2] = 0x98badcfe; - _context.state[3] = 0x10325476; -} - - -const DigestEngine::Digest& MD4Engine::digest() -{ - static const unsigned char PADDING[64] = - { - 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 - }; - unsigned char bits[8]; - unsigned int index, padLen; - - /* Save number of bits */ - encode(bits, _context.count, 8); - - /* Pad out to 56 mod 64. */ - index = (unsigned int)((_context.count[0] >> 3) & 0x3f); - padLen = (index < 56) ? (56 - index) : (120 - index); - update(PADDING, padLen); - - /* Append length (before padding) */ - update(bits, 8); - - /* Store state in digest */ - unsigned char digest[16]; - encode(digest, _context.state, 16); - _digest.clear(); - _digest.insert(_digest.begin(), digest, digest + sizeof(digest)); - - /* Zeroize sensitive information. */ - memset(&_context, 0, sizeof (_context)); - reset(); - return _digest; -} - - -/* Constants for MD4Transform routine. */ -#define S11 3 -#define S12 7 -#define S13 11 -#define S14 19 -#define S21 3 -#define S22 5 -#define S23 9 -#define S24 13 -#define S31 3 -#define S32 9 -#define S33 11 -#define S34 15 - - -/* F, G and H are basic MD4 functions. */ -#define F(x, y, z) (((x) & (y)) | ((~x) & (z))) -#define G(x, y, z) (((x) & (y)) | ((x) & (z)) | ((y) & (z))) -#define H(x, y, z) ((x) ^ (y) ^ (z)) - - -/* ROTATE_LEFT rotates x left n bits. */ -#define ROTATE_LEFT(x, n) (((x) << (n)) | ((x) >> (32-(n)))) - - -/* FF, GG and HH are transformations for rounds 1, 2 and 3 */ -/* Rotation is separate from addition to prevent recomputation */ -#define FF(a, b, c, d, x, s) { \ - (a) += F ((b), (c), (d)) + (x); \ - (a) = ROTATE_LEFT ((a), (s)); \ - } -#define GG(a, b, c, d, x, s) { \ - (a) += G ((b), (c), (d)) + (x) + (UInt32)0x5a827999; \ - (a) = ROTATE_LEFT ((a), (s)); \ - } -#define HH(a, b, c, d, x, s) { \ - (a) += H ((b), (c), (d)) + (x) + (UInt32)0x6ed9eba1; \ - (a) = ROTATE_LEFT ((a), (s)); \ - } - - -void MD4Engine::transform (UInt32 state[4], const unsigned char block[64]) -{ - UInt32 a = state[0], b = state[1], c = state[2], d = state[3], x[16]; - - decode(x, block, 64); - - /* Round 1 */ - FF (a, b, c, d, x[ 0], S11); /* 1 */ - FF (d, a, b, c, x[ 1], S12); /* 2 */ - FF (c, d, a, b, x[ 2], S13); /* 3 */ - FF (b, c, d, a, x[ 3], S14); /* 4 */ - FF (a, b, c, d, x[ 4], S11); /* 5 */ - FF (d, a, b, c, x[ 5], S12); /* 6 */ - FF (c, d, a, b, x[ 6], S13); /* 7 */ - FF (b, c, d, a, x[ 7], S14); /* 8 */ - FF (a, b, c, d, x[ 8], S11); /* 9 */ - FF (d, a, b, c, x[ 9], S12); /* 10 */ - FF (c, d, a, b, x[10], S13); /* 11 */ - FF (b, c, d, a, x[11], S14); /* 12 */ - FF (a, b, c, d, x[12], S11); /* 13 */ - FF (d, a, b, c, x[13], S12); /* 14 */ - FF (c, d, a, b, x[14], S13); /* 15 */ - FF (b, c, d, a, x[15], S14); /* 16 */ - - /* Round 2 */ - GG (a, b, c, d, x[ 0], S21); /* 17 */ - GG (d, a, b, c, x[ 4], S22); /* 18 */ - GG (c, d, a, b, x[ 8], S23); /* 19 */ - GG (b, c, d, a, x[12], S24); /* 20 */ - GG (a, b, c, d, x[ 1], S21); /* 21 */ - GG (d, a, b, c, x[ 5], S22); /* 22 */ - GG (c, d, a, b, x[ 9], S23); /* 23 */ - GG (b, c, d, a, x[13], S24); /* 24 */ - GG (a, b, c, d, x[ 2], S21); /* 25 */ - GG (d, a, b, c, x[ 6], S22); /* 26 */ - GG (c, d, a, b, x[10], S23); /* 27 */ - GG (b, c, d, a, x[14], S24); /* 28 */ - GG (a, b, c, d, x[ 3], S21); /* 29 */ - GG (d, a, b, c, x[ 7], S22); /* 30 */ - GG (c, d, a, b, x[11], S23); /* 31 */ - GG (b, c, d, a, x[15], S24); /* 32 */ - - /* Round 3 */ - HH (a, b, c, d, x[ 0], S31); /* 33 */ - HH (d, a, b, c, x[ 8], S32); /* 34 */ - HH (c, d, a, b, x[ 4], S33); /* 35 */ - HH (b, c, d, a, x[12], S34); /* 36 */ - HH (a, b, c, d, x[ 2], S31); /* 37 */ - HH (d, a, b, c, x[10], S32); /* 38 */ - HH (c, d, a, b, x[ 6], S33); /* 39 */ - HH (b, c, d, a, x[14], S34); /* 40 */ - HH (a, b, c, d, x[ 1], S31); /* 41 */ - HH (d, a, b, c, x[ 9], S32); /* 42 */ - HH (c, d, a, b, x[ 5], S33); /* 43 */ - HH (b, c, d, a, x[13], S34); /* 44 */ - HH (a, b, c, d, x[ 3], S31); /* 45 */ - HH (d, a, b, c, x[11], S32); /* 46 */ - HH (c, d, a, b, x[ 7], S33); /* 47 */ - HH (b, c, d, a, x[15], S34); /* 48 */ - - state[0] += a; - state[1] += b; - state[2] += c; - state[3] += d; - - /* Zeroize sensitive information. */ - memset(x, 0, sizeof(x)); -} - - -void MD4Engine::encode(unsigned char* output, const UInt32* input, unsigned int len) -{ - unsigned int i, j; - - for (i = 0, j = 0; j < len; i++, j += 4) - { - output[j] = (unsigned char)(input[i] & 0xff); - output[j+1] = (unsigned char)((input[i] >> 8) & 0xff); - output[j+2] = (unsigned char)((input[i] >> 16) & 0xff); - output[j+3] = (unsigned char)((input[i] >> 24) & 0xff); - } -} - - -void MD4Engine::decode(UInt32* output, const unsigned char* input, unsigned int len) -{ - unsigned int i, j; - - for (i = 0, j = 0; j < len; i++, j += 4) - output[i] = ((UInt32)input[j]) | (((UInt32)input[j+1]) << 8) | - (((UInt32)input[j+2]) << 16) | (((UInt32)input[j+3]) << 24); -} - - -} // namespace Poco +// +// MD4Engine.cpp +// +// $Id: //poco/1.2/Foundation/src/MD4Engine.cpp#1 $ +// +// Library: Foundation +// Package: Crypt +// Module: MD4Engine +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// +// +// MD4 (RFC 1320) algorithm: +// Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All +// rights reserved. +// +// License to copy and use this software is granted provided that it +// is identified as the "RSA Data Security, Inc. MD4 Message-Digest +// Algorithm" in all material mentioning or referencing this software +// or this function. +// +// License is also granted to make and use derivative works provided +// that such works are identified as "derived from the RSA Data +// Security, Inc. MD4 Message-Digest Algorithm" in all material +// mentioning or referencing the derived work. +// +// RSA Data Security, Inc. makes no representations concerning either +// the merchantability of this software or the suitability of this +// software for any particular purpose. It is provided "as is" +// without express or implied warranty of any kind. +// +// These notices must be retained in any copies of any part of this +// documentation and/or software. +// + + +#include "Poco/MD4Engine.h" +#include + + +namespace Poco { + + +MD4Engine::MD4Engine() +{ + _digest.reserve(16); + reset(); +} + + +MD4Engine::~MD4Engine() +{ + reset(); +} + + +void MD4Engine::updateImpl(const void* input_, unsigned inputLen) +{ + const unsigned char* input = (const unsigned char*) input_; + unsigned int i, index, partLen; + + /* Compute number of bytes mod 64 */ + index = (unsigned int)((_context.count[0] >> 3) & 0x3F); + + /* Update number of bits */ + if ((_context.count[0] += ((UInt32) inputLen << 3)) < ((UInt32) inputLen << 3)) + _context.count[1]++; + _context.count[1] += ((UInt32) inputLen >> 29); + + partLen = 64 - index; + + /* Transform as many times as possible. */ + if (inputLen >= partLen) + { + memcpy(&_context.buffer[index], input, partLen); + transform(_context.state, _context.buffer); + + for (i = partLen; i + 63 < inputLen; i += 64) + transform(_context.state, &input[i]); + + index = 0; + } + else i = 0; + + /* Buffer remaining input */ + memcpy(&_context.buffer[index], &input[i], inputLen-i); +} + + +unsigned MD4Engine::digestLength() const +{ + return DIGEST_SIZE; +} + + +void MD4Engine::reset() +{ + memset(&_context, 0, sizeof(_context)); + _context.count[0] = _context.count[1] = 0; + _context.state[0] = 0x67452301; + _context.state[1] = 0xefcdab89; + _context.state[2] = 0x98badcfe; + _context.state[3] = 0x10325476; +} + + +const DigestEngine::Digest& MD4Engine::digest() +{ + static const unsigned char PADDING[64] = + { + 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 + }; + unsigned char bits[8]; + unsigned int index, padLen; + + /* Save number of bits */ + encode(bits, _context.count, 8); + + /* Pad out to 56 mod 64. */ + index = (unsigned int)((_context.count[0] >> 3) & 0x3f); + padLen = (index < 56) ? (56 - index) : (120 - index); + update(PADDING, padLen); + + /* Append length (before padding) */ + update(bits, 8); + + /* Store state in digest */ + unsigned char digest[16]; + encode(digest, _context.state, 16); + _digest.clear(); + _digest.insert(_digest.begin(), digest, digest + sizeof(digest)); + + /* Zeroize sensitive information. */ + memset(&_context, 0, sizeof (_context)); + reset(); + return _digest; +} + + +/* Constants for MD4Transform routine. */ +#define S11 3 +#define S12 7 +#define S13 11 +#define S14 19 +#define S21 3 +#define S22 5 +#define S23 9 +#define S24 13 +#define S31 3 +#define S32 9 +#define S33 11 +#define S34 15 + + +/* F, G and H are basic MD4 functions. */ +#define F(x, y, z) (((x) & (y)) | ((~x) & (z))) +#define G(x, y, z) (((x) & (y)) | ((x) & (z)) | ((y) & (z))) +#define H(x, y, z) ((x) ^ (y) ^ (z)) + + +/* ROTATE_LEFT rotates x left n bits. */ +#define ROTATE_LEFT(x, n) (((x) << (n)) | ((x) >> (32-(n)))) + + +/* FF, GG and HH are transformations for rounds 1, 2 and 3 */ +/* Rotation is separate from addition to prevent recomputation */ +#define FF(a, b, c, d, x, s) { \ + (a) += F ((b), (c), (d)) + (x); \ + (a) = ROTATE_LEFT ((a), (s)); \ + } +#define GG(a, b, c, d, x, s) { \ + (a) += G ((b), (c), (d)) + (x) + (UInt32)0x5a827999; \ + (a) = ROTATE_LEFT ((a), (s)); \ + } +#define HH(a, b, c, d, x, s) { \ + (a) += H ((b), (c), (d)) + (x) + (UInt32)0x6ed9eba1; \ + (a) = ROTATE_LEFT ((a), (s)); \ + } + + +void MD4Engine::transform (UInt32 state[4], const unsigned char block[64]) +{ + UInt32 a = state[0], b = state[1], c = state[2], d = state[3], x[16]; + + decode(x, block, 64); + + /* Round 1 */ + FF (a, b, c, d, x[ 0], S11); /* 1 */ + FF (d, a, b, c, x[ 1], S12); /* 2 */ + FF (c, d, a, b, x[ 2], S13); /* 3 */ + FF (b, c, d, a, x[ 3], S14); /* 4 */ + FF (a, b, c, d, x[ 4], S11); /* 5 */ + FF (d, a, b, c, x[ 5], S12); /* 6 */ + FF (c, d, a, b, x[ 6], S13); /* 7 */ + FF (b, c, d, a, x[ 7], S14); /* 8 */ + FF (a, b, c, d, x[ 8], S11); /* 9 */ + FF (d, a, b, c, x[ 9], S12); /* 10 */ + FF (c, d, a, b, x[10], S13); /* 11 */ + FF (b, c, d, a, x[11], S14); /* 12 */ + FF (a, b, c, d, x[12], S11); /* 13 */ + FF (d, a, b, c, x[13], S12); /* 14 */ + FF (c, d, a, b, x[14], S13); /* 15 */ + FF (b, c, d, a, x[15], S14); /* 16 */ + + /* Round 2 */ + GG (a, b, c, d, x[ 0], S21); /* 17 */ + GG (d, a, b, c, x[ 4], S22); /* 18 */ + GG (c, d, a, b, x[ 8], S23); /* 19 */ + GG (b, c, d, a, x[12], S24); /* 20 */ + GG (a, b, c, d, x[ 1], S21); /* 21 */ + GG (d, a, b, c, x[ 5], S22); /* 22 */ + GG (c, d, a, b, x[ 9], S23); /* 23 */ + GG (b, c, d, a, x[13], S24); /* 24 */ + GG (a, b, c, d, x[ 2], S21); /* 25 */ + GG (d, a, b, c, x[ 6], S22); /* 26 */ + GG (c, d, a, b, x[10], S23); /* 27 */ + GG (b, c, d, a, x[14], S24); /* 28 */ + GG (a, b, c, d, x[ 3], S21); /* 29 */ + GG (d, a, b, c, x[ 7], S22); /* 30 */ + GG (c, d, a, b, x[11], S23); /* 31 */ + GG (b, c, d, a, x[15], S24); /* 32 */ + + /* Round 3 */ + HH (a, b, c, d, x[ 0], S31); /* 33 */ + HH (d, a, b, c, x[ 8], S32); /* 34 */ + HH (c, d, a, b, x[ 4], S33); /* 35 */ + HH (b, c, d, a, x[12], S34); /* 36 */ + HH (a, b, c, d, x[ 2], S31); /* 37 */ + HH (d, a, b, c, x[10], S32); /* 38 */ + HH (c, d, a, b, x[ 6], S33); /* 39 */ + HH (b, c, d, a, x[14], S34); /* 40 */ + HH (a, b, c, d, x[ 1], S31); /* 41 */ + HH (d, a, b, c, x[ 9], S32); /* 42 */ + HH (c, d, a, b, x[ 5], S33); /* 43 */ + HH (b, c, d, a, x[13], S34); /* 44 */ + HH (a, b, c, d, x[ 3], S31); /* 45 */ + HH (d, a, b, c, x[11], S32); /* 46 */ + HH (c, d, a, b, x[ 7], S33); /* 47 */ + HH (b, c, d, a, x[15], S34); /* 48 */ + + state[0] += a; + state[1] += b; + state[2] += c; + state[3] += d; + + /* Zeroize sensitive information. */ + memset(x, 0, sizeof(x)); +} + + +void MD4Engine::encode(unsigned char* output, const UInt32* input, unsigned int len) +{ + unsigned int i, j; + + for (i = 0, j = 0; j < len; i++, j += 4) + { + output[j] = (unsigned char)(input[i] & 0xff); + output[j+1] = (unsigned char)((input[i] >> 8) & 0xff); + output[j+2] = (unsigned char)((input[i] >> 16) & 0xff); + output[j+3] = (unsigned char)((input[i] >> 24) & 0xff); + } +} + + +void MD4Engine::decode(UInt32* output, const unsigned char* input, unsigned int len) +{ + unsigned int i, j; + + for (i = 0, j = 0; j < len; i++, j += 4) + output[i] = ((UInt32)input[j]) | (((UInt32)input[j+1]) << 8) | + (((UInt32)input[j+2]) << 16) | (((UInt32)input[j+3]) << 24); +} + + +} // namespace Poco diff --git a/Foundation/src/MD5Engine.cpp b/Foundation/src/MD5Engine.cpp index db5d552b3..a6b6b198d 100644 --- a/Foundation/src/MD5Engine.cpp +++ b/Foundation/src/MD5Engine.cpp @@ -1,331 +1,331 @@ -// -// MD5Engine.cpp -// -// $Id: //poco/1.2/Foundation/src/MD5Engine.cpp#1 $ -// -// Library: Foundation -// Package: Crypt -// Module: MD5Engine -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// -// -// MD5 (RFC 1321) algorithm: -// Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All -// rights reserved. -// -// License to copy and use this software is granted provided that it -// is identified as the "RSA Data Security, Inc. MD5 Message-Digest -// Algorithm" in all material mentioning or referencing this software -// or this function. -// -// License is also granted to make and use derivative works provided -// that such works are identified as "derived from the RSA Data -// Security, Inc. MD5 Message-Digest Algorithm" in all material -// mentioning or referencing the derived work. -// -// RSA Data Security, Inc. makes no representations concerning either -// the merchantability of this software or the suitability of this -// software for any particular purpose. It is provided "as is" -// without express or implied warranty of any kind. -// -// These notices must be retained in any copies of any part of this -// documentation and/or software. -// - - -#include "Poco/MD5Engine.h" -#include - - -namespace Poco { - - -MD5Engine::MD5Engine() -{ - _digest.reserve(16); - reset(); -} - - -MD5Engine::~MD5Engine() -{ - reset(); -} - - -void MD5Engine::updateImpl(const void* input_, unsigned inputLen) -{ - const unsigned char* input = (const unsigned char*) input_; - unsigned int i, index, partLen; - - /* Compute number of bytes mod 64 */ - index = (unsigned int)((_context.count[0] >> 3) & 0x3F); - - /* Update number of bits */ - if ((_context.count[0] += ((UInt32) inputLen << 3)) < ((UInt32) inputLen << 3)) - _context.count[1]++; - _context.count[1] += ((UInt32) inputLen >> 29); - - partLen = 64 - index; - - /* Transform as many times as possible. */ - if (inputLen >= partLen) - { - memcpy(&_context.buffer[index], input, partLen); - transform(_context.state, _context.buffer); - - for (i = partLen; i + 63 < inputLen; i += 64) - transform(_context.state, &input[i]); - - index = 0; - } - else i = 0; - - /* Buffer remaining input */ - memcpy(&_context.buffer[index], &input[i],inputLen-i); -} - - -unsigned MD5Engine::digestLength() const -{ - return DIGEST_SIZE; -} - - -void MD5Engine::reset() -{ - memset(&_context, 0, sizeof(_context)); - _context.count[0] = _context.count[1] = 0; - _context.state[0] = 0x67452301; - _context.state[1] = 0xefcdab89; - _context.state[2] = 0x98badcfe; - _context.state[3] = 0x10325476; -} - - -const DigestEngine::Digest& MD5Engine::digest() -{ - static const unsigned char PADDING[64] = - { - 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 - }; - unsigned char bits[8]; - unsigned int index, padLen; - - /* Save number of bits */ - encode(bits, _context.count, 8); - - /* Pad out to 56 mod 64. */ - index = (unsigned int)((_context.count[0] >> 3) & 0x3f); - padLen = (index < 56) ? (56 - index) : (120 - index); - update(PADDING, padLen); - - /* Append length (before padding) */ - update(bits, 8); - - /* Store state in digest */ - unsigned char digest[16]; - encode(digest, _context.state, 16); - _digest.clear(); - _digest.insert(_digest.begin(), digest, digest + sizeof(digest)); - - /* Zeroize sensitive information. */ - memset(&_context, 0, sizeof (_context)); - reset(); - return _digest; -} - - -/* Constants for MD5Transform routine. */ -#define S11 7 -#define S12 12 -#define S13 17 -#define S14 22 -#define S21 5 -#define S22 9 -#define S23 14 -#define S24 20 -#define S31 4 -#define S32 11 -#define S33 16 -#define S34 23 -#define S41 6 -#define S42 10 -#define S43 15 -#define S44 21 - - -/* F, G, H and I are basic MD5 functions. */ -#define F(x, y, z) (((x) & (y)) | ((~x) & (z))) -#define G(x, y, z) (((x) & (z)) | ((y) & (~z))) -#define H(x, y, z) ((x) ^ (y) ^ (z)) -#define I(x, y, z) ((y) ^ ((x) | (~z))) - - -/* ROTATE_LEFT rotates x left n bits. */ -#define ROTATE_LEFT(x, n) (((x) << (n)) | ((x) >> (32-(n)))) - - -/* FF, GG, HH, and II transformations for rounds 1, 2, 3, and 4. - Rotation is separate from addition to prevent recomputation. */ -#define FF(a, b, c, d, x, s, ac) { \ - (a) += F ((b), (c), (d)) + (x) + (UInt32)(ac); \ - (a) = ROTATE_LEFT ((a), (s)); \ - (a) += (b); \ - } -#define GG(a, b, c, d, x, s, ac) { \ - (a) += G ((b), (c), (d)) + (x) + (UInt32)(ac); \ - (a) = ROTATE_LEFT ((a), (s)); \ - (a) += (b); \ - } -#define HH(a, b, c, d, x, s, ac) { \ - (a) += H ((b), (c), (d)) + (x) + (UInt32)(ac); \ - (a) = ROTATE_LEFT ((a), (s)); \ - (a) += (b); \ - } -#define II(a, b, c, d, x, s, ac) { \ - (a) += I ((b), (c), (d)) + (x) + (UInt32)(ac); \ - (a) = ROTATE_LEFT ((a), (s)); \ - (a) += (b); \ - } - - -void MD5Engine::transform (UInt32 state[4], const unsigned char block[64]) -{ - UInt32 a = state[0], b = state[1], c = state[2], d = state[3], x[16]; - - decode(x, block, 64); - - /* Round 1 */ - FF (a, b, c, d, x[ 0], S11, 0xd76aa478); /* 1 */ - FF (d, a, b, c, x[ 1], S12, 0xe8c7b756); /* 2 */ - FF (c, d, a, b, x[ 2], S13, 0x242070db); /* 3 */ - FF (b, c, d, a, x[ 3], S14, 0xc1bdceee); /* 4 */ - FF (a, b, c, d, x[ 4], S11, 0xf57c0faf); /* 5 */ - FF (d, a, b, c, x[ 5], S12, 0x4787c62a); /* 6 */ - FF (c, d, a, b, x[ 6], S13, 0xa8304613); /* 7 */ - FF (b, c, d, a, x[ 7], S14, 0xfd469501); /* 8 */ - FF (a, b, c, d, x[ 8], S11, 0x698098d8); /* 9 */ - FF (d, a, b, c, x[ 9], S12, 0x8b44f7af); /* 10 */ - FF (c, d, a, b, x[10], S13, 0xffff5bb1); /* 11 */ - FF (b, c, d, a, x[11], S14, 0x895cd7be); /* 12 */ - FF (a, b, c, d, x[12], S11, 0x6b901122); /* 13 */ - FF (d, a, b, c, x[13], S12, 0xfd987193); /* 14 */ - FF (c, d, a, b, x[14], S13, 0xa679438e); /* 15 */ - FF (b, c, d, a, x[15], S14, 0x49b40821); /* 16 */ - - /* Round 2 */ - GG (a, b, c, d, x[ 1], S21, 0xf61e2562); /* 17 */ - GG (d, a, b, c, x[ 6], S22, 0xc040b340); /* 18 */ - GG (c, d, a, b, x[11], S23, 0x265e5a51); /* 19 */ - GG (b, c, d, a, x[ 0], S24, 0xe9b6c7aa); /* 20 */ - GG (a, b, c, d, x[ 5], S21, 0xd62f105d); /* 21 */ - GG (d, a, b, c, x[10], S22, 0x2441453); /* 22 */ - GG (c, d, a, b, x[15], S23, 0xd8a1e681); /* 23 */ - GG (b, c, d, a, x[ 4], S24, 0xe7d3fbc8); /* 24 */ - GG (a, b, c, d, x[ 9], S21, 0x21e1cde6); /* 25 */ - GG (d, a, b, c, x[14], S22, 0xc33707d6); /* 26 */ - GG (c, d, a, b, x[ 3], S23, 0xf4d50d87); /* 27 */ - GG (b, c, d, a, x[ 8], S24, 0x455a14ed); /* 28 */ - GG (a, b, c, d, x[13], S21, 0xa9e3e905); /* 29 */ - GG (d, a, b, c, x[ 2], S22, 0xfcefa3f8); /* 30 */ - GG (c, d, a, b, x[ 7], S23, 0x676f02d9); /* 31 */ - GG (b, c, d, a, x[12], S24, 0x8d2a4c8a); /* 32 */ - - /* Round 3 */ - HH (a, b, c, d, x[ 5], S31, 0xfffa3942); /* 33 */ - HH (d, a, b, c, x[ 8], S32, 0x8771f681); /* 34 */ - HH (c, d, a, b, x[11], S33, 0x6d9d6122); /* 35 */ - HH (b, c, d, a, x[14], S34, 0xfde5380c); /* 36 */ - HH (a, b, c, d, x[ 1], S31, 0xa4beea44); /* 37 */ - HH (d, a, b, c, x[ 4], S32, 0x4bdecfa9); /* 38 */ - HH (c, d, a, b, x[ 7], S33, 0xf6bb4b60); /* 39 */ - HH (b, c, d, a, x[10], S34, 0xbebfbc70); /* 40 */ - HH (a, b, c, d, x[13], S31, 0x289b7ec6); /* 41 */ - HH (d, a, b, c, x[ 0], S32, 0xeaa127fa); /* 42 */ - HH (c, d, a, b, x[ 3], S33, 0xd4ef3085); /* 43 */ - HH (b, c, d, a, x[ 6], S34, 0x4881d05); /* 44 */ - HH (a, b, c, d, x[ 9], S31, 0xd9d4d039); /* 45 */ - HH (d, a, b, c, x[12], S32, 0xe6db99e5); /* 46 */ - HH (c, d, a, b, x[15], S33, 0x1fa27cf8); /* 47 */ - HH (b, c, d, a, x[ 2], S34, 0xc4ac5665); /* 48 */ - - /* Round 4 */ - II (a, b, c, d, x[ 0], S41, 0xf4292244); /* 49 */ - II (d, a, b, c, x[ 7], S42, 0x432aff97); /* 50 */ - II (c, d, a, b, x[14], S43, 0xab9423a7); /* 51 */ - II (b, c, d, a, x[ 5], S44, 0xfc93a039); /* 52 */ - II (a, b, c, d, x[12], S41, 0x655b59c3); /* 53 */ - II (d, a, b, c, x[ 3], S42, 0x8f0ccc92); /* 54 */ - II (c, d, a, b, x[10], S43, 0xffeff47d); /* 55 */ - II (b, c, d, a, x[ 1], S44, 0x85845dd1); /* 56 */ - II (a, b, c, d, x[ 8], S41, 0x6fa87e4f); /* 57 */ - II (d, a, b, c, x[15], S42, 0xfe2ce6e0); /* 58 */ - II (c, d, a, b, x[ 6], S43, 0xa3014314); /* 59 */ - II (b, c, d, a, x[13], S44, 0x4e0811a1); /* 60 */ - II (a, b, c, d, x[ 4], S41, 0xf7537e82); /* 61 */ - II (d, a, b, c, x[11], S42, 0xbd3af235); /* 62 */ - II (c, d, a, b, x[ 2], S43, 0x2ad7d2bb); /* 63 */ - II (b, c, d, a, x[ 9], S44, 0xeb86d391); /* 64 */ - - state[0] += a; - state[1] += b; - state[2] += c; - state[3] += d; - - /* Zeroize sensitive information. */ - memset(x, 0, sizeof(x)); -} - - -void MD5Engine::encode(unsigned char* output, const UInt32* input, unsigned int len) -{ - unsigned int i, j; - - for (i = 0, j = 0; j < len; i++, j += 4) - { - output[j] = (unsigned char)(input[i] & 0xff); - output[j+1] = (unsigned char)((input[i] >> 8) & 0xff); - output[j+2] = (unsigned char)((input[i] >> 16) & 0xff); - output[j+3] = (unsigned char)((input[i] >> 24) & 0xff); - } -} - - -void MD5Engine::decode(UInt32* output, const unsigned char* input, unsigned int len) -{ - unsigned int i, j; - - for (i = 0, j = 0; j < len; i++, j += 4) - output[i] = ((UInt32)input[j]) | (((UInt32)input[j+1]) << 8) | - (((UInt32)input[j+2]) << 16) | (((UInt32)input[j+3]) << 24); -} - - -} // namespace Poco +// +// MD5Engine.cpp +// +// $Id: //poco/1.2/Foundation/src/MD5Engine.cpp#1 $ +// +// Library: Foundation +// Package: Crypt +// Module: MD5Engine +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// +// +// MD5 (RFC 1321) algorithm: +// Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All +// rights reserved. +// +// License to copy and use this software is granted provided that it +// is identified as the "RSA Data Security, Inc. MD5 Message-Digest +// Algorithm" in all material mentioning or referencing this software +// or this function. +// +// License is also granted to make and use derivative works provided +// that such works are identified as "derived from the RSA Data +// Security, Inc. MD5 Message-Digest Algorithm" in all material +// mentioning or referencing the derived work. +// +// RSA Data Security, Inc. makes no representations concerning either +// the merchantability of this software or the suitability of this +// software for any particular purpose. It is provided "as is" +// without express or implied warranty of any kind. +// +// These notices must be retained in any copies of any part of this +// documentation and/or software. +// + + +#include "Poco/MD5Engine.h" +#include + + +namespace Poco { + + +MD5Engine::MD5Engine() +{ + _digest.reserve(16); + reset(); +} + + +MD5Engine::~MD5Engine() +{ + reset(); +} + + +void MD5Engine::updateImpl(const void* input_, unsigned inputLen) +{ + const unsigned char* input = (const unsigned char*) input_; + unsigned int i, index, partLen; + + /* Compute number of bytes mod 64 */ + index = (unsigned int)((_context.count[0] >> 3) & 0x3F); + + /* Update number of bits */ + if ((_context.count[0] += ((UInt32) inputLen << 3)) < ((UInt32) inputLen << 3)) + _context.count[1]++; + _context.count[1] += ((UInt32) inputLen >> 29); + + partLen = 64 - index; + + /* Transform as many times as possible. */ + if (inputLen >= partLen) + { + memcpy(&_context.buffer[index], input, partLen); + transform(_context.state, _context.buffer); + + for (i = partLen; i + 63 < inputLen; i += 64) + transform(_context.state, &input[i]); + + index = 0; + } + else i = 0; + + /* Buffer remaining input */ + memcpy(&_context.buffer[index], &input[i],inputLen-i); +} + + +unsigned MD5Engine::digestLength() const +{ + return DIGEST_SIZE; +} + + +void MD5Engine::reset() +{ + memset(&_context, 0, sizeof(_context)); + _context.count[0] = _context.count[1] = 0; + _context.state[0] = 0x67452301; + _context.state[1] = 0xefcdab89; + _context.state[2] = 0x98badcfe; + _context.state[3] = 0x10325476; +} + + +const DigestEngine::Digest& MD5Engine::digest() +{ + static const unsigned char PADDING[64] = + { + 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 + }; + unsigned char bits[8]; + unsigned int index, padLen; + + /* Save number of bits */ + encode(bits, _context.count, 8); + + /* Pad out to 56 mod 64. */ + index = (unsigned int)((_context.count[0] >> 3) & 0x3f); + padLen = (index < 56) ? (56 - index) : (120 - index); + update(PADDING, padLen); + + /* Append length (before padding) */ + update(bits, 8); + + /* Store state in digest */ + unsigned char digest[16]; + encode(digest, _context.state, 16); + _digest.clear(); + _digest.insert(_digest.begin(), digest, digest + sizeof(digest)); + + /* Zeroize sensitive information. */ + memset(&_context, 0, sizeof (_context)); + reset(); + return _digest; +} + + +/* Constants for MD5Transform routine. */ +#define S11 7 +#define S12 12 +#define S13 17 +#define S14 22 +#define S21 5 +#define S22 9 +#define S23 14 +#define S24 20 +#define S31 4 +#define S32 11 +#define S33 16 +#define S34 23 +#define S41 6 +#define S42 10 +#define S43 15 +#define S44 21 + + +/* F, G, H and I are basic MD5 functions. */ +#define F(x, y, z) (((x) & (y)) | ((~x) & (z))) +#define G(x, y, z) (((x) & (z)) | ((y) & (~z))) +#define H(x, y, z) ((x) ^ (y) ^ (z)) +#define I(x, y, z) ((y) ^ ((x) | (~z))) + + +/* ROTATE_LEFT rotates x left n bits. */ +#define ROTATE_LEFT(x, n) (((x) << (n)) | ((x) >> (32-(n)))) + + +/* FF, GG, HH, and II transformations for rounds 1, 2, 3, and 4. + Rotation is separate from addition to prevent recomputation. */ +#define FF(a, b, c, d, x, s, ac) { \ + (a) += F ((b), (c), (d)) + (x) + (UInt32)(ac); \ + (a) = ROTATE_LEFT ((a), (s)); \ + (a) += (b); \ + } +#define GG(a, b, c, d, x, s, ac) { \ + (a) += G ((b), (c), (d)) + (x) + (UInt32)(ac); \ + (a) = ROTATE_LEFT ((a), (s)); \ + (a) += (b); \ + } +#define HH(a, b, c, d, x, s, ac) { \ + (a) += H ((b), (c), (d)) + (x) + (UInt32)(ac); \ + (a) = ROTATE_LEFT ((a), (s)); \ + (a) += (b); \ + } +#define II(a, b, c, d, x, s, ac) { \ + (a) += I ((b), (c), (d)) + (x) + (UInt32)(ac); \ + (a) = ROTATE_LEFT ((a), (s)); \ + (a) += (b); \ + } + + +void MD5Engine::transform (UInt32 state[4], const unsigned char block[64]) +{ + UInt32 a = state[0], b = state[1], c = state[2], d = state[3], x[16]; + + decode(x, block, 64); + + /* Round 1 */ + FF (a, b, c, d, x[ 0], S11, 0xd76aa478); /* 1 */ + FF (d, a, b, c, x[ 1], S12, 0xe8c7b756); /* 2 */ + FF (c, d, a, b, x[ 2], S13, 0x242070db); /* 3 */ + FF (b, c, d, a, x[ 3], S14, 0xc1bdceee); /* 4 */ + FF (a, b, c, d, x[ 4], S11, 0xf57c0faf); /* 5 */ + FF (d, a, b, c, x[ 5], S12, 0x4787c62a); /* 6 */ + FF (c, d, a, b, x[ 6], S13, 0xa8304613); /* 7 */ + FF (b, c, d, a, x[ 7], S14, 0xfd469501); /* 8 */ + FF (a, b, c, d, x[ 8], S11, 0x698098d8); /* 9 */ + FF (d, a, b, c, x[ 9], S12, 0x8b44f7af); /* 10 */ + FF (c, d, a, b, x[10], S13, 0xffff5bb1); /* 11 */ + FF (b, c, d, a, x[11], S14, 0x895cd7be); /* 12 */ + FF (a, b, c, d, x[12], S11, 0x6b901122); /* 13 */ + FF (d, a, b, c, x[13], S12, 0xfd987193); /* 14 */ + FF (c, d, a, b, x[14], S13, 0xa679438e); /* 15 */ + FF (b, c, d, a, x[15], S14, 0x49b40821); /* 16 */ + + /* Round 2 */ + GG (a, b, c, d, x[ 1], S21, 0xf61e2562); /* 17 */ + GG (d, a, b, c, x[ 6], S22, 0xc040b340); /* 18 */ + GG (c, d, a, b, x[11], S23, 0x265e5a51); /* 19 */ + GG (b, c, d, a, x[ 0], S24, 0xe9b6c7aa); /* 20 */ + GG (a, b, c, d, x[ 5], S21, 0xd62f105d); /* 21 */ + GG (d, a, b, c, x[10], S22, 0x2441453); /* 22 */ + GG (c, d, a, b, x[15], S23, 0xd8a1e681); /* 23 */ + GG (b, c, d, a, x[ 4], S24, 0xe7d3fbc8); /* 24 */ + GG (a, b, c, d, x[ 9], S21, 0x21e1cde6); /* 25 */ + GG (d, a, b, c, x[14], S22, 0xc33707d6); /* 26 */ + GG (c, d, a, b, x[ 3], S23, 0xf4d50d87); /* 27 */ + GG (b, c, d, a, x[ 8], S24, 0x455a14ed); /* 28 */ + GG (a, b, c, d, x[13], S21, 0xa9e3e905); /* 29 */ + GG (d, a, b, c, x[ 2], S22, 0xfcefa3f8); /* 30 */ + GG (c, d, a, b, x[ 7], S23, 0x676f02d9); /* 31 */ + GG (b, c, d, a, x[12], S24, 0x8d2a4c8a); /* 32 */ + + /* Round 3 */ + HH (a, b, c, d, x[ 5], S31, 0xfffa3942); /* 33 */ + HH (d, a, b, c, x[ 8], S32, 0x8771f681); /* 34 */ + HH (c, d, a, b, x[11], S33, 0x6d9d6122); /* 35 */ + HH (b, c, d, a, x[14], S34, 0xfde5380c); /* 36 */ + HH (a, b, c, d, x[ 1], S31, 0xa4beea44); /* 37 */ + HH (d, a, b, c, x[ 4], S32, 0x4bdecfa9); /* 38 */ + HH (c, d, a, b, x[ 7], S33, 0xf6bb4b60); /* 39 */ + HH (b, c, d, a, x[10], S34, 0xbebfbc70); /* 40 */ + HH (a, b, c, d, x[13], S31, 0x289b7ec6); /* 41 */ + HH (d, a, b, c, x[ 0], S32, 0xeaa127fa); /* 42 */ + HH (c, d, a, b, x[ 3], S33, 0xd4ef3085); /* 43 */ + HH (b, c, d, a, x[ 6], S34, 0x4881d05); /* 44 */ + HH (a, b, c, d, x[ 9], S31, 0xd9d4d039); /* 45 */ + HH (d, a, b, c, x[12], S32, 0xe6db99e5); /* 46 */ + HH (c, d, a, b, x[15], S33, 0x1fa27cf8); /* 47 */ + HH (b, c, d, a, x[ 2], S34, 0xc4ac5665); /* 48 */ + + /* Round 4 */ + II (a, b, c, d, x[ 0], S41, 0xf4292244); /* 49 */ + II (d, a, b, c, x[ 7], S42, 0x432aff97); /* 50 */ + II (c, d, a, b, x[14], S43, 0xab9423a7); /* 51 */ + II (b, c, d, a, x[ 5], S44, 0xfc93a039); /* 52 */ + II (a, b, c, d, x[12], S41, 0x655b59c3); /* 53 */ + II (d, a, b, c, x[ 3], S42, 0x8f0ccc92); /* 54 */ + II (c, d, a, b, x[10], S43, 0xffeff47d); /* 55 */ + II (b, c, d, a, x[ 1], S44, 0x85845dd1); /* 56 */ + II (a, b, c, d, x[ 8], S41, 0x6fa87e4f); /* 57 */ + II (d, a, b, c, x[15], S42, 0xfe2ce6e0); /* 58 */ + II (c, d, a, b, x[ 6], S43, 0xa3014314); /* 59 */ + II (b, c, d, a, x[13], S44, 0x4e0811a1); /* 60 */ + II (a, b, c, d, x[ 4], S41, 0xf7537e82); /* 61 */ + II (d, a, b, c, x[11], S42, 0xbd3af235); /* 62 */ + II (c, d, a, b, x[ 2], S43, 0x2ad7d2bb); /* 63 */ + II (b, c, d, a, x[ 9], S44, 0xeb86d391); /* 64 */ + + state[0] += a; + state[1] += b; + state[2] += c; + state[3] += d; + + /* Zeroize sensitive information. */ + memset(x, 0, sizeof(x)); +} + + +void MD5Engine::encode(unsigned char* output, const UInt32* input, unsigned int len) +{ + unsigned int i, j; + + for (i = 0, j = 0; j < len; i++, j += 4) + { + output[j] = (unsigned char)(input[i] & 0xff); + output[j+1] = (unsigned char)((input[i] >> 8) & 0xff); + output[j+2] = (unsigned char)((input[i] >> 16) & 0xff); + output[j+3] = (unsigned char)((input[i] >> 24) & 0xff); + } +} + + +void MD5Engine::decode(UInt32* output, const unsigned char* input, unsigned int len) +{ + unsigned int i, j; + + for (i = 0, j = 0; j < len; i++, j += 4) + output[i] = ((UInt32)input[j]) | (((UInt32)input[j+1]) << 8) | + (((UInt32)input[j+2]) << 16) | (((UInt32)input[j+3]) << 24); +} + + +} // namespace Poco diff --git a/Foundation/src/Manifest.cpp b/Foundation/src/Manifest.cpp index 67b7232ad..f3b186668 100644 --- a/Foundation/src/Manifest.cpp +++ b/Foundation/src/Manifest.cpp @@ -1,53 +1,53 @@ -// -// Manifest.cpp -// -// $Id: //poco/1.2/Foundation/src/Manifest.cpp#1 $ -// -// Library: Foundation -// Package: SharedLibrary -// Module: ClassLoader -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/Manifest.h" - - -namespace Poco { - - -ManifestBase::ManifestBase() -{ -} - - -ManifestBase::~ManifestBase() -{ -} - - -} // namespace Poco +// +// Manifest.cpp +// +// $Id: //poco/1.2/Foundation/src/Manifest.cpp#1 $ +// +// Library: Foundation +// Package: SharedLibrary +// Module: ClassLoader +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/Manifest.h" + + +namespace Poco { + + +ManifestBase::ManifestBase() +{ +} + + +ManifestBase::~ManifestBase() +{ +} + + +} // namespace Poco diff --git a/Foundation/src/MemoryPool.cpp b/Foundation/src/MemoryPool.cpp index 310ce4c17..a60df3659 100644 --- a/Foundation/src/MemoryPool.cpp +++ b/Foundation/src/MemoryPool.cpp @@ -1,103 +1,103 @@ -// -// MemoryPool.cpp -// -// $Id: //poco/1.2/Foundation/src/MemoryPool.cpp#1 $ -// -// Library: Foundation -// Package: Core -// Module: MemoryPool -// -// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/MemoryPool.h" -#include "Poco/Exception.h" - - -namespace Poco { - - -MemoryPool::MemoryPool(size_t blockSize, int preAlloc, int maxAlloc): - _blockSize(blockSize), - _maxAlloc(maxAlloc), - _allocated(preAlloc) -{ - poco_assert (maxAlloc == 0 || maxAlloc >= preAlloc); - - int r = BLOCK_RESERVE; - if (preAlloc > r) - r = preAlloc; - if (maxAlloc > 0 && maxAlloc < r) - r = maxAlloc; - _blocks.reserve(r); - for (int i = 0; i < preAlloc; ++i) - { - _blocks.push_back(new char[_blockSize]); - } -} - - -MemoryPool::~MemoryPool() -{ - for (BlockVec::iterator it = _blocks.begin(); it != _blocks.end(); ++it) - { - delete [] *it; - } -} - - -void* MemoryPool::get() -{ - FastMutex::ScopedLock lock(_mutex); - - if (_blocks.empty()) - { - if (_maxAlloc == 0 || _allocated < _maxAlloc) - { - ++_allocated; - return new char[_blockSize]; - } - else throw OutOfMemoryException("MemoryPool exhausted"); - } - else - { - char* ptr = _blocks.back(); - _blocks.pop_back(); - return ptr; - } -} - - -void MemoryPool::release(void* ptr) -{ - FastMutex::ScopedLock lock(_mutex); - - _blocks.push_back(reinterpret_cast(ptr)); -} - - -} // namespace Poco +// +// MemoryPool.cpp +// +// $Id: //poco/1.2/Foundation/src/MemoryPool.cpp#1 $ +// +// Library: Foundation +// Package: Core +// Module: MemoryPool +// +// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/MemoryPool.h" +#include "Poco/Exception.h" + + +namespace Poco { + + +MemoryPool::MemoryPool(size_t blockSize, int preAlloc, int maxAlloc): + _blockSize(blockSize), + _maxAlloc(maxAlloc), + _allocated(preAlloc) +{ + poco_assert (maxAlloc == 0 || maxAlloc >= preAlloc); + + int r = BLOCK_RESERVE; + if (preAlloc > r) + r = preAlloc; + if (maxAlloc > 0 && maxAlloc < r) + r = maxAlloc; + _blocks.reserve(r); + for (int i = 0; i < preAlloc; ++i) + { + _blocks.push_back(new char[_blockSize]); + } +} + + +MemoryPool::~MemoryPool() +{ + for (BlockVec::iterator it = _blocks.begin(); it != _blocks.end(); ++it) + { + delete [] *it; + } +} + + +void* MemoryPool::get() +{ + FastMutex::ScopedLock lock(_mutex); + + if (_blocks.empty()) + { + if (_maxAlloc == 0 || _allocated < _maxAlloc) + { + ++_allocated; + return new char[_blockSize]; + } + else throw OutOfMemoryException("MemoryPool exhausted"); + } + else + { + char* ptr = _blocks.back(); + _blocks.pop_back(); + return ptr; + } +} + + +void MemoryPool::release(void* ptr) +{ + FastMutex::ScopedLock lock(_mutex); + + _blocks.push_back(reinterpret_cast(ptr)); +} + + +} // namespace Poco diff --git a/Foundation/src/Message.cpp b/Foundation/src/Message.cpp index ef1380a6f..d05b8038f 100644 --- a/Foundation/src/Message.cpp +++ b/Foundation/src/Message.cpp @@ -1,202 +1,202 @@ -// -// Message.cpp -// -// $Id: //poco/1.2/Foundation/src/Message.cpp#1 $ -// -// Library: Foundation -// Package: Logging -// Module: Message -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/Message.h" -#include "Poco/Exception.h" -#include "Poco/Process.h" -#include "Poco/Thread.h" - - -namespace Poco { - - -Message::Message(): - _prio(PRIO_FATAL), - _tid(0), - _pid(0), - _pMap(0) -{ - init(); -} - - -Message::Message(const std::string& source, const std::string& text, Priority prio): - _source(source), - _text(text), - _prio(prio), - _tid(0), - _pid(0), - _pMap(0) -{ - init(); -} - - -Message::Message(const Message& msg) -{ - _source = msg._source; - _text = msg._text; - _prio = msg._prio; - _time = msg._time; - _thread = msg._thread; - _tid = msg._tid; - _pid = msg._pid; - if (msg._pMap) - _pMap = new StringMap(*msg._pMap); - else - _pMap = 0; -} - - -Message::Message(const Message& msg, const std::string& text) -{ - _source = msg._source; - _text = text; - _prio = msg._prio; - _time = msg._time; - _thread = msg._thread; - _tid = msg._tid; - _pid = msg._pid; - if (msg._pMap) - _pMap = new StringMap(*msg._pMap); - else - _pMap = 0; -} - - -Message::~Message() -{ - delete _pMap; -} - - -void Message::init() -{ - _pid = Process::id(); - Thread* pThread = Thread::current(); - if (pThread) - { - _tid = pThread->id(); - _thread = pThread->name(); - } -} - - -Message& Message::operator = (const Message& msg) -{ - if (this == &msg) return *this; - - _source = msg._source; - _text = msg._text; - _prio = msg._prio; - _time = msg._time; - _thread = msg._thread; - _pid = msg._pid; - if (msg._pMap) - _pMap = new StringMap(*msg._pMap); - else - _pMap = 0; - - return *this; -} - - -void Message::setSource(const std::string& src) -{ - _source = src; -} - - -void Message::setText(const std::string& text) -{ - _text = text; -} - - -void Message::setPriority(Priority prio) -{ - _prio = prio; -} - - -void Message::setTime(const Timestamp& t) -{ - _time = t; -} - - -const Timestamp& Message::getTime() const -{ - return _time; -} - - -void Message::setThread(const std::string& thread) -{ - _thread = thread; -} - - -void Message::setTid(long tid) -{ - _tid = tid; -} - - -void Message::setPid(long pid) -{ - _pid = pid; -} - - -const std::string& Message::operator [] (const std::string& param) const -{ - if (_pMap) - return (*_pMap)[param]; - else - throw NotFoundException(); -} - - -std::string& Message::operator [] (const std::string& param) -{ - if (!_pMap) - _pMap = new StringMap; - return (*_pMap)[param]; -} - - -} // namespace Poco +// +// Message.cpp +// +// $Id: //poco/1.2/Foundation/src/Message.cpp#1 $ +// +// Library: Foundation +// Package: Logging +// Module: Message +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/Message.h" +#include "Poco/Exception.h" +#include "Poco/Process.h" +#include "Poco/Thread.h" + + +namespace Poco { + + +Message::Message(): + _prio(PRIO_FATAL), + _tid(0), + _pid(0), + _pMap(0) +{ + init(); +} + + +Message::Message(const std::string& source, const std::string& text, Priority prio): + _source(source), + _text(text), + _prio(prio), + _tid(0), + _pid(0), + _pMap(0) +{ + init(); +} + + +Message::Message(const Message& msg) +{ + _source = msg._source; + _text = msg._text; + _prio = msg._prio; + _time = msg._time; + _thread = msg._thread; + _tid = msg._tid; + _pid = msg._pid; + if (msg._pMap) + _pMap = new StringMap(*msg._pMap); + else + _pMap = 0; +} + + +Message::Message(const Message& msg, const std::string& text) +{ + _source = msg._source; + _text = text; + _prio = msg._prio; + _time = msg._time; + _thread = msg._thread; + _tid = msg._tid; + _pid = msg._pid; + if (msg._pMap) + _pMap = new StringMap(*msg._pMap); + else + _pMap = 0; +} + + +Message::~Message() +{ + delete _pMap; +} + + +void Message::init() +{ + _pid = Process::id(); + Thread* pThread = Thread::current(); + if (pThread) + { + _tid = pThread->id(); + _thread = pThread->name(); + } +} + + +Message& Message::operator = (const Message& msg) +{ + if (this == &msg) return *this; + + _source = msg._source; + _text = msg._text; + _prio = msg._prio; + _time = msg._time; + _thread = msg._thread; + _pid = msg._pid; + if (msg._pMap) + _pMap = new StringMap(*msg._pMap); + else + _pMap = 0; + + return *this; +} + + +void Message::setSource(const std::string& src) +{ + _source = src; +} + + +void Message::setText(const std::string& text) +{ + _text = text; +} + + +void Message::setPriority(Priority prio) +{ + _prio = prio; +} + + +void Message::setTime(const Timestamp& t) +{ + _time = t; +} + + +const Timestamp& Message::getTime() const +{ + return _time; +} + + +void Message::setThread(const std::string& thread) +{ + _thread = thread; +} + + +void Message::setTid(long tid) +{ + _tid = tid; +} + + +void Message::setPid(long pid) +{ + _pid = pid; +} + + +const std::string& Message::operator [] (const std::string& param) const +{ + if (_pMap) + return (*_pMap)[param]; + else + throw NotFoundException(); +} + + +std::string& Message::operator [] (const std::string& param) +{ + if (!_pMap) + _pMap = new StringMap; + return (*_pMap)[param]; +} + + +} // namespace Poco diff --git a/Foundation/src/Mutex.cpp b/Foundation/src/Mutex.cpp index 8c05b7aaf..30f5b866a 100644 --- a/Foundation/src/Mutex.cpp +++ b/Foundation/src/Mutex.cpp @@ -1,70 +1,70 @@ -// -// Mutex.cpp -// -// $Id: //poco/1.2/Foundation/src/Mutex.cpp#1 $ -// -// Library: Foundation -// Package: Threading -// Module: Mutex -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/Mutex.h" - - -#if defined(POCO_OS_FAMILY_WINDOWS) -#include "Mutex_WIN32.cpp" -#else -#include "Mutex_POSIX.cpp" -#endif - - -namespace Poco { - - -Mutex::Mutex() -{ -} - - -Mutex::~Mutex() -{ -} - - -FastMutex::FastMutex() -{ -} - - -FastMutex::~FastMutex() -{ -} - - -} // namespace Poco +// +// Mutex.cpp +// +// $Id: //poco/1.2/Foundation/src/Mutex.cpp#1 $ +// +// Library: Foundation +// Package: Threading +// Module: Mutex +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/Mutex.h" + + +#if defined(POCO_OS_FAMILY_WINDOWS) +#include "Mutex_WIN32.cpp" +#else +#include "Mutex_POSIX.cpp" +#endif + + +namespace Poco { + + +Mutex::Mutex() +{ +} + + +Mutex::~Mutex() +{ +} + + +FastMutex::FastMutex() +{ +} + + +FastMutex::~FastMutex() +{ +} + + +} // namespace Poco diff --git a/Foundation/src/Mutex_POSIX.cpp b/Foundation/src/Mutex_POSIX.cpp index 0a6ee7f63..3723eaffd 100644 --- a/Foundation/src/Mutex_POSIX.cpp +++ b/Foundation/src/Mutex_POSIX.cpp @@ -1,95 +1,95 @@ -// -// Mutex_POSIX.cpp -// -// $Id: //poco/1.2/Foundation/src/Mutex_POSIX.cpp#1 $ -// -// Library: Foundation -// Package: Threading -// Module: Mutex -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/Mutex_POSIX.h" - - -namespace Poco { - - -MutexImpl::MutexImpl() -{ - pthread_mutexattr_t attr; - pthread_mutexattr_init(&attr); -#if defined(PTHREAD_MUTEX_RECURSIVE_NP) - pthread_mutexattr_settype_np(&attr, PTHREAD_MUTEX_RECURSIVE_NP); -#else - pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); -#endif - if (pthread_mutex_init(&_mutex, &attr)) - { - pthread_mutexattr_destroy(&attr); - throw SystemException("cannot create mutex"); - } - pthread_mutexattr_destroy(&attr); -} - - -MutexImpl::MutexImpl(bool fast) -{ - pthread_mutexattr_t attr; - pthread_mutexattr_init(&attr); -#if defined(PTHREAD_MUTEX_RECURSIVE_NP) - pthread_mutexattr_settype_np(&attr, fast ? PTHREAD_MUTEX_NORMAL_NP : PTHREAD_MUTEX_RECURSIVE_NP); -#else - pthread_mutexattr_settype(&attr, fast ? PTHREAD_MUTEX_NORMAL : PTHREAD_MUTEX_RECURSIVE); -#endif - if (pthread_mutex_init(&_mutex, &attr)) - { - pthread_mutexattr_destroy(&attr); - throw SystemException("cannot create mutex"); - } - pthread_mutexattr_destroy(&attr); -} - - -MutexImpl::~MutexImpl() -{ - pthread_mutex_destroy(&_mutex); -} - - -FastMutexImpl::FastMutexImpl(): MutexImpl(true) -{ -} - - -FastMutexImpl::~FastMutexImpl() -{ -} - - -} // namespace Poco +// +// Mutex_POSIX.cpp +// +// $Id: //poco/1.2/Foundation/src/Mutex_POSIX.cpp#1 $ +// +// Library: Foundation +// Package: Threading +// Module: Mutex +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/Mutex_POSIX.h" + + +namespace Poco { + + +MutexImpl::MutexImpl() +{ + pthread_mutexattr_t attr; + pthread_mutexattr_init(&attr); +#if defined(PTHREAD_MUTEX_RECURSIVE_NP) + pthread_mutexattr_settype_np(&attr, PTHREAD_MUTEX_RECURSIVE_NP); +#else + pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); +#endif + if (pthread_mutex_init(&_mutex, &attr)) + { + pthread_mutexattr_destroy(&attr); + throw SystemException("cannot create mutex"); + } + pthread_mutexattr_destroy(&attr); +} + + +MutexImpl::MutexImpl(bool fast) +{ + pthread_mutexattr_t attr; + pthread_mutexattr_init(&attr); +#if defined(PTHREAD_MUTEX_RECURSIVE_NP) + pthread_mutexattr_settype_np(&attr, fast ? PTHREAD_MUTEX_NORMAL_NP : PTHREAD_MUTEX_RECURSIVE_NP); +#else + pthread_mutexattr_settype(&attr, fast ? PTHREAD_MUTEX_NORMAL : PTHREAD_MUTEX_RECURSIVE); +#endif + if (pthread_mutex_init(&_mutex, &attr)) + { + pthread_mutexattr_destroy(&attr); + throw SystemException("cannot create mutex"); + } + pthread_mutexattr_destroy(&attr); +} + + +MutexImpl::~MutexImpl() +{ + pthread_mutex_destroy(&_mutex); +} + + +FastMutexImpl::FastMutexImpl(): MutexImpl(true) +{ +} + + +FastMutexImpl::~FastMutexImpl() +{ +} + + +} // namespace Poco diff --git a/Foundation/src/Mutex_WIN32.cpp b/Foundation/src/Mutex_WIN32.cpp index 5ba97ebce..1d9da8934 100644 --- a/Foundation/src/Mutex_WIN32.cpp +++ b/Foundation/src/Mutex_WIN32.cpp @@ -1,56 +1,56 @@ -// -// Mutex_WIN32.cpp -// -// $Id: //poco/1.2/Foundation/src/Mutex_WIN32.cpp#1 $ -// -// Library: Foundation -// Package: Threading -// Module: Mutex -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/Mutex_WIN32.h" - - -namespace Poco { - - -MutexImpl::MutexImpl() -{ - if (!InitializeCriticalSectionAndSpinCount(&_cs, 4000)) - throw SystemException("cannot create mutex"); -} - - -MutexImpl::~MutexImpl() -{ - DeleteCriticalSection(&_cs); -} - - -} // namespace Poco +// +// Mutex_WIN32.cpp +// +// $Id: //poco/1.2/Foundation/src/Mutex_WIN32.cpp#1 $ +// +// Library: Foundation +// Package: Threading +// Module: Mutex +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/Mutex_WIN32.h" + + +namespace Poco { + + +MutexImpl::MutexImpl() +{ + if (!InitializeCriticalSectionAndSpinCount(&_cs, 4000)) + throw SystemException("cannot create mutex"); +} + + +MutexImpl::~MutexImpl() +{ + DeleteCriticalSection(&_cs); +} + + +} // namespace Poco diff --git a/Foundation/src/NamedEvent.cpp b/Foundation/src/NamedEvent.cpp index fc6270086..aacddcf4e 100644 --- a/Foundation/src/NamedEvent.cpp +++ b/Foundation/src/NamedEvent.cpp @@ -1,65 +1,65 @@ -// -// NamedEvent.cpp -// -// $Id: //poco/1.2/Foundation/src/NamedEvent.cpp#1 $ -// -// Library: Foundation -// Package: Processes -// Module: NamedEvent -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/NamedEvent.h" - - -#if defined(POCO_OS_FAMILY_WINDOWS) && defined(POCO_WIN32_UTF8) -#include "NamedEvent_WIN32U.cpp" -#elif defined(POCO_OS_FAMILY_WINDOWS) -#include "NamedEvent_WIN32.cpp" -#elif defined(POCO_OS_FAMILY_UNIX) -#include "NamedEvent_UNIX.cpp" -#else -#include "NamedEvent_VMS.cpp" -#endif - - -namespace Poco { - - -NamedEvent::NamedEvent(const std::string& name): - NamedEventImpl(name) -{ -} - - -NamedEvent::~NamedEvent() -{ -} - - -} // namespace Poco +// +// NamedEvent.cpp +// +// $Id: //poco/1.2/Foundation/src/NamedEvent.cpp#1 $ +// +// Library: Foundation +// Package: Processes +// Module: NamedEvent +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/NamedEvent.h" + + +#if defined(POCO_OS_FAMILY_WINDOWS) && defined(POCO_WIN32_UTF8) +#include "NamedEvent_WIN32U.cpp" +#elif defined(POCO_OS_FAMILY_WINDOWS) +#include "NamedEvent_WIN32.cpp" +#elif defined(POCO_OS_FAMILY_UNIX) +#include "NamedEvent_UNIX.cpp" +#else +#include "NamedEvent_VMS.cpp" +#endif + + +namespace Poco { + + +NamedEvent::NamedEvent(const std::string& name): + NamedEventImpl(name) +{ +} + + +NamedEvent::~NamedEvent() +{ +} + + +} // namespace Poco diff --git a/Foundation/src/NamedEvent_UNIX.cpp b/Foundation/src/NamedEvent_UNIX.cpp index 0b9e2b5da..0137f4898 100644 --- a/Foundation/src/NamedEvent_UNIX.cpp +++ b/Foundation/src/NamedEvent_UNIX.cpp @@ -1,169 +1,169 @@ -// -// NamedEvent_UNIX.cpp -// -// $Id: //poco/1.2/Foundation/src/NamedEvent_UNIX.cpp#2 $ -// -// Library: Foundation -// Package: Processes -// Module: NamedEvent -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/NamedEvent_UNIX.h" -#include "Poco/Exception.h" -#include -#include -#include -#if defined(sun) || defined(__APPLE__) || defined(__osf__) || defined(__QNX__) -#include -#else -#include -#include -#include -#include -#endif - - -namespace Poco { - - -#if defined(linux) || defined(__CYGWIN__) - union semun - { - int val; - struct semid_ds* buf; - unsigned short int* array; - struct seminfo* __buf; - }; -#elif defined(hpux) - union semun - { - int val; - struct semid_ds* buf; - ushort* array; - }; -#endif - - -NamedEventImpl::NamedEventImpl(const std::string& name): - _name(name) -{ - std::string fileName = getFileName(); -#if defined(sun) || defined(__APPLE__) || defined(__osf__) || defined(__QNX__) - _sem = sem_open(fileName.c_str(), O_CREAT, S_IRWXU | S_IRWXG | S_IRWXO, 0); - if ((long) _sem == (long) SEM_FAILED) - throw SystemException("cannot create named event (sem_open() failed)", _name); -#else - int fd = open(fileName.c_str(), O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); - if (fd != -1) - close(fd); - else - throw SystemException("cannot create named event (lockfile)", _name); - key_t key = ftok(fileName.c_str(), 0); - if (key == -1) - throw SystemException("cannot create named event (ftok() failed)", _name); - _semid = semget(key, 1, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH | IPC_CREAT | IPC_EXCL); - if (_semid >= 0) - { - union semun arg; - arg.val = 0; - semctl(_semid, 0, SETVAL, arg); - } - else if (errno == EEXIST) - { - _semid = semget(key, 1, 0); - } - else throw SystemException("cannot create named event (semget() failed)", _name); -#endif // defined(sun) || defined(__APPLE__) || defined(__osf__) || defined(__QNX__) -} - - -NamedEventImpl::~NamedEventImpl() -{ -#if defined(sun) || defined(__APPLE__) || defined(__osf__) || defined(__QNX__) - sem_close(_sem); -#endif -} - - -void NamedEventImpl::setImpl() -{ -#if defined(sun) || defined(__APPLE__) || defined(__osf__) || defined(__QNX__) - if (sem_post(_sem) != 0) - throw SystemException("cannot set named event", _name); -#else - struct sembuf op; - op.sem_num = 0; - op.sem_op = 1; - op.sem_flg = 0; - if (semop(_semid, &op, 1) != 0) - throw SystemException("cannot set named event", _name); -#endif -} - - -void NamedEventImpl::waitImpl() -{ -#if defined(sun) || defined(__APPLE__) || defined(__osf__) || defined(__QNX__) - int err; - do - { - err = sem_wait(_sem); - } - while (err && errno == EINTR); - if (err) throw SystemException("cannot wait for named event", _name); -#else - struct sembuf op; - op.sem_num = 0; - op.sem_op = -1; - op.sem_flg = 0; - int err; - do - { - err = semop(_semid, &op, 1); - } - while (err && errno == EINTR); - if (err) throw SystemException("cannot wait for named event", _name); -#endif -} - - -std::string NamedEventImpl::getFileName() -{ -#if defined(sun) || defined(__APPLE__) || defined(__QNX__) - std::string fn = "/"; -#else - std::string fn = "/tmp/"; -#endif - fn.append(_name); - fn.append(".event"); - return fn; -} - - -} // namespace Poco +// +// NamedEvent_UNIX.cpp +// +// $Id: //poco/1.2/Foundation/src/NamedEvent_UNIX.cpp#2 $ +// +// Library: Foundation +// Package: Processes +// Module: NamedEvent +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/NamedEvent_UNIX.h" +#include "Poco/Exception.h" +#include +#include +#include +#if defined(sun) || defined(__APPLE__) || defined(__osf__) || defined(__QNX__) +#include +#else +#include +#include +#include +#include +#endif + + +namespace Poco { + + +#if defined(linux) || defined(__CYGWIN__) + union semun + { + int val; + struct semid_ds* buf; + unsigned short int* array; + struct seminfo* __buf; + }; +#elif defined(hpux) + union semun + { + int val; + struct semid_ds* buf; + ushort* array; + }; +#endif + + +NamedEventImpl::NamedEventImpl(const std::string& name): + _name(name) +{ + std::string fileName = getFileName(); +#if defined(sun) || defined(__APPLE__) || defined(__osf__) || defined(__QNX__) + _sem = sem_open(fileName.c_str(), O_CREAT, S_IRWXU | S_IRWXG | S_IRWXO, 0); + if ((long) _sem == (long) SEM_FAILED) + throw SystemException("cannot create named event (sem_open() failed)", _name); +#else + int fd = open(fileName.c_str(), O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); + if (fd != -1) + close(fd); + else + throw SystemException("cannot create named event (lockfile)", _name); + key_t key = ftok(fileName.c_str(), 0); + if (key == -1) + throw SystemException("cannot create named event (ftok() failed)", _name); + _semid = semget(key, 1, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH | IPC_CREAT | IPC_EXCL); + if (_semid >= 0) + { + union semun arg; + arg.val = 0; + semctl(_semid, 0, SETVAL, arg); + } + else if (errno == EEXIST) + { + _semid = semget(key, 1, 0); + } + else throw SystemException("cannot create named event (semget() failed)", _name); +#endif // defined(sun) || defined(__APPLE__) || defined(__osf__) || defined(__QNX__) +} + + +NamedEventImpl::~NamedEventImpl() +{ +#if defined(sun) || defined(__APPLE__) || defined(__osf__) || defined(__QNX__) + sem_close(_sem); +#endif +} + + +void NamedEventImpl::setImpl() +{ +#if defined(sun) || defined(__APPLE__) || defined(__osf__) || defined(__QNX__) + if (sem_post(_sem) != 0) + throw SystemException("cannot set named event", _name); +#else + struct sembuf op; + op.sem_num = 0; + op.sem_op = 1; + op.sem_flg = 0; + if (semop(_semid, &op, 1) != 0) + throw SystemException("cannot set named event", _name); +#endif +} + + +void NamedEventImpl::waitImpl() +{ +#if defined(sun) || defined(__APPLE__) || defined(__osf__) || defined(__QNX__) + int err; + do + { + err = sem_wait(_sem); + } + while (err && errno == EINTR); + if (err) throw SystemException("cannot wait for named event", _name); +#else + struct sembuf op; + op.sem_num = 0; + op.sem_op = -1; + op.sem_flg = 0; + int err; + do + { + err = semop(_semid, &op, 1); + } + while (err && errno == EINTR); + if (err) throw SystemException("cannot wait for named event", _name); +#endif +} + + +std::string NamedEventImpl::getFileName() +{ +#if defined(sun) || defined(__APPLE__) || defined(__QNX__) + std::string fn = "/"; +#else + std::string fn = "/tmp/"; +#endif + fn.append(_name); + fn.append(".event"); + return fn; +} + + +} // namespace Poco diff --git a/Foundation/src/NamedEvent_VMS.cpp b/Foundation/src/NamedEvent_VMS.cpp index fddd2ece0..e9e3676a1 100644 --- a/Foundation/src/NamedEvent_VMS.cpp +++ b/Foundation/src/NamedEvent_VMS.cpp @@ -1,85 +1,85 @@ -// -// NamedEvent_VMS.cpp -// -// $Id: //poco/1.2/Foundation/src/NamedEvent_VMS.cpp#1 $ -// -// Library: Foundation -// Package: Processes -// Module: NamedEvent -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/NamedEvent_VMS.h" -#include -#include -#include -#include - - -namespace Poco { - - -NamedEventImpl::NamedEventImpl(const std::string& name): - _name(name) -{ - struct dsc$descriptor_s mbxDesc; - mbxDesc.dsc$w_length = _name.length(); - mbxDesc.dsc$b_dtype = DSC$K_DTYPE_T; - mbxDesc.dsc$b_class = DSC$K_CLASS_S; - mbxDesc.dsc$a_pointer = _name.c_str(); - if (sys$crembx(0, &_mbxChan, 0, 0, 0, 0, &mbxDesc, 0, 0) != 1) - throw SystemException("cannot create named event", _name); -} - - -NamedEventImpl::~NamedEventImpl() -{ - sys$dassgn(_mbxChan); -} - - -void NamedEventImpl::setImpl() -{ - char buffer = 0xFF; - if (sys$qio(0, _mbxChan, IO$_WRITEVBLK, 0, 0, 0, &buffer, sizeof(buffer), 0, 0, 0, 0) != 1) - throw SystemException("cannot set named event", _name); -} - - -void NamedEventImpl::waitImpl() -{ - char buffer = 0; - while (buffer == 0) - { - if (sys$qiow(0, _mbxChan, IO$_READVBLK, 0, 0, 0, &buffer, sizeof(buffer), 0, 0, 0, 0) != 1) - throw SystemException("cannot wait for named event", _name); - } -} - - -} // namespace Poco +// +// NamedEvent_VMS.cpp +// +// $Id: //poco/1.2/Foundation/src/NamedEvent_VMS.cpp#1 $ +// +// Library: Foundation +// Package: Processes +// Module: NamedEvent +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/NamedEvent_VMS.h" +#include +#include +#include +#include + + +namespace Poco { + + +NamedEventImpl::NamedEventImpl(const std::string& name): + _name(name) +{ + struct dsc$descriptor_s mbxDesc; + mbxDesc.dsc$w_length = _name.length(); + mbxDesc.dsc$b_dtype = DSC$K_DTYPE_T; + mbxDesc.dsc$b_class = DSC$K_CLASS_S; + mbxDesc.dsc$a_pointer = _name.c_str(); + if (sys$crembx(0, &_mbxChan, 0, 0, 0, 0, &mbxDesc, 0, 0) != 1) + throw SystemException("cannot create named event", _name); +} + + +NamedEventImpl::~NamedEventImpl() +{ + sys$dassgn(_mbxChan); +} + + +void NamedEventImpl::setImpl() +{ + char buffer = 0xFF; + if (sys$qio(0, _mbxChan, IO$_WRITEVBLK, 0, 0, 0, &buffer, sizeof(buffer), 0, 0, 0, 0) != 1) + throw SystemException("cannot set named event", _name); +} + + +void NamedEventImpl::waitImpl() +{ + char buffer = 0; + while (buffer == 0) + { + if (sys$qiow(0, _mbxChan, IO$_READVBLK, 0, 0, 0, &buffer, sizeof(buffer), 0, 0, 0, 0) != 1) + throw SystemException("cannot wait for named event", _name); + } +} + + +} // namespace Poco diff --git a/Foundation/src/NamedEvent_WIN32.cpp b/Foundation/src/NamedEvent_WIN32.cpp index c252d6ae6..f1b9a95ac 100644 --- a/Foundation/src/NamedEvent_WIN32.cpp +++ b/Foundation/src/NamedEvent_WIN32.cpp @@ -1,78 +1,78 @@ -// -// NamedEvent_WIN32.cpp -// -// $Id: //poco/1.2/Foundation/src/NamedEvent_WIN32.cpp#1 $ -// -// Library: Foundation -// Package: Processes -// Module: NamedEvent -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/NamedEvent_WIN32.h" -#include "Poco/Exception.h" - - -namespace Poco { - - -NamedEventImpl::NamedEventImpl(const std::string& name): - _name(name) -{ - _event = CreateEvent(NULL, FALSE, FALSE, _name.c_str()); - if (!_event) - throw SystemException("cannot create named event", _name); -} - - -NamedEventImpl::~NamedEventImpl() -{ - CloseHandle(_event); -} - - -void NamedEventImpl::setImpl() -{ - if (!SetEvent(_event)) - throw SystemException("cannot signal named event", _name); -} - - -void NamedEventImpl::waitImpl() -{ - switch (WaitForSingleObject(_event, INFINITE)) - { - case WAIT_OBJECT_0: - return; - default: - throw SystemException("wait for named event failed", _name); - } -} - - -} // namespace Poco +// +// NamedEvent_WIN32.cpp +// +// $Id: //poco/1.2/Foundation/src/NamedEvent_WIN32.cpp#1 $ +// +// Library: Foundation +// Package: Processes +// Module: NamedEvent +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/NamedEvent_WIN32.h" +#include "Poco/Exception.h" + + +namespace Poco { + + +NamedEventImpl::NamedEventImpl(const std::string& name): + _name(name) +{ + _event = CreateEvent(NULL, FALSE, FALSE, _name.c_str()); + if (!_event) + throw SystemException("cannot create named event", _name); +} + + +NamedEventImpl::~NamedEventImpl() +{ + CloseHandle(_event); +} + + +void NamedEventImpl::setImpl() +{ + if (!SetEvent(_event)) + throw SystemException("cannot signal named event", _name); +} + + +void NamedEventImpl::waitImpl() +{ + switch (WaitForSingleObject(_event, INFINITE)) + { + case WAIT_OBJECT_0: + return; + default: + throw SystemException("wait for named event failed", _name); + } +} + + +} // namespace Poco diff --git a/Foundation/src/NamedEvent_WIN32U.cpp b/Foundation/src/NamedEvent_WIN32U.cpp index 875a1343c..d85ece1eb 100644 --- a/Foundation/src/NamedEvent_WIN32U.cpp +++ b/Foundation/src/NamedEvent_WIN32U.cpp @@ -1,80 +1,80 @@ -// -// NamedEvent_WIN32.cpp -// -// $Id: //poco/1.2/Foundation/src/NamedEvent_WIN32U.cpp#1 $ -// -// Library: Foundation -// Package: Processes -// Module: NamedEvent -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/NamedEvent_WIN32U.h" -#include "Poco/Exception.h" -#include "Poco/UnicodeConverter.h" - - -namespace Poco { - - -NamedEventImpl::NamedEventImpl(const std::string& name): - _name(name) -{ - UnicodeConverter::toUTF16(_name, _uname); - _event = CreateEventW(NULL, FALSE, FALSE, _uname.c_str()); - if (!_event) - throw SystemException("cannot create named event", _name); -} - - -NamedEventImpl::~NamedEventImpl() -{ - CloseHandle(_event); -} - - -void NamedEventImpl::setImpl() -{ - if (!SetEvent(_event)) - throw SystemException("cannot signal named event", _name); -} - - -void NamedEventImpl::waitImpl() -{ - switch (WaitForSingleObject(_event, INFINITE)) - { - case WAIT_OBJECT_0: - return; - default: - throw SystemException("wait for named event failed", _name); - } -} - - -} // namespace Poco +// +// NamedEvent_WIN32.cpp +// +// $Id: //poco/1.2/Foundation/src/NamedEvent_WIN32U.cpp#1 $ +// +// Library: Foundation +// Package: Processes +// Module: NamedEvent +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/NamedEvent_WIN32U.h" +#include "Poco/Exception.h" +#include "Poco/UnicodeConverter.h" + + +namespace Poco { + + +NamedEventImpl::NamedEventImpl(const std::string& name): + _name(name) +{ + UnicodeConverter::toUTF16(_name, _uname); + _event = CreateEventW(NULL, FALSE, FALSE, _uname.c_str()); + if (!_event) + throw SystemException("cannot create named event", _name); +} + + +NamedEventImpl::~NamedEventImpl() +{ + CloseHandle(_event); +} + + +void NamedEventImpl::setImpl() +{ + if (!SetEvent(_event)) + throw SystemException("cannot signal named event", _name); +} + + +void NamedEventImpl::waitImpl() +{ + switch (WaitForSingleObject(_event, INFINITE)) + { + case WAIT_OBJECT_0: + return; + default: + throw SystemException("wait for named event failed", _name); + } +} + + +} // namespace Poco diff --git a/Foundation/src/NamedMutex.cpp b/Foundation/src/NamedMutex.cpp index 961439493..737c33cbb 100644 --- a/Foundation/src/NamedMutex.cpp +++ b/Foundation/src/NamedMutex.cpp @@ -1,65 +1,65 @@ -// -// NamedMutex.cpp -// -// $Id: //poco/1.2/Foundation/src/NamedMutex.cpp#1 $ -// -// Library: Foundation -// Package: Processes -// Module: NamedMutex -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/NamedMutex.h" - - -#if defined(POCO_OS_FAMILY_WINDOWS) && defined(POCO_WIN32_UTF8) -#include "NamedMutex_WIN32U.cpp" -#elif defined(POCO_OS_FAMILY_WINDOWS) -#include "NamedMutex_WIN32.cpp" -#elif defined(POCO_OS_FAMILY_UNIX) -#include "NamedMutex_UNIX.cpp" -#else -#include "NamedMutex_VMS.cpp" -#endif - - -namespace Poco { - - -NamedMutex::NamedMutex(const std::string& name): - NamedMutexImpl(name) -{ -} - - -NamedMutex::~NamedMutex() -{ -} - - -} // namespace Poco +// +// NamedMutex.cpp +// +// $Id: //poco/1.2/Foundation/src/NamedMutex.cpp#1 $ +// +// Library: Foundation +// Package: Processes +// Module: NamedMutex +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/NamedMutex.h" + + +#if defined(POCO_OS_FAMILY_WINDOWS) && defined(POCO_WIN32_UTF8) +#include "NamedMutex_WIN32U.cpp" +#elif defined(POCO_OS_FAMILY_WINDOWS) +#include "NamedMutex_WIN32.cpp" +#elif defined(POCO_OS_FAMILY_UNIX) +#include "NamedMutex_UNIX.cpp" +#else +#include "NamedMutex_VMS.cpp" +#endif + + +namespace Poco { + + +NamedMutex::NamedMutex(const std::string& name): + NamedMutexImpl(name) +{ +} + + +NamedMutex::~NamedMutex() +{ +} + + +} // namespace Poco diff --git a/Foundation/src/NamedMutex_UNIX.cpp b/Foundation/src/NamedMutex_UNIX.cpp index 5b91235e9..f7a5c1cf4 100644 --- a/Foundation/src/NamedMutex_UNIX.cpp +++ b/Foundation/src/NamedMutex_UNIX.cpp @@ -1,183 +1,183 @@ -// -// NamedMutex_UNIX.cpp -// -// $Id: //poco/1.2/Foundation/src/NamedMutex_UNIX.cpp#2 $ -// -// Library: Foundation -// Package: Processes -// Module: NamedMutex -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/NamedMutex_UNIX.h" -#include "Poco/Exception.h" -#include -#include -#include -#if defined(sun) || defined(__APPLE__) || defined(__osf__) -#include -#else -#include -#include -#include -#include -#endif - - -namespace Poco { - - -#if defined(linux) || defined(__CYGWIN__) - union semun - { - int val; - struct semid_ds* buf; - unsigned short int* array; - struct seminfo* __buf; - }; -#elif defined(hpux) - union semun - { - int val; - struct semid_ds* buf; - ushort* array; - }; -#endif - - -NamedMutexImpl::NamedMutexImpl(const std::string& name): - _name(name) -{ - std::string fileName = getFileName(); -#if defined(sun) || defined(__APPLE__) || defined(__osf__) || defined(__QNX__) - _sem = sem_open(fileName.c_str(), O_CREAT, S_IRWXU | S_IRWXG | S_IRWXO, 1); - if ((long) _sem == (long) SEM_FAILED) - throw SystemException("cannot create named mutex (sem_open() failed)", _name); -#else - int fd = open(fileName.c_str(), O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); - if (fd != -1) - close(fd); - else - throw SystemException("cannot create named mutex (lockfile)", _name); - key_t key = ftok(fileName.c_str(), 0); - if (key == -1) - throw SystemException("cannot create named mutex (ftok() failed)", _name); - _semid = semget(key, 1, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH | IPC_CREAT | IPC_EXCL); - if (_semid >= 0) - { - union semun arg; - arg.val = 1; - semctl(_semid, 0, SETVAL, arg); - } - else if (errno == EEXIST) - { - _semid = semget(key, 1, 0); - } - else throw SystemException("cannot create named mutex (semget() failed)", _name); -#endif // defined(sun) || defined(__APPLE__) || defined(__osf__) || defined(__QNX__) -} - - -NamedMutexImpl::~NamedMutexImpl() -{ -#if defined(sun) || defined(__APPLE__) || defined(__osf__) || defined(__QNX__) - sem_close(_sem); -#endif -} - - -void NamedMutexImpl::lockImpl() -{ -#if defined(sun) || defined(__APPLE__) || defined(__osf__) || defined(__QNX__) - int err; - do - { - err = sem_wait(_sem); - } - while (err && errno == EINTR); - if (err) throw SystemException("cannot lock named mutex", _name); -#else - struct sembuf op; - op.sem_num = 0; - op.sem_op = -1; - op.sem_flg = SEM_UNDO; - int err; - do - { - err = semop(_semid, &op, 1); - } - while (err && errno == EINTR); - if (err) throw SystemException("cannot lock named mutex", _name); -#endif -} - - -bool NamedMutexImpl::tryLockImpl() -{ -#if defined(sun) || defined(__APPLE__) || defined(__osf__) || defined(__QNX__) - return sem_trywait(_sem) == 0; -#else - struct sembuf op; - op.sem_num = 0; - op.sem_op = -1; - op.sem_flg = SEM_UNDO | IPC_NOWAIT; - return semop(_semid, &op, 1) == 0; -#endif -} - - -void NamedMutexImpl::unlockImpl() -{ -#if defined(sun) || defined(__APPLE__) || defined(__osf__) || defined(__QNX__) - if (sem_post(_sem) != 0) - throw SystemException("cannot unlock named mutex", _name); -#else - struct sembuf op; - op.sem_num = 0; - op.sem_op = 1; - op.sem_flg = SEM_UNDO; - if (semop(_semid, &op, 1) != 0) - throw SystemException("cannot unlock named mutex", _name); -#endif -} - - -std::string NamedMutexImpl::getFileName() -{ -#if defined(sun) || defined(__APPLE__) || defined(__QNX__) - std::string fn = "/"; -#else - std::string fn = "/tmp/"; -#endif - fn.append(_name); - fn.append(".mutex"); - return fn; -} - - -} // namespace Poco +// +// NamedMutex_UNIX.cpp +// +// $Id: //poco/1.2/Foundation/src/NamedMutex_UNIX.cpp#2 $ +// +// Library: Foundation +// Package: Processes +// Module: NamedMutex +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/NamedMutex_UNIX.h" +#include "Poco/Exception.h" +#include +#include +#include +#if defined(sun) || defined(__APPLE__) || defined(__osf__) +#include +#else +#include +#include +#include +#include +#endif + + +namespace Poco { + + +#if defined(linux) || defined(__CYGWIN__) + union semun + { + int val; + struct semid_ds* buf; + unsigned short int* array; + struct seminfo* __buf; + }; +#elif defined(hpux) + union semun + { + int val; + struct semid_ds* buf; + ushort* array; + }; +#endif + + +NamedMutexImpl::NamedMutexImpl(const std::string& name): + _name(name) +{ + std::string fileName = getFileName(); +#if defined(sun) || defined(__APPLE__) || defined(__osf__) || defined(__QNX__) + _sem = sem_open(fileName.c_str(), O_CREAT, S_IRWXU | S_IRWXG | S_IRWXO, 1); + if ((long) _sem == (long) SEM_FAILED) + throw SystemException("cannot create named mutex (sem_open() failed)", _name); +#else + int fd = open(fileName.c_str(), O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); + if (fd != -1) + close(fd); + else + throw SystemException("cannot create named mutex (lockfile)", _name); + key_t key = ftok(fileName.c_str(), 0); + if (key == -1) + throw SystemException("cannot create named mutex (ftok() failed)", _name); + _semid = semget(key, 1, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH | IPC_CREAT | IPC_EXCL); + if (_semid >= 0) + { + union semun arg; + arg.val = 1; + semctl(_semid, 0, SETVAL, arg); + } + else if (errno == EEXIST) + { + _semid = semget(key, 1, 0); + } + else throw SystemException("cannot create named mutex (semget() failed)", _name); +#endif // defined(sun) || defined(__APPLE__) || defined(__osf__) || defined(__QNX__) +} + + +NamedMutexImpl::~NamedMutexImpl() +{ +#if defined(sun) || defined(__APPLE__) || defined(__osf__) || defined(__QNX__) + sem_close(_sem); +#endif +} + + +void NamedMutexImpl::lockImpl() +{ +#if defined(sun) || defined(__APPLE__) || defined(__osf__) || defined(__QNX__) + int err; + do + { + err = sem_wait(_sem); + } + while (err && errno == EINTR); + if (err) throw SystemException("cannot lock named mutex", _name); +#else + struct sembuf op; + op.sem_num = 0; + op.sem_op = -1; + op.sem_flg = SEM_UNDO; + int err; + do + { + err = semop(_semid, &op, 1); + } + while (err && errno == EINTR); + if (err) throw SystemException("cannot lock named mutex", _name); +#endif +} + + +bool NamedMutexImpl::tryLockImpl() +{ +#if defined(sun) || defined(__APPLE__) || defined(__osf__) || defined(__QNX__) + return sem_trywait(_sem) == 0; +#else + struct sembuf op; + op.sem_num = 0; + op.sem_op = -1; + op.sem_flg = SEM_UNDO | IPC_NOWAIT; + return semop(_semid, &op, 1) == 0; +#endif +} + + +void NamedMutexImpl::unlockImpl() +{ +#if defined(sun) || defined(__APPLE__) || defined(__osf__) || defined(__QNX__) + if (sem_post(_sem) != 0) + throw SystemException("cannot unlock named mutex", _name); +#else + struct sembuf op; + op.sem_num = 0; + op.sem_op = 1; + op.sem_flg = SEM_UNDO; + if (semop(_semid, &op, 1) != 0) + throw SystemException("cannot unlock named mutex", _name); +#endif +} + + +std::string NamedMutexImpl::getFileName() +{ +#if defined(sun) || defined(__APPLE__) || defined(__QNX__) + std::string fn = "/"; +#else + std::string fn = "/tmp/"; +#endif + fn.append(_name); + fn.append(".mutex"); + return fn; +} + + +} // namespace Poco diff --git a/Foundation/src/NamedMutex_VMS.cpp b/Foundation/src/NamedMutex_VMS.cpp index ddad77b83..c1a460db8 100644 --- a/Foundation/src/NamedMutex_VMS.cpp +++ b/Foundation/src/NamedMutex_VMS.cpp @@ -1,87 +1,87 @@ -// -// NamedMutex_VMS.cpp -// -// $Id: //poco/1.2/Foundation/src/NamedMutex_VMS.cpp#1 $ -// -// Library: Foundation -// Package: Processes -// Module: NamedMutex -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/NamedMutex_VMS.h" -#include -#include - - -namespace Poco { - - -NamedMutexImpl::NamedMutexImpl(const std::string& name): - _name(name) -{ - _nameDesc.dsc$w_length = _name.length(); - _nameDesc.dsc$b_dtype = DSC$K_DTYPE_T; - _nameDesc.dsc$b_class = DSC$K_CLASS_S; - _nameDesc.dsc$a_pointer = _name.data(); - int status = sys$enqw(0, LCK$K_NLMODE, (struct _lksb*) &_lksb, 0, &_nameDesc, 0, 0, 0, 0, 0, 0); - if (status != 1) - throw SystemException("cannot create named mutex", _name); -} - - -NamedMutexImpl::~NamedMutexImpl() -{ - sys$deq(m_lksb[1], 0, 0, 0); -} - - -void NamedMutexImpl::lockImpl() -{ - int status = sys$enqw(0, LCK$K_EXMODE, (struct _lksb*) &_lksb, LCK$M_CONVERT, &_nameDesc, 0, 0, 0, 0, 0, 0); - if (status != 1) - throw SystemException("cannot lock named mutex", _name); -} - - -bool NamedMutexImpl::tryLockImpl() -{ - int status = sys$enqw(0, LCK$K_EXMODE, (struct _lksb*) &_lksb, LCK$M_CONVERT | LCK$M_NOQUEUE, &_nameDesc, 0, 0, 0, 0, 0, 0); - return status == 1; -} - - -void NamedMutexImpl::unlockImpl() -{ - int status = sys$enqw(0, LCK$K_NLMODE, (struct _lksb*) &_lksb, LCK$M_CONVERT, &_nameDesc, 0, 0, 0, 0, 0, 0); - if (status != 1) - throw SystemException("cannot unlock named mutex", _name); -} - - -} // namespace Poco +// +// NamedMutex_VMS.cpp +// +// $Id: //poco/1.2/Foundation/src/NamedMutex_VMS.cpp#1 $ +// +// Library: Foundation +// Package: Processes +// Module: NamedMutex +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/NamedMutex_VMS.h" +#include +#include + + +namespace Poco { + + +NamedMutexImpl::NamedMutexImpl(const std::string& name): + _name(name) +{ + _nameDesc.dsc$w_length = _name.length(); + _nameDesc.dsc$b_dtype = DSC$K_DTYPE_T; + _nameDesc.dsc$b_class = DSC$K_CLASS_S; + _nameDesc.dsc$a_pointer = _name.data(); + int status = sys$enqw(0, LCK$K_NLMODE, (struct _lksb*) &_lksb, 0, &_nameDesc, 0, 0, 0, 0, 0, 0); + if (status != 1) + throw SystemException("cannot create named mutex", _name); +} + + +NamedMutexImpl::~NamedMutexImpl() +{ + sys$deq(m_lksb[1], 0, 0, 0); +} + + +void NamedMutexImpl::lockImpl() +{ + int status = sys$enqw(0, LCK$K_EXMODE, (struct _lksb*) &_lksb, LCK$M_CONVERT, &_nameDesc, 0, 0, 0, 0, 0, 0); + if (status != 1) + throw SystemException("cannot lock named mutex", _name); +} + + +bool NamedMutexImpl::tryLockImpl() +{ + int status = sys$enqw(0, LCK$K_EXMODE, (struct _lksb*) &_lksb, LCK$M_CONVERT | LCK$M_NOQUEUE, &_nameDesc, 0, 0, 0, 0, 0, 0); + return status == 1; +} + + +void NamedMutexImpl::unlockImpl() +{ + int status = sys$enqw(0, LCK$K_NLMODE, (struct _lksb*) &_lksb, LCK$M_CONVERT, &_nameDesc, 0, 0, 0, 0, 0, 0); + if (status != 1) + throw SystemException("cannot unlock named mutex", _name); +} + + +} // namespace Poco diff --git a/Foundation/src/NamedMutex_WIN32.cpp b/Foundation/src/NamedMutex_WIN32.cpp index be23e92e2..3daf0a871 100644 --- a/Foundation/src/NamedMutex_WIN32.cpp +++ b/Foundation/src/NamedMutex_WIN32.cpp @@ -1,95 +1,95 @@ -// -// NamedMutex_WIN32.cpp -// -// $Id: //poco/1.2/Foundation/src/NamedMutex_WIN32.cpp#1 $ -// -// Library: Foundation -// Package: Processes -// Module: NamedMutex -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/NamedMutex_WIN32.h" -#include "Poco/Exception.h" - - -namespace Poco { - - -NamedMutexImpl::NamedMutexImpl(const std::string& name): - _name(name) -{ - _mutex = CreateMutex(NULL, FALSE, _name.c_str()); - if (!_mutex) - throw SystemException("cannot create named mutex", _name); -} - - -NamedMutexImpl::~NamedMutexImpl() -{ - CloseHandle(_mutex); -} - - -void NamedMutexImpl::lockImpl() -{ - switch (WaitForSingleObject(_mutex, INFINITE)) - { - case WAIT_OBJECT_0: - return; - case WAIT_ABANDONED: - throw SystemException("cannot lock named mutex (abadoned)", _name); - default: - throw SystemException("cannot lock named mutex", _name); - } -} - - -bool NamedMutexImpl::tryLockImpl() -{ - switch (WaitForSingleObject(_mutex, 0)) - { - case WAIT_OBJECT_0: - return true; - case WAIT_TIMEOUT: - return false; - case WAIT_ABANDONED: - throw SystemException("cannot lock named mutex (abadoned)", _name); - default: - throw SystemException("cannot lock named mutex", _name); - } -} - - -void NamedMutexImpl::unlockImpl() -{ - ReleaseMutex(_mutex); -} - - -} // namespace Poco +// +// NamedMutex_WIN32.cpp +// +// $Id: //poco/1.2/Foundation/src/NamedMutex_WIN32.cpp#1 $ +// +// Library: Foundation +// Package: Processes +// Module: NamedMutex +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/NamedMutex_WIN32.h" +#include "Poco/Exception.h" + + +namespace Poco { + + +NamedMutexImpl::NamedMutexImpl(const std::string& name): + _name(name) +{ + _mutex = CreateMutex(NULL, FALSE, _name.c_str()); + if (!_mutex) + throw SystemException("cannot create named mutex", _name); +} + + +NamedMutexImpl::~NamedMutexImpl() +{ + CloseHandle(_mutex); +} + + +void NamedMutexImpl::lockImpl() +{ + switch (WaitForSingleObject(_mutex, INFINITE)) + { + case WAIT_OBJECT_0: + return; + case WAIT_ABANDONED: + throw SystemException("cannot lock named mutex (abadoned)", _name); + default: + throw SystemException("cannot lock named mutex", _name); + } +} + + +bool NamedMutexImpl::tryLockImpl() +{ + switch (WaitForSingleObject(_mutex, 0)) + { + case WAIT_OBJECT_0: + return true; + case WAIT_TIMEOUT: + return false; + case WAIT_ABANDONED: + throw SystemException("cannot lock named mutex (abadoned)", _name); + default: + throw SystemException("cannot lock named mutex", _name); + } +} + + +void NamedMutexImpl::unlockImpl() +{ + ReleaseMutex(_mutex); +} + + +} // namespace Poco diff --git a/Foundation/src/NamedMutex_WIN32U.cpp b/Foundation/src/NamedMutex_WIN32U.cpp index 7d1a9819b..7229d58d2 100644 --- a/Foundation/src/NamedMutex_WIN32U.cpp +++ b/Foundation/src/NamedMutex_WIN32U.cpp @@ -1,97 +1,97 @@ -// -// NamedMutex_WIN32.cpp -// -// $Id: //poco/1.2/Foundation/src/NamedMutex_WIN32U.cpp#1 $ -// -// Library: Foundation -// Package: Processes -// Module: NamedMutex -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/NamedMutex_WIN32U.h" -#include "Poco/Exception.h" -#include "Poco/UnicodeConverter.h" - - -namespace Poco { - - -NamedMutexImpl::NamedMutexImpl(const std::string& name): - _name(name) -{ - UnicodeConverter::toUTF16(_name, _uname); - _mutex = CreateMutexW(NULL, FALSE, _uname.c_str()); - if (!_mutex) - throw SystemException("cannot create named mutex", _name); -} - - -NamedMutexImpl::~NamedMutexImpl() -{ - CloseHandle(_mutex); -} - - -void NamedMutexImpl::lockImpl() -{ - switch (WaitForSingleObject(_mutex, INFINITE)) - { - case WAIT_OBJECT_0: - return; - case WAIT_ABANDONED: - throw SystemException("cannot lock named mutex (abadoned)", _name); - default: - throw SystemException("cannot lock named mutex", _name); - } -} - - -bool NamedMutexImpl::tryLockImpl() -{ - switch (WaitForSingleObject(_mutex, 0)) - { - case WAIT_OBJECT_0: - return true; - case WAIT_TIMEOUT: - return false; - case WAIT_ABANDONED: - throw SystemException("cannot lock named mutex (abadoned)", _name); - default: - throw SystemException("cannot lock named mutex", _name); - } -} - - -void NamedMutexImpl::unlockImpl() -{ - ReleaseMutex(_mutex); -} - - -} // namespace Poco +// +// NamedMutex_WIN32.cpp +// +// $Id: //poco/1.2/Foundation/src/NamedMutex_WIN32U.cpp#1 $ +// +// Library: Foundation +// Package: Processes +// Module: NamedMutex +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/NamedMutex_WIN32U.h" +#include "Poco/Exception.h" +#include "Poco/UnicodeConverter.h" + + +namespace Poco { + + +NamedMutexImpl::NamedMutexImpl(const std::string& name): + _name(name) +{ + UnicodeConverter::toUTF16(_name, _uname); + _mutex = CreateMutexW(NULL, FALSE, _uname.c_str()); + if (!_mutex) + throw SystemException("cannot create named mutex", _name); +} + + +NamedMutexImpl::~NamedMutexImpl() +{ + CloseHandle(_mutex); +} + + +void NamedMutexImpl::lockImpl() +{ + switch (WaitForSingleObject(_mutex, INFINITE)) + { + case WAIT_OBJECT_0: + return; + case WAIT_ABANDONED: + throw SystemException("cannot lock named mutex (abadoned)", _name); + default: + throw SystemException("cannot lock named mutex", _name); + } +} + + +bool NamedMutexImpl::tryLockImpl() +{ + switch (WaitForSingleObject(_mutex, 0)) + { + case WAIT_OBJECT_0: + return true; + case WAIT_TIMEOUT: + return false; + case WAIT_ABANDONED: + throw SystemException("cannot lock named mutex (abadoned)", _name); + default: + throw SystemException("cannot lock named mutex", _name); + } +} + + +void NamedMutexImpl::unlockImpl() +{ + ReleaseMutex(_mutex); +} + + +} // namespace Poco diff --git a/Foundation/src/NestedDiagnosticContext.cpp b/Foundation/src/NestedDiagnosticContext.cpp index cd202fba0..e39b44afa 100644 --- a/Foundation/src/NestedDiagnosticContext.cpp +++ b/Foundation/src/NestedDiagnosticContext.cpp @@ -1,146 +1,146 @@ -// -// NestedDiagnosticContext.cpp -// -// $Id: //poco/1.2/Foundation/src/NestedDiagnosticContext.cpp#1 $ -// -// Library: Foundation -// Package: Core -// Module: NestedDiagnosticContext -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/NestedDiagnosticContext.h" -#include "Poco/SingletonHolder.h" -#include "Poco/ThreadLocal.h" - - -namespace Poco { - - -NestedDiagnosticContext::NestedDiagnosticContext() -{ -} - - -NestedDiagnosticContext::NestedDiagnosticContext(const NestedDiagnosticContext& ctx) -{ - _stack = ctx._stack; -} - - -NestedDiagnosticContext::~NestedDiagnosticContext() -{ -} - - -NestedDiagnosticContext& NestedDiagnosticContext::operator = (const NestedDiagnosticContext& ctx) -{ - if (&ctx != this) - _stack = ctx._stack; - return *this; -} - - -void NestedDiagnosticContext::push(const std::string& info) -{ - Context ctx; - ctx.info = info; - ctx.line = -1; - ctx.file = 0; - _stack.push_back(ctx); -} - - -void NestedDiagnosticContext::push(const std::string& info, int line, const char* filename) -{ - Context ctx; - ctx.info = info; - ctx.line = line; - ctx.file = filename; - _stack.push_back(ctx); -} - - -void NestedDiagnosticContext::pop() -{ - if (!_stack.empty()) - _stack.pop_back(); -} - - -int NestedDiagnosticContext::depth() const -{ - return int(_stack.size()); -} - - -std::string NestedDiagnosticContext::toString() const -{ - std::string result; - for (Stack::const_iterator it = _stack.begin(); it != _stack.end(); ++it) - { - if (!result.empty()) - result.append(":"); - result.append(it->info); - } - return result; -} - - -void NestedDiagnosticContext::dump(std::ostream& ostr) const -{ - dump(ostr, "\n"); -} - - -void NestedDiagnosticContext::dump(std::ostream& ostr, const std::string& delimiter) const -{ - for (Stack::const_iterator it = _stack.begin(); it != _stack.end(); ++it) - { - ostr << it->info; - if (it->file) - ostr << " (in \"" << it->file << "\", line " << it->line << ")"; - ostr << delimiter; - } -} - - -void NestedDiagnosticContext::clear() -{ - _stack.clear(); -} - - -NestedDiagnosticContext& NestedDiagnosticContext::current() -{ - static ThreadLocal ndc; - return ndc.get(); -} - - -} // namespace Poco +// +// NestedDiagnosticContext.cpp +// +// $Id: //poco/1.2/Foundation/src/NestedDiagnosticContext.cpp#1 $ +// +// Library: Foundation +// Package: Core +// Module: NestedDiagnosticContext +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/NestedDiagnosticContext.h" +#include "Poco/SingletonHolder.h" +#include "Poco/ThreadLocal.h" + + +namespace Poco { + + +NestedDiagnosticContext::NestedDiagnosticContext() +{ +} + + +NestedDiagnosticContext::NestedDiagnosticContext(const NestedDiagnosticContext& ctx) +{ + _stack = ctx._stack; +} + + +NestedDiagnosticContext::~NestedDiagnosticContext() +{ +} + + +NestedDiagnosticContext& NestedDiagnosticContext::operator = (const NestedDiagnosticContext& ctx) +{ + if (&ctx != this) + _stack = ctx._stack; + return *this; +} + + +void NestedDiagnosticContext::push(const std::string& info) +{ + Context ctx; + ctx.info = info; + ctx.line = -1; + ctx.file = 0; + _stack.push_back(ctx); +} + + +void NestedDiagnosticContext::push(const std::string& info, int line, const char* filename) +{ + Context ctx; + ctx.info = info; + ctx.line = line; + ctx.file = filename; + _stack.push_back(ctx); +} + + +void NestedDiagnosticContext::pop() +{ + if (!_stack.empty()) + _stack.pop_back(); +} + + +int NestedDiagnosticContext::depth() const +{ + return int(_stack.size()); +} + + +std::string NestedDiagnosticContext::toString() const +{ + std::string result; + for (Stack::const_iterator it = _stack.begin(); it != _stack.end(); ++it) + { + if (!result.empty()) + result.append(":"); + result.append(it->info); + } + return result; +} + + +void NestedDiagnosticContext::dump(std::ostream& ostr) const +{ + dump(ostr, "\n"); +} + + +void NestedDiagnosticContext::dump(std::ostream& ostr, const std::string& delimiter) const +{ + for (Stack::const_iterator it = _stack.begin(); it != _stack.end(); ++it) + { + ostr << it->info; + if (it->file) + ostr << " (in \"" << it->file << "\", line " << it->line << ")"; + ostr << delimiter; + } +} + + +void NestedDiagnosticContext::clear() +{ + _stack.clear(); +} + + +NestedDiagnosticContext& NestedDiagnosticContext::current() +{ + static ThreadLocal ndc; + return ndc.get(); +} + + +} // namespace Poco diff --git a/Foundation/src/Notification.cpp b/Foundation/src/Notification.cpp index d36b8ae1f..df4af154e 100644 --- a/Foundation/src/Notification.cpp +++ b/Foundation/src/Notification.cpp @@ -1,60 +1,60 @@ -// -// Notification.cpp -// -// $Id: //poco/1.2/Foundation/src/Notification.cpp#1 $ -// -// Library: Foundation -// Package: Notifications -// Module: Notification -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/Notification.h" -#include - - -namespace Poco { - - -Notification::Notification() -{ -} - - -Notification::~Notification() -{ -} - - -std::string Notification::name() const -{ - return typeid(*this).name(); -} - - -} // namespace Poco +// +// Notification.cpp +// +// $Id: //poco/1.2/Foundation/src/Notification.cpp#1 $ +// +// Library: Foundation +// Package: Notifications +// Module: Notification +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/Notification.h" +#include + + +namespace Poco { + + +Notification::Notification() +{ +} + + +Notification::~Notification() +{ +} + + +std::string Notification::name() const +{ + return typeid(*this).name(); +} + + +} // namespace Poco diff --git a/Foundation/src/NotificationCenter.cpp b/Foundation/src/NotificationCenter.cpp index 5e1ca8a29..a3d22b81c 100644 --- a/Foundation/src/NotificationCenter.cpp +++ b/Foundation/src/NotificationCenter.cpp @@ -1,126 +1,126 @@ -// -// NotificationCenter.cpp -// -// $Id: //poco/1.2/Foundation/src/NotificationCenter.cpp#2 $ -// -// Library: Foundation -// Package: Notifications -// Module: NotificationCenter -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/NotificationCenter.h" -#include "Poco/Notification.h" -#include "Poco/Observer.h" -#include "Poco/AutoPtr.h" -#include "Poco/SingletonHolder.h" - - -namespace Poco { - - -NotificationCenter::NotificationCenter() -{ -} - - -NotificationCenter::~NotificationCenter() -{ - for (ObserverList::iterator it = _observers.begin(); it != _observers.end(); ++it) - { - delete *it; - } -} - - -void NotificationCenter::addObserver(const AbstractObserver& observer) -{ - Mutex::ScopedLock lock(_mutex); - _observers.push_front(observer.clone()); -} - - -void NotificationCenter::removeObserver(const AbstractObserver& observer) -{ - Mutex::ScopedLock lock(_mutex); - for (ObserverList::iterator it = _observers.begin(); it != _observers.end(); ++it) - { - if (*it && observer.equals(**it)) - { - delete *it; - *it = 0; - return; - } - } -} - - -void NotificationCenter::postNotification(Notification* pNotification) -{ - poco_check_ptr (pNotification); - - Mutex::ScopedLock lock(_mutex); - AutoPtr pNf = pNotification; - ObserverList::iterator it = _observers.begin(); - while (it != _observers.end()) - { - ObserverList::iterator cur = it++; - if (*cur) - { - (*cur)->notify(pNotification); - } - else - { - _observers.erase(cur); - } - } -} - - -bool NotificationCenter::hasObservers() const -{ - Mutex::ScopedLock lock(_mutex); - - ObserverList::const_iterator it = _observers.begin(); - while (it != _observers.end()) - { - if (*it) return true; - ++it; - } - return false; -} - - -NotificationCenter& NotificationCenter::defaultCenter() -{ - static SingletonHolder sh; - return *sh.get(); -} - - -} // namespace Poco +// +// NotificationCenter.cpp +// +// $Id: //poco/1.2/Foundation/src/NotificationCenter.cpp#2 $ +// +// Library: Foundation +// Package: Notifications +// Module: NotificationCenter +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/NotificationCenter.h" +#include "Poco/Notification.h" +#include "Poco/Observer.h" +#include "Poco/AutoPtr.h" +#include "Poco/SingletonHolder.h" + + +namespace Poco { + + +NotificationCenter::NotificationCenter() +{ +} + + +NotificationCenter::~NotificationCenter() +{ + for (ObserverList::iterator it = _observers.begin(); it != _observers.end(); ++it) + { + delete *it; + } +} + + +void NotificationCenter::addObserver(const AbstractObserver& observer) +{ + Mutex::ScopedLock lock(_mutex); + _observers.push_front(observer.clone()); +} + + +void NotificationCenter::removeObserver(const AbstractObserver& observer) +{ + Mutex::ScopedLock lock(_mutex); + for (ObserverList::iterator it = _observers.begin(); it != _observers.end(); ++it) + { + if (*it && observer.equals(**it)) + { + delete *it; + *it = 0; + return; + } + } +} + + +void NotificationCenter::postNotification(Notification* pNotification) +{ + poco_check_ptr (pNotification); + + Mutex::ScopedLock lock(_mutex); + AutoPtr pNf = pNotification; + ObserverList::iterator it = _observers.begin(); + while (it != _observers.end()) + { + ObserverList::iterator cur = it++; + if (*cur) + { + (*cur)->notify(pNotification); + } + else + { + _observers.erase(cur); + } + } +} + + +bool NotificationCenter::hasObservers() const +{ + Mutex::ScopedLock lock(_mutex); + + ObserverList::const_iterator it = _observers.begin(); + while (it != _observers.end()) + { + if (*it) return true; + ++it; + } + return false; +} + + +NotificationCenter& NotificationCenter::defaultCenter() +{ + static SingletonHolder sh; + return *sh.get(); +} + + +} // namespace Poco diff --git a/Foundation/src/NotificationQueue.cpp b/Foundation/src/NotificationQueue.cpp index e84a2cb22..e99d8f7d2 100644 --- a/Foundation/src/NotificationQueue.cpp +++ b/Foundation/src/NotificationQueue.cpp @@ -1,227 +1,227 @@ -// -// NotificationQueue.cpp -// -// $Id: //poco/1.2/Foundation/src/NotificationQueue.cpp#1 $ -// -// Library: Foundation -// Package: Notifications -// Module: NotificationQueue -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/NotificationQueue.h" -#include "Poco/NotificationCenter.h" -#include "Poco/Notification.h" -#include "Poco/SingletonHolder.h" - - -namespace Poco { - - -NotificationQueue::NotificationQueue() -{ -} - - -NotificationQueue::~NotificationQueue() -{ - clear(); -} - - -void NotificationQueue::enqueueNotification(Notification* pNotification) -{ - poco_check_ptr (pNotification); - FastMutex::ScopedLock lock(_mutex); - if (_waitQueue.empty()) - { - _nfQueue.push_back(pNotification); - } - else - { - WaitInfo* pWI = _waitQueue.front(); - _waitQueue.pop_front(); - pWI->pNf = pNotification; - pWI->nfAvailable.set(); - } -} - - -void NotificationQueue::enqueueUrgentNotification(Notification* pNotification) -{ - poco_check_ptr (pNotification); - FastMutex::ScopedLock lock(_mutex); - if (_waitQueue.empty()) - { - _nfQueue.push_front(pNotification); - } - else - { - WaitInfo* pWI = _waitQueue.front(); - _waitQueue.pop_front(); - pWI->pNf = pNotification; - pWI->nfAvailable.set(); - } -} - - -Notification* NotificationQueue::dequeueNotification() -{ - FastMutex::ScopedLock lock(_mutex); - return dequeueOne(); -} - - -Notification* NotificationQueue::waitDequeueNotification() -{ - Notification* pNf = 0; - WaitInfo* pWI = 0; - { - FastMutex::ScopedLock lock(_mutex); - pNf = dequeueOne(); - if (pNf) return pNf; - pWI = new WaitInfo; - pWI->pNf = 0; - _waitQueue.push_back(pWI); - } - pWI->nfAvailable.wait(); - pNf = pWI->pNf; - delete pWI; - return pNf; -} - - -Notification* NotificationQueue::waitDequeueNotification(long milliseconds) -{ - Notification* pNf = 0; - WaitInfo* pWI = 0; - { - FastMutex::ScopedLock lock(_mutex); - pNf = dequeueOne(); - if (pNf) return pNf; - pWI = new WaitInfo; - pWI->pNf = 0; - _waitQueue.push_back(pWI); - } - if (pWI->nfAvailable.tryWait(milliseconds)) - { - pNf = pWI->pNf; - } - else - { - FastMutex::ScopedLock lock(_mutex); - pNf = pWI->pNf; - for (WaitQueue::iterator it = _waitQueue.begin(); it != _waitQueue.end(); ++it) - { - if (*it == pWI) - { - _waitQueue.erase(it); - break; - } - } - } - delete pWI; - return pNf; -} - - -void NotificationQueue::dispatch(NotificationCenter& notificationCenter) -{ - FastMutex::ScopedLock lock(_mutex); - Notification* pNf = dequeueOne(); - while (pNf) - { - notificationCenter.postNotification(pNf); - pNf = dequeueOne(); - } -} - - -void NotificationQueue::wakeUpAll() -{ - FastMutex::ScopedLock lock(_mutex); - for (WaitQueue::iterator it = _waitQueue.begin(); it != _waitQueue.end(); ++it) - { - (*it)->nfAvailable.set(); - } - _waitQueue.clear(); -} - - -bool NotificationQueue::empty() const -{ - FastMutex::ScopedLock lock(_mutex); - return _nfQueue.empty(); -} - - -int NotificationQueue::size() const -{ - FastMutex::ScopedLock lock(_mutex); - return int(_nfQueue.size()); -} - - -void NotificationQueue::clear() -{ - FastMutex::ScopedLock lock(_mutex); - for (NfQueue::iterator it = _nfQueue.begin(); it != _nfQueue.end(); ++it) - { - (*it)->release(); - } - _nfQueue.clear(); -} - - -bool NotificationQueue::hasIdleThreads() const -{ - FastMutex::ScopedLock lock(_mutex); - return !_waitQueue.empty(); -} - - -Notification* NotificationQueue::dequeueOne() -{ - Notification* pNf = 0; - if (!_nfQueue.empty()) - { - pNf = _nfQueue.front(); - _nfQueue.pop_front(); - } - return pNf; -} - - -NotificationQueue& NotificationQueue::defaultQueue() -{ - static SingletonHolder sh; - return *sh.get(); -} - - -} // namespace Poco +// +// NotificationQueue.cpp +// +// $Id: //poco/1.2/Foundation/src/NotificationQueue.cpp#1 $ +// +// Library: Foundation +// Package: Notifications +// Module: NotificationQueue +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/NotificationQueue.h" +#include "Poco/NotificationCenter.h" +#include "Poco/Notification.h" +#include "Poco/SingletonHolder.h" + + +namespace Poco { + + +NotificationQueue::NotificationQueue() +{ +} + + +NotificationQueue::~NotificationQueue() +{ + clear(); +} + + +void NotificationQueue::enqueueNotification(Notification* pNotification) +{ + poco_check_ptr (pNotification); + FastMutex::ScopedLock lock(_mutex); + if (_waitQueue.empty()) + { + _nfQueue.push_back(pNotification); + } + else + { + WaitInfo* pWI = _waitQueue.front(); + _waitQueue.pop_front(); + pWI->pNf = pNotification; + pWI->nfAvailable.set(); + } +} + + +void NotificationQueue::enqueueUrgentNotification(Notification* pNotification) +{ + poco_check_ptr (pNotification); + FastMutex::ScopedLock lock(_mutex); + if (_waitQueue.empty()) + { + _nfQueue.push_front(pNotification); + } + else + { + WaitInfo* pWI = _waitQueue.front(); + _waitQueue.pop_front(); + pWI->pNf = pNotification; + pWI->nfAvailable.set(); + } +} + + +Notification* NotificationQueue::dequeueNotification() +{ + FastMutex::ScopedLock lock(_mutex); + return dequeueOne(); +} + + +Notification* NotificationQueue::waitDequeueNotification() +{ + Notification* pNf = 0; + WaitInfo* pWI = 0; + { + FastMutex::ScopedLock lock(_mutex); + pNf = dequeueOne(); + if (pNf) return pNf; + pWI = new WaitInfo; + pWI->pNf = 0; + _waitQueue.push_back(pWI); + } + pWI->nfAvailable.wait(); + pNf = pWI->pNf; + delete pWI; + return pNf; +} + + +Notification* NotificationQueue::waitDequeueNotification(long milliseconds) +{ + Notification* pNf = 0; + WaitInfo* pWI = 0; + { + FastMutex::ScopedLock lock(_mutex); + pNf = dequeueOne(); + if (pNf) return pNf; + pWI = new WaitInfo; + pWI->pNf = 0; + _waitQueue.push_back(pWI); + } + if (pWI->nfAvailable.tryWait(milliseconds)) + { + pNf = pWI->pNf; + } + else + { + FastMutex::ScopedLock lock(_mutex); + pNf = pWI->pNf; + for (WaitQueue::iterator it = _waitQueue.begin(); it != _waitQueue.end(); ++it) + { + if (*it == pWI) + { + _waitQueue.erase(it); + break; + } + } + } + delete pWI; + return pNf; +} + + +void NotificationQueue::dispatch(NotificationCenter& notificationCenter) +{ + FastMutex::ScopedLock lock(_mutex); + Notification* pNf = dequeueOne(); + while (pNf) + { + notificationCenter.postNotification(pNf); + pNf = dequeueOne(); + } +} + + +void NotificationQueue::wakeUpAll() +{ + FastMutex::ScopedLock lock(_mutex); + for (WaitQueue::iterator it = _waitQueue.begin(); it != _waitQueue.end(); ++it) + { + (*it)->nfAvailable.set(); + } + _waitQueue.clear(); +} + + +bool NotificationQueue::empty() const +{ + FastMutex::ScopedLock lock(_mutex); + return _nfQueue.empty(); +} + + +int NotificationQueue::size() const +{ + FastMutex::ScopedLock lock(_mutex); + return int(_nfQueue.size()); +} + + +void NotificationQueue::clear() +{ + FastMutex::ScopedLock lock(_mutex); + for (NfQueue::iterator it = _nfQueue.begin(); it != _nfQueue.end(); ++it) + { + (*it)->release(); + } + _nfQueue.clear(); +} + + +bool NotificationQueue::hasIdleThreads() const +{ + FastMutex::ScopedLock lock(_mutex); + return !_waitQueue.empty(); +} + + +Notification* NotificationQueue::dequeueOne() +{ + Notification* pNf = 0; + if (!_nfQueue.empty()) + { + pNf = _nfQueue.front(); + _nfQueue.pop_front(); + } + return pNf; +} + + +NotificationQueue& NotificationQueue::defaultQueue() +{ + static SingletonHolder sh; + return *sh.get(); +} + + +} // namespace Poco diff --git a/Foundation/src/NullChannel.cpp b/Foundation/src/NullChannel.cpp index 2dc2c9056..a8b84c5a6 100644 --- a/Foundation/src/NullChannel.cpp +++ b/Foundation/src/NullChannel.cpp @@ -1,63 +1,63 @@ -// -// NullChannel.cpp -// -// $Id: //poco/1.2/Foundation/src/NullChannel.cpp#1 $ -// -// Library: Foundation -// Package: Logging -// Module: NullChannel -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/NullChannel.h" - - -namespace Poco { - - -NullChannel::NullChannel() -{ -} - - -NullChannel::~NullChannel() -{ -} - - -void NullChannel::log(const Message&) -{ -} - - -void NullChannel::setProperty(const std::string&, const std::string&) -{ -} - - -} // namespace Poco +// +// NullChannel.cpp +// +// $Id: //poco/1.2/Foundation/src/NullChannel.cpp#1 $ +// +// Library: Foundation +// Package: Logging +// Module: NullChannel +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/NullChannel.h" + + +namespace Poco { + + +NullChannel::NullChannel() +{ +} + + +NullChannel::~NullChannel() +{ +} + + +void NullChannel::log(const Message&) +{ +} + + +void NullChannel::setProperty(const std::string&, const std::string&) +{ +} + + +} // namespace Poco diff --git a/Foundation/src/NullStream.cpp b/Foundation/src/NullStream.cpp index 28bf3f81d..c45456678 100644 --- a/Foundation/src/NullStream.cpp +++ b/Foundation/src/NullStream.cpp @@ -1,96 +1,96 @@ -// -// NullStream.cpp -// -// $Id: //poco/1.2/Foundation/src/NullStream.cpp#1 $ -// -// Library: Foundation -// Package: Streams -// Module: NullStream -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/NullStream.h" - - -namespace Poco { - - -NullStreamBuf::NullStreamBuf() -{ -} - - -NullStreamBuf::~NullStreamBuf() -{ -} - - -int NullStreamBuf::readFromDevice() -{ - return -1; -} - - -int NullStreamBuf::writeToDevice(char c) -{ - return charToInt(c); -} - - -NullIOS::NullIOS() -{ - poco_ios_init(&_buf); -} - - -NullIOS::~NullIOS() -{ -} - - -NullInputStream::NullInputStream(): std::istream(&_buf) -{ -} - - -NullInputStream::~NullInputStream() -{ -} - - -NullOutputStream::NullOutputStream(): std::ostream(&_buf) -{ -} - - -NullOutputStream::~NullOutputStream() -{ -} - - -} // namespace Poco +// +// NullStream.cpp +// +// $Id: //poco/1.2/Foundation/src/NullStream.cpp#1 $ +// +// Library: Foundation +// Package: Streams +// Module: NullStream +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/NullStream.h" + + +namespace Poco { + + +NullStreamBuf::NullStreamBuf() +{ +} + + +NullStreamBuf::~NullStreamBuf() +{ +} + + +int NullStreamBuf::readFromDevice() +{ + return -1; +} + + +int NullStreamBuf::writeToDevice(char c) +{ + return charToInt(c); +} + + +NullIOS::NullIOS() +{ + poco_ios_init(&_buf); +} + + +NullIOS::~NullIOS() +{ +} + + +NullInputStream::NullInputStream(): std::istream(&_buf) +{ +} + + +NullInputStream::~NullInputStream() +{ +} + + +NullOutputStream::NullOutputStream(): std::ostream(&_buf) +{ +} + + +NullOutputStream::~NullOutputStream() +{ +} + + +} // namespace Poco diff --git a/Foundation/src/NumberFormatter.cpp b/Foundation/src/NumberFormatter.cpp index a369f63c0..e1aaf157e 100644 --- a/Foundation/src/NumberFormatter.cpp +++ b/Foundation/src/NumberFormatter.cpp @@ -1,384 +1,384 @@ -// -// NumberFormatter.cpp -// -// $Id: //poco/1.2/Foundation/src/NumberFormatter.cpp#1 $ -// -// Library: Foundation -// Package: Core -// Module: NumberFormatter -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/NumberFormatter.h" -#include -#include - - -#if defined(_MSC_VER) - #define I64_FMT "I64" -#elif defined(__APPLE__) - #define I64_FMT "q" -#else - #define I64_FMT "ll" -#endif - - -namespace Poco { - - -std::string NumberFormatter::format(int value) -{ - char buffer[64]; - sprintf(buffer, "%d", value); - return std::string(buffer); -} - - -std::string NumberFormatter::format(int value, int width) -{ - poco_assert (width > 0 && width < 64); - - char buffer[64]; - sprintf(buffer, "%*d", width, value); - return std::string(buffer); -} - - -std::string NumberFormatter::format0(int value, int width) -{ - poco_assert (width > 0 && width < 64); - - char buffer[64]; - sprintf(buffer, "%0*d", width, value); - return std::string(buffer); -} - - -std::string NumberFormatter::formatHex(int value) -{ - char buffer[64]; - sprintf(buffer, "%X", value); - return std::string(buffer); -} - - -std::string NumberFormatter::formatHex(int value, int width) -{ - poco_assert (width > 0 && width < 64); - - char buffer[64]; - sprintf(buffer, "%0*X", width, value); - return std::string(buffer); -} - - -std::string NumberFormatter::format(unsigned value) -{ - char buffer[64]; - sprintf(buffer, "%u", value); - return std::string(buffer); -} - - -std::string NumberFormatter::format(unsigned value, int width) -{ - poco_assert (width > 0 && width < 64); - - char buffer[64]; - sprintf(buffer, "%*u", width, value); - return std::string(buffer); -} - - -std::string NumberFormatter::format0(unsigned int value, int width) -{ - poco_assert (width > 0 && width < 64); - - char buffer[64]; - sprintf(buffer, "%0*u", width, value); - return std::string(buffer); -} - - -std::string NumberFormatter::formatHex(unsigned value) -{ - char buffer[64]; - sprintf(buffer, "%X", value); - return std::string(buffer); -} - - -std::string NumberFormatter::formatHex(unsigned value, int width) -{ - poco_assert (width > 0 && width < 64); - - char buffer[64]; - sprintf(buffer, "%0*X", width, value); - return std::string(buffer); -} - - -std::string NumberFormatter::format(long value) -{ - char buffer[64]; - sprintf(buffer, "%ld", value); - return std::string(buffer); -} - - -std::string NumberFormatter::format(long value, int width) -{ - poco_assert (width > 0 && width < 64); - - char buffer[64]; - sprintf(buffer, "%*ld", width, value); - return std::string(buffer); -} - - -std::string NumberFormatter::format0(long value, int width) -{ - poco_assert (width > 0 && width < 64); - - char buffer[64]; - sprintf(buffer, "%0*ld", width, value); - return std::string(buffer); -} - - -std::string NumberFormatter::formatHex(long value) -{ - char buffer[64]; - sprintf(buffer, "%lX", value); - return std::string(buffer); -} - - -std::string NumberFormatter::formatHex(long value, int width) -{ - poco_assert (width > 0 && width < 64); - - char buffer[64]; - sprintf(buffer, "%0*lX", width, value); - return std::string(buffer); -} - - -std::string NumberFormatter::format(unsigned long value) -{ - char buffer[64]; - sprintf(buffer, "%lu", value); - return std::string(buffer); -} - - -std::string NumberFormatter::format(unsigned long value, int width) -{ - poco_assert (width > 0 && width < 64); - - char buffer[64]; - sprintf(buffer, "%*lu", width, value); - return std::string(buffer); -} - - -std::string NumberFormatter::format0(unsigned long value, int width) -{ - poco_assert (width > 0 && width < 64); - - char buffer[64]; - sprintf(buffer, "%0*lu", width, value); - return std::string(buffer); -} - - -std::string NumberFormatter::formatHex(unsigned long value) -{ - char buffer[64]; - sprintf(buffer, "%lX", value); - return std::string(buffer); -} - - -std::string NumberFormatter::formatHex(unsigned long value, int width) -{ - poco_assert (width > 0 && width < 64); - - char buffer[64]; - sprintf(buffer, "%0*lX", width, value); - return std::string(buffer); -} - - -#if defined(POCO_HAVE_INT64) && !defined(POCO_LONG_IS_64_BIT) - - -std::string NumberFormatter::format(Int64 value) -{ - char buffer[64]; - sprintf(buffer, "%"I64_FMT"d", value); - return std::string(buffer); -} - - -std::string NumberFormatter::format(Int64 value, int width) -{ - poco_assert (width > 0 && width < 64); - - char buffer[64]; - sprintf(buffer, "%*"I64_FMT"d", width, value); - return std::string(buffer); -} - - -std::string NumberFormatter::format0(Int64 value, int width) -{ - poco_assert (width > 0 && width < 64); - - char buffer[64]; - sprintf(buffer, "%0*"I64_FMT"d", width, value); - return std::string(buffer); -} - - -std::string NumberFormatter::formatHex(Int64 value) -{ - char buffer[64]; - sprintf(buffer, "%"I64_FMT"X", value); - return std::string(buffer); -} - - -std::string NumberFormatter::formatHex(Int64 value, int width) -{ - poco_assert (width > 0 && width < 64); - - char buffer[64]; - sprintf(buffer, "%0*"I64_FMT"X", width, value); - return std::string(buffer); -} - - -std::string NumberFormatter::format(UInt64 value) -{ - char buffer[64]; - sprintf(buffer, "%"I64_FMT"u", value); - return std::string(buffer); -} - - -std::string NumberFormatter::format(UInt64 value, int width) -{ - poco_assert (width > 0 && width < 64); - - char buffer[64]; - sprintf(buffer, "%*"I64_FMT"u", width, value); - return std::string(buffer); -} - - -std::string NumberFormatter::format0(UInt64 value, int width) -{ - poco_assert (width > 0 && width < 64); - - char buffer[64]; - sprintf(buffer, "%0*"I64_FMT"u", width, value); - return std::string(buffer); -} - - -std::string NumberFormatter::formatHex(UInt64 value) -{ - char buffer[64]; - sprintf(buffer, "%"I64_FMT"X", value); - return std::string(buffer); -} - - -std::string NumberFormatter::formatHex(UInt64 value, int width) -{ - poco_assert (width > 0 && width < 64); - - char buffer[64]; - sprintf(buffer, "%0*"I64_FMT"X", width, value); - return std::string(buffer); -} - - -#endif // defined(POCO_HAVE_INT64) && !defined(POCO_LONG_IS_64_BIT) - - -std::string NumberFormatter::format(float value) -{ - char buffer[64]; - sprintf(buffer, "%.*g", 10, (double) value); - return std::string(buffer); -} - - -std::string NumberFormatter::format(double value) -{ - char buffer[64]; - sprintf(buffer, "%.*g", 20, value); - return std::string(buffer); -} - - -std::string NumberFormatter::format(double value, int precision) -{ - poco_assert (precision >= 0 && precision < 32); - - char buffer[64]; - sprintf(buffer, "%.*f", precision, value); - return std::string(buffer); -} - - -std::string NumberFormatter::format(double value, int width, int precision) -{ - poco_assert (width > 0 && width < 64 && precision >= 0 && precision < width); - - char buffer[64]; - sprintf(buffer, "%*.*f", width, precision, value); - return std::string(buffer); -} - - -std::string NumberFormatter::format(const void* ptr) -{ - char buffer[24]; -#if defined(POCO_PTR_IS_64_BIT) - sprintf(buffer, "%016"I64_FMT"X", (UIntPtr) ptr); -#else - sprintf(buffer, "%08lX", (UIntPtr) ptr); -#endif - return std::string(buffer); -} - - -} // namespace Poco +// +// NumberFormatter.cpp +// +// $Id: //poco/1.2/Foundation/src/NumberFormatter.cpp#1 $ +// +// Library: Foundation +// Package: Core +// Module: NumberFormatter +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/NumberFormatter.h" +#include +#include + + +#if defined(_MSC_VER) + #define I64_FMT "I64" +#elif defined(__APPLE__) + #define I64_FMT "q" +#else + #define I64_FMT "ll" +#endif + + +namespace Poco { + + +std::string NumberFormatter::format(int value) +{ + char buffer[64]; + sprintf(buffer, "%d", value); + return std::string(buffer); +} + + +std::string NumberFormatter::format(int value, int width) +{ + poco_assert (width > 0 && width < 64); + + char buffer[64]; + sprintf(buffer, "%*d", width, value); + return std::string(buffer); +} + + +std::string NumberFormatter::format0(int value, int width) +{ + poco_assert (width > 0 && width < 64); + + char buffer[64]; + sprintf(buffer, "%0*d", width, value); + return std::string(buffer); +} + + +std::string NumberFormatter::formatHex(int value) +{ + char buffer[64]; + sprintf(buffer, "%X", value); + return std::string(buffer); +} + + +std::string NumberFormatter::formatHex(int value, int width) +{ + poco_assert (width > 0 && width < 64); + + char buffer[64]; + sprintf(buffer, "%0*X", width, value); + return std::string(buffer); +} + + +std::string NumberFormatter::format(unsigned value) +{ + char buffer[64]; + sprintf(buffer, "%u", value); + return std::string(buffer); +} + + +std::string NumberFormatter::format(unsigned value, int width) +{ + poco_assert (width > 0 && width < 64); + + char buffer[64]; + sprintf(buffer, "%*u", width, value); + return std::string(buffer); +} + + +std::string NumberFormatter::format0(unsigned int value, int width) +{ + poco_assert (width > 0 && width < 64); + + char buffer[64]; + sprintf(buffer, "%0*u", width, value); + return std::string(buffer); +} + + +std::string NumberFormatter::formatHex(unsigned value) +{ + char buffer[64]; + sprintf(buffer, "%X", value); + return std::string(buffer); +} + + +std::string NumberFormatter::formatHex(unsigned value, int width) +{ + poco_assert (width > 0 && width < 64); + + char buffer[64]; + sprintf(buffer, "%0*X", width, value); + return std::string(buffer); +} + + +std::string NumberFormatter::format(long value) +{ + char buffer[64]; + sprintf(buffer, "%ld", value); + return std::string(buffer); +} + + +std::string NumberFormatter::format(long value, int width) +{ + poco_assert (width > 0 && width < 64); + + char buffer[64]; + sprintf(buffer, "%*ld", width, value); + return std::string(buffer); +} + + +std::string NumberFormatter::format0(long value, int width) +{ + poco_assert (width > 0 && width < 64); + + char buffer[64]; + sprintf(buffer, "%0*ld", width, value); + return std::string(buffer); +} + + +std::string NumberFormatter::formatHex(long value) +{ + char buffer[64]; + sprintf(buffer, "%lX", value); + return std::string(buffer); +} + + +std::string NumberFormatter::formatHex(long value, int width) +{ + poco_assert (width > 0 && width < 64); + + char buffer[64]; + sprintf(buffer, "%0*lX", width, value); + return std::string(buffer); +} + + +std::string NumberFormatter::format(unsigned long value) +{ + char buffer[64]; + sprintf(buffer, "%lu", value); + return std::string(buffer); +} + + +std::string NumberFormatter::format(unsigned long value, int width) +{ + poco_assert (width > 0 && width < 64); + + char buffer[64]; + sprintf(buffer, "%*lu", width, value); + return std::string(buffer); +} + + +std::string NumberFormatter::format0(unsigned long value, int width) +{ + poco_assert (width > 0 && width < 64); + + char buffer[64]; + sprintf(buffer, "%0*lu", width, value); + return std::string(buffer); +} + + +std::string NumberFormatter::formatHex(unsigned long value) +{ + char buffer[64]; + sprintf(buffer, "%lX", value); + return std::string(buffer); +} + + +std::string NumberFormatter::formatHex(unsigned long value, int width) +{ + poco_assert (width > 0 && width < 64); + + char buffer[64]; + sprintf(buffer, "%0*lX", width, value); + return std::string(buffer); +} + + +#if defined(POCO_HAVE_INT64) && !defined(POCO_LONG_IS_64_BIT) + + +std::string NumberFormatter::format(Int64 value) +{ + char buffer[64]; + sprintf(buffer, "%"I64_FMT"d", value); + return std::string(buffer); +} + + +std::string NumberFormatter::format(Int64 value, int width) +{ + poco_assert (width > 0 && width < 64); + + char buffer[64]; + sprintf(buffer, "%*"I64_FMT"d", width, value); + return std::string(buffer); +} + + +std::string NumberFormatter::format0(Int64 value, int width) +{ + poco_assert (width > 0 && width < 64); + + char buffer[64]; + sprintf(buffer, "%0*"I64_FMT"d", width, value); + return std::string(buffer); +} + + +std::string NumberFormatter::formatHex(Int64 value) +{ + char buffer[64]; + sprintf(buffer, "%"I64_FMT"X", value); + return std::string(buffer); +} + + +std::string NumberFormatter::formatHex(Int64 value, int width) +{ + poco_assert (width > 0 && width < 64); + + char buffer[64]; + sprintf(buffer, "%0*"I64_FMT"X", width, value); + return std::string(buffer); +} + + +std::string NumberFormatter::format(UInt64 value) +{ + char buffer[64]; + sprintf(buffer, "%"I64_FMT"u", value); + return std::string(buffer); +} + + +std::string NumberFormatter::format(UInt64 value, int width) +{ + poco_assert (width > 0 && width < 64); + + char buffer[64]; + sprintf(buffer, "%*"I64_FMT"u", width, value); + return std::string(buffer); +} + + +std::string NumberFormatter::format0(UInt64 value, int width) +{ + poco_assert (width > 0 && width < 64); + + char buffer[64]; + sprintf(buffer, "%0*"I64_FMT"u", width, value); + return std::string(buffer); +} + + +std::string NumberFormatter::formatHex(UInt64 value) +{ + char buffer[64]; + sprintf(buffer, "%"I64_FMT"X", value); + return std::string(buffer); +} + + +std::string NumberFormatter::formatHex(UInt64 value, int width) +{ + poco_assert (width > 0 && width < 64); + + char buffer[64]; + sprintf(buffer, "%0*"I64_FMT"X", width, value); + return std::string(buffer); +} + + +#endif // defined(POCO_HAVE_INT64) && !defined(POCO_LONG_IS_64_BIT) + + +std::string NumberFormatter::format(float value) +{ + char buffer[64]; + sprintf(buffer, "%.*g", 10, (double) value); + return std::string(buffer); +} + + +std::string NumberFormatter::format(double value) +{ + char buffer[64]; + sprintf(buffer, "%.*g", 20, value); + return std::string(buffer); +} + + +std::string NumberFormatter::format(double value, int precision) +{ + poco_assert (precision >= 0 && precision < 32); + + char buffer[64]; + sprintf(buffer, "%.*f", precision, value); + return std::string(buffer); +} + + +std::string NumberFormatter::format(double value, int width, int precision) +{ + poco_assert (width > 0 && width < 64 && precision >= 0 && precision < width); + + char buffer[64]; + sprintf(buffer, "%*.*f", width, precision, value); + return std::string(buffer); +} + + +std::string NumberFormatter::format(const void* ptr) +{ + char buffer[24]; +#if defined(POCO_PTR_IS_64_BIT) + sprintf(buffer, "%016"I64_FMT"X", (UIntPtr) ptr); +#else + sprintf(buffer, "%08lX", (UIntPtr) ptr); +#endif + return std::string(buffer); +} + + +} // namespace Poco diff --git a/Foundation/src/NumberParser.cpp b/Foundation/src/NumberParser.cpp index b2b291098..6025bcff4 100644 --- a/Foundation/src/NumberParser.cpp +++ b/Foundation/src/NumberParser.cpp @@ -1,173 +1,173 @@ -// -// NumberParser.cpp -// -// $Id: //poco/1.2/Foundation/src/NumberParser.cpp#1 $ -// -// Library: Foundation -// Package: Core -// Module: NumberParser -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/NumberParser.h" -#include "Poco/Exception.h" -#include -#include - - -#if defined(_MSC_VER) - #define I64_FMT "I64" -#elif defined(__APPLE__) - #define I64_FMT "q" -#else - #define I64_FMT "ll" -#endif - - -namespace Poco { - - -int NumberParser::parse(const std::string& s) -{ - int result; - if (tryParse(s, result)) - return result; - else - throw SyntaxException("Not a valid integer", s); -} - - -bool NumberParser::tryParse(const std::string& s, int& value) -{ - return sscanf(s.c_str(), "%d", &value) == 1; -} - - -unsigned NumberParser::parseUnsigned(const std::string& s) -{ - unsigned result; - if (tryParseUnsigned(s, result)) - return result; - else - throw SyntaxException("Not a valid unsigned integer", s); -} - - -bool NumberParser::tryParseUnsigned(const std::string& s, unsigned& value) -{ - return sscanf(s.c_str(), "%u", &value) == 1; -} - - -unsigned NumberParser::parseHex(const std::string& s) -{ - unsigned result; - if (tryParseHex(s, result)) - return result; - else - throw SyntaxException("Not a valid hexadecimal integer", s); -} - - -bool NumberParser::tryParseHex(const std::string& s, unsigned& value) -{ - return sscanf(s.c_str(), "%x", &value) == 1; -} - - -#if defined(POCO_HAVE_INT64) - - -Int64 NumberParser::parse64(const std::string& s) -{ - Int64 result; - if (tryParse64(s, result)) - return result; - else - throw SyntaxException("Not a valid integer", s); -} - - -bool NumberParser::tryParse64(const std::string& s, Int64& value) -{ - return sscanf(s.c_str(), "%"I64_FMT"d", &value) == 1; -} - - -UInt64 NumberParser::parseUnsigned64(const std::string& s) -{ - UInt64 result; - if (tryParseUnsigned64(s, result)) - return result; - else - throw SyntaxException("Not a valid unsigned integer", s); -} - - -bool NumberParser::tryParseUnsigned64(const std::string& s, UInt64& value) -{ - return sscanf(s.c_str(), "%"I64_FMT"u", &value) == 1; -} - - -UInt64 NumberParser::parseHex64(const std::string& s) -{ - UInt64 result; - if (tryParseHex64(s, result)) - return result; - else - throw SyntaxException("Not a valid hexadecimal integer", s); -} - - -bool NumberParser::tryParseHex64(const std::string& s, UInt64& value) -{ - return sscanf(s.c_str(), "%"I64_FMT"x", &value) == 1; -} - - -#endif // defined(POCO_HAVE_INT64) - - -double NumberParser::parseFloat(const std::string& s) -{ - double result; - if (tryParseFloat(s, result)) - return result; - else - throw SyntaxException("Not a valid floating-point number", s); -} - - -bool NumberParser::tryParseFloat(const std::string& s, double& value) -{ - return sscanf(s.c_str(), "%lf", &value) == 1; -} - - -} // namespace Poco +// +// NumberParser.cpp +// +// $Id: //poco/1.2/Foundation/src/NumberParser.cpp#1 $ +// +// Library: Foundation +// Package: Core +// Module: NumberParser +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/NumberParser.h" +#include "Poco/Exception.h" +#include +#include + + +#if defined(_MSC_VER) + #define I64_FMT "I64" +#elif defined(__APPLE__) + #define I64_FMT "q" +#else + #define I64_FMT "ll" +#endif + + +namespace Poco { + + +int NumberParser::parse(const std::string& s) +{ + int result; + if (tryParse(s, result)) + return result; + else + throw SyntaxException("Not a valid integer", s); +} + + +bool NumberParser::tryParse(const std::string& s, int& value) +{ + return sscanf(s.c_str(), "%d", &value) == 1; +} + + +unsigned NumberParser::parseUnsigned(const std::string& s) +{ + unsigned result; + if (tryParseUnsigned(s, result)) + return result; + else + throw SyntaxException("Not a valid unsigned integer", s); +} + + +bool NumberParser::tryParseUnsigned(const std::string& s, unsigned& value) +{ + return sscanf(s.c_str(), "%u", &value) == 1; +} + + +unsigned NumberParser::parseHex(const std::string& s) +{ + unsigned result; + if (tryParseHex(s, result)) + return result; + else + throw SyntaxException("Not a valid hexadecimal integer", s); +} + + +bool NumberParser::tryParseHex(const std::string& s, unsigned& value) +{ + return sscanf(s.c_str(), "%x", &value) == 1; +} + + +#if defined(POCO_HAVE_INT64) + + +Int64 NumberParser::parse64(const std::string& s) +{ + Int64 result; + if (tryParse64(s, result)) + return result; + else + throw SyntaxException("Not a valid integer", s); +} + + +bool NumberParser::tryParse64(const std::string& s, Int64& value) +{ + return sscanf(s.c_str(), "%"I64_FMT"d", &value) == 1; +} + + +UInt64 NumberParser::parseUnsigned64(const std::string& s) +{ + UInt64 result; + if (tryParseUnsigned64(s, result)) + return result; + else + throw SyntaxException("Not a valid unsigned integer", s); +} + + +bool NumberParser::tryParseUnsigned64(const std::string& s, UInt64& value) +{ + return sscanf(s.c_str(), "%"I64_FMT"u", &value) == 1; +} + + +UInt64 NumberParser::parseHex64(const std::string& s) +{ + UInt64 result; + if (tryParseHex64(s, result)) + return result; + else + throw SyntaxException("Not a valid hexadecimal integer", s); +} + + +bool NumberParser::tryParseHex64(const std::string& s, UInt64& value) +{ + return sscanf(s.c_str(), "%"I64_FMT"x", &value) == 1; +} + + +#endif // defined(POCO_HAVE_INT64) + + +double NumberParser::parseFloat(const std::string& s) +{ + double result; + if (tryParseFloat(s, result)) + return result; + else + throw SyntaxException("Not a valid floating-point number", s); +} + + +bool NumberParser::tryParseFloat(const std::string& s, double& value) +{ + return sscanf(s.c_str(), "%lf", &value) == 1; +} + + +} // namespace Poco diff --git a/Foundation/src/OpcomChannel.cpp b/Foundation/src/OpcomChannel.cpp index 5bea21897..d24a03edb 100644 --- a/Foundation/src/OpcomChannel.cpp +++ b/Foundation/src/OpcomChannel.cpp @@ -1,199 +1,199 @@ -// -// OpcomChannel.cpp -// -// $Id: //poco/1.2/Foundation/src/OpcomChannel.cpp#1 $ -// -// Library: Foundation -// Package: Logging -// Module: OpcomChannel -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/OpcomChannel.h" -#include "Poco/Message.h" -#include -#include -#include - - -namespace Poco { - - -const std::string OpcomChannel::PROP_TARGET = "target"; - - -OpcomChannel::OpcomChannel(): _target(OPC$M_NM_CENTRL) -{ -} - - -OpcomChannel::OpcomChannel(int target): _target(target) -{ -} - - -OpcomChannel::~OpcomChannel() -{ -} - - -void OpcomChannel::log(const Message& msg) -{ - const std::string& text = msg.getText(); - // set up OPC buffer - struct _opcdef buffer; - buffer.opc$b_ms_type = OPC$_RQ_RQST; - buffer.opc$b_ms_target = _target; - buffer.opc$l_ms_rqstid = 0; - int len = text.size(); - // restrict message text to 128 chars - if (len > 128) len = 128; - // copy message text into buffer - memcpy(&buffer.opc$l_ms_text, text.data(), len); - - // sys$sndopr only accepts 32-bit pointers - #pragma pointer_size save - #pragma pointer_size 32 - - // set up the descriptor - struct dsc$descriptor bufferDsc; - bufferDsc.dsc$w_length = len + 8; - bufferDsc.dsc$a_pointer = (char*) &buffer; - // call the system service - sys$sndopr(&bufferDsc, 0); - - #pragma pointer_size restore -} - - -void OpcomChannel::setProperty(const std::string& name, const std::string& value) -{ - if (name == PROP_TARGET) - { - if (value == "CARDS") - _target = OPC$M_NM_CARDS; - else if (value == "CENTRL") - _target = OPC$M_NM_CENTRL; - else if (value == "CLUSTER") - _target = OPC$M_NM_CLUSTER; - else if (value == "DEVICE") - _target = OPC$M_NM_DEVICE; - else if (value == "DISKS") - _target = OPC$M_NM_DISKS; - else if (value == "NTWORK") - _target = OPC$M_NM_NTWORK; - else if (value == "TAPES") - _target = OPC$M_NM_TAPES; - else if (value == "PRINT") - _target = OPC$M_NM_PRINT; - else if (value == "SECURITY") - _target = OPC$M_NM_SECURITY; - else if (value == "OPER1") - _target = OPC$M_NM_OPER1; - else if (value == "OPER2") - _target = OPC$M_NM_OPER2; - else if (value == "OPER3") - _target = OPC$M_NM_OPER3; - else if (value == "OPER4") - _target = OPC$M_NM_OPER4; - else if (value == "OPER5") - _target = OPC$M_NM_OPER5; - else if (value == "OPER6") - _target = OPC$M_NM_OPER6; - else if (value == "OPER7") - _target = OPC$M_NM_OPER7; - else if (value == "OPER8") - _target = OPC$M_NM_OPER8; - else if (value == "OPER9") - _target = OPC$M_NM_OPER9; - else if (value == "OPER10") - _target = OPC$M_NM_OPER10; - else if (value == "OPER11") - _target = OPC$M_NM_OPER11; - else if (value == "OPER12") - _target = OPC$M_NM_OPER12; - } - else - { - Channel::setProperty(name, value); - } -} - - -std::string OpcomChannel::getProperty(const std::string& name) const -{ - if (name == PROP_TARGET) - { - if (_target == OPC$M_NM_CARDS) - return "CARDS"; - else if (_target == OPC$M_NM_CENTRL) - return "CENTRL"; - else if (_target == OPC$M_NM_CLUSTER) - return "CLUSTER"; - else if (_target == OPC$M_NM_DEVICE) - return "DEVICE"; - else if (_target == OPC$M_NM_DISKS) - return "DISKS"; - else if (_target == OPC$M_NM_NTWORK) - return "NTWORK"; - else if (_target == OPC$M_NM_TAPES) - return "TAPES"; - else if (_target == OPC$M_NM_PRINT) - return "PRINT"; - else if (_target == OPC$M_NM_SECURITY) - return "SECURITY"; - else if (_target == OPC$M_NM_OPER1) - return "OPER1"; - else if (_target == OPC$M_NM_OPER2) - return "OPER2"; - else if (_target == OPC$M_NM_OPER3) - return "OPER3"; - else if (_target == OPC$M_NM_OPER4) - return "OPER4"; - else if (_target == OPC$M_NM_OPER5) - return "OPER5"; - else if (_target == OPC$M_NM_OPER6) - return "OPER6"; - else if (_target == OPC$M_NM_OPER7) - return "OPER7"; - else if (_target == OPC$M_NM_OPER8) - return "OPER8"; - else if (_target == OPC$M_NM_OPER9) - return "OPER9"; - else if (_target == OPC$M_NM_OPER10) - return "OPER10"; - else if (_target == OPC$M_NM_OPER11) - return "OPER11"; - else if (_target == OPC$M_NM_OPER12) - return "OPER12"; - } - return Channel::getProperty(name); -} - - -} // namespace Poco +// +// OpcomChannel.cpp +// +// $Id: //poco/1.2/Foundation/src/OpcomChannel.cpp#1 $ +// +// Library: Foundation +// Package: Logging +// Module: OpcomChannel +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/OpcomChannel.h" +#include "Poco/Message.h" +#include +#include +#include + + +namespace Poco { + + +const std::string OpcomChannel::PROP_TARGET = "target"; + + +OpcomChannel::OpcomChannel(): _target(OPC$M_NM_CENTRL) +{ +} + + +OpcomChannel::OpcomChannel(int target): _target(target) +{ +} + + +OpcomChannel::~OpcomChannel() +{ +} + + +void OpcomChannel::log(const Message& msg) +{ + const std::string& text = msg.getText(); + // set up OPC buffer + struct _opcdef buffer; + buffer.opc$b_ms_type = OPC$_RQ_RQST; + buffer.opc$b_ms_target = _target; + buffer.opc$l_ms_rqstid = 0; + int len = text.size(); + // restrict message text to 128 chars + if (len > 128) len = 128; + // copy message text into buffer + memcpy(&buffer.opc$l_ms_text, text.data(), len); + + // sys$sndopr only accepts 32-bit pointers + #pragma pointer_size save + #pragma pointer_size 32 + + // set up the descriptor + struct dsc$descriptor bufferDsc; + bufferDsc.dsc$w_length = len + 8; + bufferDsc.dsc$a_pointer = (char*) &buffer; + // call the system service + sys$sndopr(&bufferDsc, 0); + + #pragma pointer_size restore +} + + +void OpcomChannel::setProperty(const std::string& name, const std::string& value) +{ + if (name == PROP_TARGET) + { + if (value == "CARDS") + _target = OPC$M_NM_CARDS; + else if (value == "CENTRL") + _target = OPC$M_NM_CENTRL; + else if (value == "CLUSTER") + _target = OPC$M_NM_CLUSTER; + else if (value == "DEVICE") + _target = OPC$M_NM_DEVICE; + else if (value == "DISKS") + _target = OPC$M_NM_DISKS; + else if (value == "NTWORK") + _target = OPC$M_NM_NTWORK; + else if (value == "TAPES") + _target = OPC$M_NM_TAPES; + else if (value == "PRINT") + _target = OPC$M_NM_PRINT; + else if (value == "SECURITY") + _target = OPC$M_NM_SECURITY; + else if (value == "OPER1") + _target = OPC$M_NM_OPER1; + else if (value == "OPER2") + _target = OPC$M_NM_OPER2; + else if (value == "OPER3") + _target = OPC$M_NM_OPER3; + else if (value == "OPER4") + _target = OPC$M_NM_OPER4; + else if (value == "OPER5") + _target = OPC$M_NM_OPER5; + else if (value == "OPER6") + _target = OPC$M_NM_OPER6; + else if (value == "OPER7") + _target = OPC$M_NM_OPER7; + else if (value == "OPER8") + _target = OPC$M_NM_OPER8; + else if (value == "OPER9") + _target = OPC$M_NM_OPER9; + else if (value == "OPER10") + _target = OPC$M_NM_OPER10; + else if (value == "OPER11") + _target = OPC$M_NM_OPER11; + else if (value == "OPER12") + _target = OPC$M_NM_OPER12; + } + else + { + Channel::setProperty(name, value); + } +} + + +std::string OpcomChannel::getProperty(const std::string& name) const +{ + if (name == PROP_TARGET) + { + if (_target == OPC$M_NM_CARDS) + return "CARDS"; + else if (_target == OPC$M_NM_CENTRL) + return "CENTRL"; + else if (_target == OPC$M_NM_CLUSTER) + return "CLUSTER"; + else if (_target == OPC$M_NM_DEVICE) + return "DEVICE"; + else if (_target == OPC$M_NM_DISKS) + return "DISKS"; + else if (_target == OPC$M_NM_NTWORK) + return "NTWORK"; + else if (_target == OPC$M_NM_TAPES) + return "TAPES"; + else if (_target == OPC$M_NM_PRINT) + return "PRINT"; + else if (_target == OPC$M_NM_SECURITY) + return "SECURITY"; + else if (_target == OPC$M_NM_OPER1) + return "OPER1"; + else if (_target == OPC$M_NM_OPER2) + return "OPER2"; + else if (_target == OPC$M_NM_OPER3) + return "OPER3"; + else if (_target == OPC$M_NM_OPER4) + return "OPER4"; + else if (_target == OPC$M_NM_OPER5) + return "OPER5"; + else if (_target == OPC$M_NM_OPER6) + return "OPER6"; + else if (_target == OPC$M_NM_OPER7) + return "OPER7"; + else if (_target == OPC$M_NM_OPER8) + return "OPER8"; + else if (_target == OPC$M_NM_OPER9) + return "OPER9"; + else if (_target == OPC$M_NM_OPER10) + return "OPER10"; + else if (_target == OPC$M_NM_OPER11) + return "OPER11"; + else if (_target == OPC$M_NM_OPER12) + return "OPER12"; + } + return Channel::getProperty(name); +} + + +} // namespace Poco diff --git a/Foundation/src/Path.cpp b/Foundation/src/Path.cpp index 034baffa7..236642538 100644 --- a/Foundation/src/Path.cpp +++ b/Foundation/src/Path.cpp @@ -1,987 +1,987 @@ -// -// Path.cpp -// -// $Id: //poco/1.2/Foundation/src/Path.cpp#1 $ -// -// Library: Foundation -// Package: Filesystem -// Module: Path -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/Path.h" -#include "Poco/File.h" -#include "Poco/Exception.h" -#include "Poco/StringTokenizer.h" -#include - - -#if defined(POCO_OS_FAMILY_VMS) -#include "Path_VMS.cpp" -#elif defined(POCO_OS_FAMILY_UNIX) -#include "Path_UNIX.cpp" -#elif defined(POCO_OS_FAMILY_WINDOWS) && defined(POCO_WIN32_UTF8) -#include "Path_WIN32U.cpp" -#elif defined(POCO_OS_FAMILY_WINDOWS) -#include "Path_WIN32.cpp" -#endif - - -namespace Poco { - - -Path::Path(): _absolute(false) -{ -} - - -Path::Path(bool absolute): _absolute(absolute) -{ -} - - -Path::Path(const std::string& path) -{ - assign(path); -} - - -Path::Path(const std::string& path, Style style) -{ - assign(path, style); -} - - -Path::Path(const char* path) -{ - poco_check_ptr(path); - assign(path); -} - - -Path::Path(const char* path, Style style) -{ - poco_check_ptr(path); - assign(path, style); -} - - -Path::Path(const Path& path): - _node(path._node), - _device(path._device), - _name(path._name), - _version(path._version), - _dirs(path._dirs), - _absolute(path._absolute) -{ -} - - -Path::Path(const Path& parent, const std::string& fileName): - _node(parent._node), - _device(parent._device), - _name(parent._name), - _version(parent._version), - _dirs(parent._dirs), - _absolute(parent._absolute) -{ - makeDirectory(); - _name = fileName; -} - - -Path::Path(const Path& parent, const Path& relative): - _node(parent._node), - _device(parent._device), - _name(parent._name), - _version(parent._version), - _dirs(parent._dirs), - _absolute(parent._absolute) -{ - resolve(relative); -} - - -Path::~Path() -{ -} - - -Path& Path::operator = (const Path& path) -{ - return assign(path); -} - - -Path& Path::operator = (const std::string& path) -{ - return assign(path); -} - - -Path& Path::operator = (const char* path) -{ - poco_check_ptr(path); - return assign(path); -} - - -void Path::swap(Path& path) -{ - std::swap(_node, path._node); - std::swap(_device, path._device); - std::swap(_name, path._name); - std::swap(_version, path._version); - std::swap(_dirs, path._dirs); - std::swap(_absolute, path._absolute); -} - - -Path& Path::assign(const Path& path) -{ - if (&path != this) - { - _node = path._node; - _device = path._device; - _name = path._name; - _version = path._version; - _dirs = path._dirs; - _absolute = path._absolute; - } - return *this; -} - - -Path& Path::assign(const std::string& path) -{ -#if defined(POCO_OS_FAMILY_VMS) - parseVMS(path); -#elif defined(POCO_OS_FAMILY_WINDOWS) - parseWindows(path); -#else - parseUnix(path); -#endif - return *this; -} - - -Path& Path::assign(const std::string& path, Style style) -{ - switch (style) - { - case PATH_UNIX: - parseUnix(path); - break; - case PATH_WINDOWS: - parseWindows(path); - break; - case PATH_VMS: - parseVMS(path); - break; - case PATH_NATIVE: - assign(path); - break; - case PATH_GUESS: - parseGuess(path); - break; - default: - poco_bugcheck(); - } - return *this; -} - - -Path& Path::assign(const char* path) -{ - return assign(std::string(path)); -} - - -std::string Path::toString() const -{ -#if defined(POCO_OS_FAMILY_UNIX) - return buildUnix(); -#elif defined(POCO_OS_FAMILY_WINDOWS) - return buildWindows(); -#else - return buildVMS(); -#endif -} - - -std::string Path::toString(Style style) const -{ - switch (style) - { - case PATH_UNIX: - return buildUnix(); - case PATH_WINDOWS: - return buildWindows(); - case PATH_VMS: - return buildVMS(); - case PATH_NATIVE: - case PATH_GUESS: - return toString(); - default: - poco_bugcheck(); - } - return std::string(); -} - - -bool Path::tryParse(const std::string& path) -{ - try - { - Path p; - p.parse(path); - assign(p); - return true; - } - catch (...) - { - return false; - } -} - - -bool Path::tryParse(const std::string& path, Style style) -{ - try - { - Path p; - p.parse(path, style); - assign(p); - return true; - } - catch (...) - { - return false; - } -} - - -Path& Path::parseDirectory(const std::string& path) -{ - assign(path); - return makeDirectory(); -} - - -Path& Path::parseDirectory(const std::string& path, Style style) -{ - assign(path, style); - return makeDirectory(); -} - - -Path& Path::makeDirectory() -{ -#if defined(POCO_OS_FAMILY_VMS) - pushDirectory(getBaseName()); -#else - pushDirectory(_name); -#endif - _name.clear(); - _version.clear(); - return *this; -} - - -Path& Path::makeFile() -{ - if (!_dirs.empty() && _name.empty()) - { - _name = _dirs.back(); - _dirs.pop_back(); -#if defined(POCO_OS_FAMILY_VMS) - setExtension("DIR"); -#endif - } - return *this; -} - - -Path& Path::makeAbsolute() -{ - return makeAbsolute(current()); -} - - -Path& Path::makeAbsolute(const Path& base) -{ - if (!_absolute) - { - Path tmp = base; - tmp.makeDirectory(); - for (StringVec::const_iterator it = _dirs.begin(); it != _dirs.end(); ++it) - { - tmp.pushDirectory(*it); - } - _node = tmp._node; - _device = tmp._device; - _dirs = tmp._dirs; - _absolute = base._absolute; - } - return *this; -} - - -Path Path::absolute() const -{ - Path result(*this); - if (!result._absolute) - { - result.makeAbsolute(); - } - return result; -} - - -Path Path::absolute(const Path& base) const -{ - Path result(*this); - if (!result._absolute) - { - result.makeAbsolute(base); - } - return result; -} - - -Path Path::parent() const -{ - Path p(*this); - return p.makeParent(); -} - - -Path& Path::makeParent() -{ - if (_name.empty()) - { - if (_dirs.empty()) - { - if (!_absolute) - _dirs.push_back(".."); - } - else - { - if (_dirs.back() == "..") - _dirs.push_back(".."); - else - _dirs.pop_back(); - } - } - else - { - _name.clear(); - _version.clear(); - } - return *this; -} - - -Path& Path::append(const Path& path) -{ - makeDirectory(); - _dirs.insert(_dirs.end(), path._dirs.begin(), path._dirs.end()); - _name = path._name; - _version = path._version; - return *this; -} - - -Path& Path::resolve(const Path& path) -{ - if (path.isAbsolute()) - { - assign(path); - } - else - { - for (int i = 0; i < path.depth(); ++i) - pushDirectory(path[i]); - _name = path._name; - } - return *this; -} - - -void Path::setNode(const std::string& node) -{ - _node = node; - _absolute = _absolute || !node.empty(); -} - - -void Path::setDevice(const std::string& device) -{ - _device = device; - _absolute = _absolute || !device.empty(); -} - - -const std::string& Path::directory(int n) const -{ - poco_assert (0 <= n && n <= _dirs.size()); - - if (n < _dirs.size()) - return _dirs[n]; - else - return _name; -} - - -const std::string& Path::operator [] (int n) const -{ - poco_assert (0 <= n && n <= _dirs.size()); - - if (n < _dirs.size()) - return _dirs[n]; - else - return _name; -} - - -void Path::pushDirectory(const std::string& dir) -{ - if (!dir.empty() && dir != ".") - { -#if defined(POCO_OS_FAMILY_VMS) - if (dir == ".." || dir == "-") - { - if (!_dirs.empty() && _dirs.back() != ".." && _dirs.back() != "-") - _dirs.pop_back(); - else if (!_absolute) - _dirs.push_back(dir); - } - else _dirs.push_back(dir); -#else - if (dir == "..") - { - if (!_dirs.empty() && _dirs.back() != "..") - _dirs.pop_back(); - else if (!_absolute) - _dirs.push_back(dir); - } - else _dirs.push_back(dir); -#endif - } -} - - -void Path::popDirectory() -{ - poco_assert (!_dirs.empty()); - - _dirs.pop_back(); -} - - -void Path::setFileName(const std::string& name) -{ - _name = name; -} - - -void Path::setBaseName(const std::string& name) -{ - std::string ext = getExtension(); - _name = name; - if (!ext.empty()) - { - _name.append("."); - _name.append(ext); - } -} - - -std::string Path::getBaseName() const -{ - std::string::size_type pos = _name.rfind('.'); - if (pos != std::string::npos) - return _name.substr(0, pos); - else - return _name; -} - - -void Path::setExtension(const std::string& extension) -{ - _name = getBaseName(); - if (!extension.empty()) - { - _name.append("."); - _name.append(extension); - } -} - - -std::string Path::getExtension() const -{ - std::string::size_type pos = _name.rfind('.'); - if (pos != std::string::npos) - return _name.substr(pos + 1); - else - return std::string(); -} - - -void Path::clear() -{ - _node.clear(); - _device.clear(); - _name.clear(); - _dirs.clear(); - _version.clear(); - _absolute = false; -} - - -std::string Path::current() -{ - return PathImpl::currentImpl(); -} - - -std::string Path::home() -{ - return PathImpl::homeImpl(); -} - - -std::string Path::temp() -{ - return PathImpl::tempImpl(); -} - - -std::string Path::null() -{ - return PathImpl::nullImpl(); -} - - -std::string Path::expand(const std::string& path) -{ - return PathImpl::expandImpl(path); -} - - -void Path::listRoots(std::vector& roots) -{ - PathImpl::listRootsImpl(roots); -} - - -bool Path::find(StringVec::const_iterator it, StringVec::const_iterator end, const std::string& name, Path& path) -{ - while (it != end) - { - Path p(*it); - p.makeDirectory(); - p.resolve(Path(name)); - File f(p); - if (f.exists()) - { - path = p; - return true; - } - ++it; - } - return false; -} - - -bool Path::find(const std::string& pathList, const std::string& name, Path& path) -{ - StringTokenizer st(pathList, std::string(1, pathSeparator()), StringTokenizer::TOK_IGNORE_EMPTY + StringTokenizer::TOK_TRIM); - return find(st.begin(), st.end(), name, path); -} - - -void Path::parseUnix(const std::string& path) -{ - clear(); - - std::string::const_iterator it = path.begin(); - std::string::const_iterator end = path.end(); - - if (it != end) - { - if (*it == '/') - { - _absolute = true; ++it; - } - else if (*it == '~') - { - ++it; - if (it == end || *it == '/') - { - Path cwd(home()); - _dirs = cwd._dirs; - _absolute = true; - } - else --it; - } - - while (it != end) - { - std::string name; - while (it != end && *it != '/') name += *it++; - if (it != end) - { - if (_dirs.empty()) - { - if (!name.empty() && *(name.rbegin()) == ':') - _device.assign(name, 0, name.length() - 1); - else - pushDirectory(name); - } - else pushDirectory(name); - } - else _name = name; - if (it != end) ++it; - } - } -} - - -void Path::parseWindows(const std::string& path) -{ - clear(); - - std::string::const_iterator it = path.begin(); - std::string::const_iterator end = path.end(); - - if (it != end) - { - if (*it == '\\' || *it == '/') { _absolute = true; ++it; } - if (_absolute && it != end && (*it == '\\' || *it == '/')) // UNC - { - ++it; - while (it != end && *it != '\\' && *it != '/') _node += *it++; - if (it != end) ++it; - } - else if (it != end) - { - char d = *it++; - if (it != end && *it == ':') // drive letter - { - if (_absolute || !(d >= 'a' && d <= 'z' || d >= 'A' && d <= 'Z')) throw PathSyntaxException(path); - _absolute = true; - _device += d; - ++it; - if (it == end || *it != '\\' && *it != '/') throw PathSyntaxException(path); - ++it; - } - else --it; - } - while (it != end) - { - std::string name; - while (it != end && *it != '\\' && *it != '/') name += *it++; - if (it != end) - pushDirectory(name); - else - _name = name; - if (it != end) ++it; - } - } - if (!_node.empty() && _dirs.empty() && !_name.empty()) - makeDirectory(); -} - - -void Path::parseVMS(const std::string& path) -{ - clear(); - - std::string::const_iterator it = path.begin(); - std::string::const_iterator end = path.end(); - - if (it != end) - { - std::string name; - while (it != end && *it != ':' && *it != '[' && *it != ';') name += *it++; - if (it != end) - { - if (*it == ':') - { - ++it; - if (it != end && *it == ':') - { - _node = name; - ++it; - } - else _device = name; - _absolute = true; - name.clear(); - } - if (it != end) - { - if (_device.empty() && *it != '[') - { - while (it != end && *it != ':' && *it != ';') name += *it++; - if (it != end) - { - if (*it == ':') - { - _device = name; - _absolute = true; - name.clear(); - ++it; - } - } - } - } - if (name.empty()) - { - if (it != end && *it == '[') - { - ++it; - if (it != end) - { - _absolute = true; - if (*it == '.') - { _absolute = false; ++it; } - else if (*it == ']' || *it == '-') - _absolute = false; - while (it != end && *it != ']') - { - name.clear(); - if (*it == '-') - name = "-"; - else - while (it != end && *it != '.' && *it != ']') name += *it++; - if (!name.empty()) - { - if (name == "-") - { - if (_dirs.empty() || _dirs.back() == "..") - _dirs.push_back(".."); - else - _dirs.pop_back(); - } - else _dirs.push_back(name); - } - if (it != end && *it != ']') ++it; - } - if (it == end) throw PathSyntaxException(path); - ++it; - if (it != end && *it == '[') - { - if (!_absolute) throw PathSyntaxException(path); - ++it; - if (it != end && *it == '.') throw PathSyntaxException(path); - int d = int(_dirs.size()); - while (it != end && *it != ']') - { - name.clear(); - if (*it == '-') - name = "-"; - else - while (it != end && *it != '.' && *it != ']') name += *it++; - if (!name.empty()) - { - if (name == "-") - { - if (_dirs.size() > d) - _dirs.pop_back(); - } - else _dirs.push_back(name); - } - if (it != end && *it != ']') ++it; - } - if (it == end) throw PathSyntaxException(path); - ++it; - } - } - _name.clear(); - } - while (it != end && *it != ';') _name += *it++; - } - else _name = name; - if (it != end && *it == ';') - { - ++it; - while (it != end) _version += *it++; - } - } - else _name = name; - } -} - - -void Path::parseGuess(const std::string& path) -{ - bool hasBackslash = false; - bool hasSlash = false; - bool hasOpenBracket = false; - bool hasClosBracket = false; - bool isWindows = path.length() > 2 && path[1] == ':' && (path[2] == '/' || path[2] == '\\'); - std::string::const_iterator end = path.end(); - std::string::const_iterator semiIt = end; - if (!isWindows) - { - for (std::string::const_iterator it = path.begin(); it != end; ++it) - { - switch (*it) - { - case '\\': hasBackslash = true; break; - case '/': hasSlash = true; break; - case '[': hasOpenBracket = true; - case ']': hasClosBracket = hasOpenBracket; - case ';': semiIt = it; break; - } - } - } - if (hasBackslash || isWindows) - { - parseWindows(path); - } - else if (hasSlash) - { - parseUnix(path); - } - else - { - bool isVMS = hasClosBracket; - if (!isVMS && semiIt != end) - { - isVMS = true; - ++semiIt; - while (semiIt != end) - { - if (*semiIt < '0' || *semiIt > '9') - { - isVMS = false; break; - } - ++semiIt; - } - } - if (isVMS) - parseVMS(path); - else - parseUnix(path); - } -} - - -std::string Path::buildUnix() const -{ - std::string result; - if (!_device.empty()) - { - result.append("/"); - result.append(_device); - result.append(":/"); - } - else if (_absolute) - { - result.append("/"); - } - for (StringVec::const_iterator it = _dirs.begin(); it != _dirs.end(); ++it) - { - result.append(*it); - result.append("/"); - } - result.append(_name); - return result; -} - - -std::string Path::buildWindows() const -{ - std::string result; - if (!_node.empty()) - { - result.append("\\\\"); - result.append(_node); - result.append("\\"); - } - else if (!_device.empty()) - { - result.append(_device); - result.append(":\\"); - } - else if (_absolute) - { - result.append("\\"); - } - for (StringVec::const_iterator it = _dirs.begin(); it != _dirs.end(); ++it) - { - result.append(*it); - result.append("\\"); - } - result.append(_name); - return result; -} - - -std::string Path::buildVMS() const -{ - std::string result; - if (!_node.empty()) - { - result.append(_node); - result.append("::"); - } - if (!_device.empty()) - { - result.append(_device); - result.append(":"); - } - if (!_dirs.empty()) - { - result.append("["); - if (!_absolute && _dirs[0] != "..") - result.append("."); - for (StringVec::const_iterator it = _dirs.begin(); it != _dirs.end(); ++it) - { - if (it != _dirs.begin() && *it != "..") - result.append("."); - if (*it == "..") - result.append("-"); - else - result.append(*it); - } - result.append("]"); - } - result.append(_name); - if (!_version.empty()) - { - result.append(";"); - result.append(_version); - } - return result; -} - - -} // namespace Poco +// +// Path.cpp +// +// $Id: //poco/1.2/Foundation/src/Path.cpp#1 $ +// +// Library: Foundation +// Package: Filesystem +// Module: Path +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/Path.h" +#include "Poco/File.h" +#include "Poco/Exception.h" +#include "Poco/StringTokenizer.h" +#include + + +#if defined(POCO_OS_FAMILY_VMS) +#include "Path_VMS.cpp" +#elif defined(POCO_OS_FAMILY_UNIX) +#include "Path_UNIX.cpp" +#elif defined(POCO_OS_FAMILY_WINDOWS) && defined(POCO_WIN32_UTF8) +#include "Path_WIN32U.cpp" +#elif defined(POCO_OS_FAMILY_WINDOWS) +#include "Path_WIN32.cpp" +#endif + + +namespace Poco { + + +Path::Path(): _absolute(false) +{ +} + + +Path::Path(bool absolute): _absolute(absolute) +{ +} + + +Path::Path(const std::string& path) +{ + assign(path); +} + + +Path::Path(const std::string& path, Style style) +{ + assign(path, style); +} + + +Path::Path(const char* path) +{ + poco_check_ptr(path); + assign(path); +} + + +Path::Path(const char* path, Style style) +{ + poco_check_ptr(path); + assign(path, style); +} + + +Path::Path(const Path& path): + _node(path._node), + _device(path._device), + _name(path._name), + _version(path._version), + _dirs(path._dirs), + _absolute(path._absolute) +{ +} + + +Path::Path(const Path& parent, const std::string& fileName): + _node(parent._node), + _device(parent._device), + _name(parent._name), + _version(parent._version), + _dirs(parent._dirs), + _absolute(parent._absolute) +{ + makeDirectory(); + _name = fileName; +} + + +Path::Path(const Path& parent, const Path& relative): + _node(parent._node), + _device(parent._device), + _name(parent._name), + _version(parent._version), + _dirs(parent._dirs), + _absolute(parent._absolute) +{ + resolve(relative); +} + + +Path::~Path() +{ +} + + +Path& Path::operator = (const Path& path) +{ + return assign(path); +} + + +Path& Path::operator = (const std::string& path) +{ + return assign(path); +} + + +Path& Path::operator = (const char* path) +{ + poco_check_ptr(path); + return assign(path); +} + + +void Path::swap(Path& path) +{ + std::swap(_node, path._node); + std::swap(_device, path._device); + std::swap(_name, path._name); + std::swap(_version, path._version); + std::swap(_dirs, path._dirs); + std::swap(_absolute, path._absolute); +} + + +Path& Path::assign(const Path& path) +{ + if (&path != this) + { + _node = path._node; + _device = path._device; + _name = path._name; + _version = path._version; + _dirs = path._dirs; + _absolute = path._absolute; + } + return *this; +} + + +Path& Path::assign(const std::string& path) +{ +#if defined(POCO_OS_FAMILY_VMS) + parseVMS(path); +#elif defined(POCO_OS_FAMILY_WINDOWS) + parseWindows(path); +#else + parseUnix(path); +#endif + return *this; +} + + +Path& Path::assign(const std::string& path, Style style) +{ + switch (style) + { + case PATH_UNIX: + parseUnix(path); + break; + case PATH_WINDOWS: + parseWindows(path); + break; + case PATH_VMS: + parseVMS(path); + break; + case PATH_NATIVE: + assign(path); + break; + case PATH_GUESS: + parseGuess(path); + break; + default: + poco_bugcheck(); + } + return *this; +} + + +Path& Path::assign(const char* path) +{ + return assign(std::string(path)); +} + + +std::string Path::toString() const +{ +#if defined(POCO_OS_FAMILY_UNIX) + return buildUnix(); +#elif defined(POCO_OS_FAMILY_WINDOWS) + return buildWindows(); +#else + return buildVMS(); +#endif +} + + +std::string Path::toString(Style style) const +{ + switch (style) + { + case PATH_UNIX: + return buildUnix(); + case PATH_WINDOWS: + return buildWindows(); + case PATH_VMS: + return buildVMS(); + case PATH_NATIVE: + case PATH_GUESS: + return toString(); + default: + poco_bugcheck(); + } + return std::string(); +} + + +bool Path::tryParse(const std::string& path) +{ + try + { + Path p; + p.parse(path); + assign(p); + return true; + } + catch (...) + { + return false; + } +} + + +bool Path::tryParse(const std::string& path, Style style) +{ + try + { + Path p; + p.parse(path, style); + assign(p); + return true; + } + catch (...) + { + return false; + } +} + + +Path& Path::parseDirectory(const std::string& path) +{ + assign(path); + return makeDirectory(); +} + + +Path& Path::parseDirectory(const std::string& path, Style style) +{ + assign(path, style); + return makeDirectory(); +} + + +Path& Path::makeDirectory() +{ +#if defined(POCO_OS_FAMILY_VMS) + pushDirectory(getBaseName()); +#else + pushDirectory(_name); +#endif + _name.clear(); + _version.clear(); + return *this; +} + + +Path& Path::makeFile() +{ + if (!_dirs.empty() && _name.empty()) + { + _name = _dirs.back(); + _dirs.pop_back(); +#if defined(POCO_OS_FAMILY_VMS) + setExtension("DIR"); +#endif + } + return *this; +} + + +Path& Path::makeAbsolute() +{ + return makeAbsolute(current()); +} + + +Path& Path::makeAbsolute(const Path& base) +{ + if (!_absolute) + { + Path tmp = base; + tmp.makeDirectory(); + for (StringVec::const_iterator it = _dirs.begin(); it != _dirs.end(); ++it) + { + tmp.pushDirectory(*it); + } + _node = tmp._node; + _device = tmp._device; + _dirs = tmp._dirs; + _absolute = base._absolute; + } + return *this; +} + + +Path Path::absolute() const +{ + Path result(*this); + if (!result._absolute) + { + result.makeAbsolute(); + } + return result; +} + + +Path Path::absolute(const Path& base) const +{ + Path result(*this); + if (!result._absolute) + { + result.makeAbsolute(base); + } + return result; +} + + +Path Path::parent() const +{ + Path p(*this); + return p.makeParent(); +} + + +Path& Path::makeParent() +{ + if (_name.empty()) + { + if (_dirs.empty()) + { + if (!_absolute) + _dirs.push_back(".."); + } + else + { + if (_dirs.back() == "..") + _dirs.push_back(".."); + else + _dirs.pop_back(); + } + } + else + { + _name.clear(); + _version.clear(); + } + return *this; +} + + +Path& Path::append(const Path& path) +{ + makeDirectory(); + _dirs.insert(_dirs.end(), path._dirs.begin(), path._dirs.end()); + _name = path._name; + _version = path._version; + return *this; +} + + +Path& Path::resolve(const Path& path) +{ + if (path.isAbsolute()) + { + assign(path); + } + else + { + for (int i = 0; i < path.depth(); ++i) + pushDirectory(path[i]); + _name = path._name; + } + return *this; +} + + +void Path::setNode(const std::string& node) +{ + _node = node; + _absolute = _absolute || !node.empty(); +} + + +void Path::setDevice(const std::string& device) +{ + _device = device; + _absolute = _absolute || !device.empty(); +} + + +const std::string& Path::directory(int n) const +{ + poco_assert (0 <= n && n <= _dirs.size()); + + if (n < _dirs.size()) + return _dirs[n]; + else + return _name; +} + + +const std::string& Path::operator [] (int n) const +{ + poco_assert (0 <= n && n <= _dirs.size()); + + if (n < _dirs.size()) + return _dirs[n]; + else + return _name; +} + + +void Path::pushDirectory(const std::string& dir) +{ + if (!dir.empty() && dir != ".") + { +#if defined(POCO_OS_FAMILY_VMS) + if (dir == ".." || dir == "-") + { + if (!_dirs.empty() && _dirs.back() != ".." && _dirs.back() != "-") + _dirs.pop_back(); + else if (!_absolute) + _dirs.push_back(dir); + } + else _dirs.push_back(dir); +#else + if (dir == "..") + { + if (!_dirs.empty() && _dirs.back() != "..") + _dirs.pop_back(); + else if (!_absolute) + _dirs.push_back(dir); + } + else _dirs.push_back(dir); +#endif + } +} + + +void Path::popDirectory() +{ + poco_assert (!_dirs.empty()); + + _dirs.pop_back(); +} + + +void Path::setFileName(const std::string& name) +{ + _name = name; +} + + +void Path::setBaseName(const std::string& name) +{ + std::string ext = getExtension(); + _name = name; + if (!ext.empty()) + { + _name.append("."); + _name.append(ext); + } +} + + +std::string Path::getBaseName() const +{ + std::string::size_type pos = _name.rfind('.'); + if (pos != std::string::npos) + return _name.substr(0, pos); + else + return _name; +} + + +void Path::setExtension(const std::string& extension) +{ + _name = getBaseName(); + if (!extension.empty()) + { + _name.append("."); + _name.append(extension); + } +} + + +std::string Path::getExtension() const +{ + std::string::size_type pos = _name.rfind('.'); + if (pos != std::string::npos) + return _name.substr(pos + 1); + else + return std::string(); +} + + +void Path::clear() +{ + _node.clear(); + _device.clear(); + _name.clear(); + _dirs.clear(); + _version.clear(); + _absolute = false; +} + + +std::string Path::current() +{ + return PathImpl::currentImpl(); +} + + +std::string Path::home() +{ + return PathImpl::homeImpl(); +} + + +std::string Path::temp() +{ + return PathImpl::tempImpl(); +} + + +std::string Path::null() +{ + return PathImpl::nullImpl(); +} + + +std::string Path::expand(const std::string& path) +{ + return PathImpl::expandImpl(path); +} + + +void Path::listRoots(std::vector& roots) +{ + PathImpl::listRootsImpl(roots); +} + + +bool Path::find(StringVec::const_iterator it, StringVec::const_iterator end, const std::string& name, Path& path) +{ + while (it != end) + { + Path p(*it); + p.makeDirectory(); + p.resolve(Path(name)); + File f(p); + if (f.exists()) + { + path = p; + return true; + } + ++it; + } + return false; +} + + +bool Path::find(const std::string& pathList, const std::string& name, Path& path) +{ + StringTokenizer st(pathList, std::string(1, pathSeparator()), StringTokenizer::TOK_IGNORE_EMPTY + StringTokenizer::TOK_TRIM); + return find(st.begin(), st.end(), name, path); +} + + +void Path::parseUnix(const std::string& path) +{ + clear(); + + std::string::const_iterator it = path.begin(); + std::string::const_iterator end = path.end(); + + if (it != end) + { + if (*it == '/') + { + _absolute = true; ++it; + } + else if (*it == '~') + { + ++it; + if (it == end || *it == '/') + { + Path cwd(home()); + _dirs = cwd._dirs; + _absolute = true; + } + else --it; + } + + while (it != end) + { + std::string name; + while (it != end && *it != '/') name += *it++; + if (it != end) + { + if (_dirs.empty()) + { + if (!name.empty() && *(name.rbegin()) == ':') + _device.assign(name, 0, name.length() - 1); + else + pushDirectory(name); + } + else pushDirectory(name); + } + else _name = name; + if (it != end) ++it; + } + } +} + + +void Path::parseWindows(const std::string& path) +{ + clear(); + + std::string::const_iterator it = path.begin(); + std::string::const_iterator end = path.end(); + + if (it != end) + { + if (*it == '\\' || *it == '/') { _absolute = true; ++it; } + if (_absolute && it != end && (*it == '\\' || *it == '/')) // UNC + { + ++it; + while (it != end && *it != '\\' && *it != '/') _node += *it++; + if (it != end) ++it; + } + else if (it != end) + { + char d = *it++; + if (it != end && *it == ':') // drive letter + { + if (_absolute || !(d >= 'a' && d <= 'z' || d >= 'A' && d <= 'Z')) throw PathSyntaxException(path); + _absolute = true; + _device += d; + ++it; + if (it == end || *it != '\\' && *it != '/') throw PathSyntaxException(path); + ++it; + } + else --it; + } + while (it != end) + { + std::string name; + while (it != end && *it != '\\' && *it != '/') name += *it++; + if (it != end) + pushDirectory(name); + else + _name = name; + if (it != end) ++it; + } + } + if (!_node.empty() && _dirs.empty() && !_name.empty()) + makeDirectory(); +} + + +void Path::parseVMS(const std::string& path) +{ + clear(); + + std::string::const_iterator it = path.begin(); + std::string::const_iterator end = path.end(); + + if (it != end) + { + std::string name; + while (it != end && *it != ':' && *it != '[' && *it != ';') name += *it++; + if (it != end) + { + if (*it == ':') + { + ++it; + if (it != end && *it == ':') + { + _node = name; + ++it; + } + else _device = name; + _absolute = true; + name.clear(); + } + if (it != end) + { + if (_device.empty() && *it != '[') + { + while (it != end && *it != ':' && *it != ';') name += *it++; + if (it != end) + { + if (*it == ':') + { + _device = name; + _absolute = true; + name.clear(); + ++it; + } + } + } + } + if (name.empty()) + { + if (it != end && *it == '[') + { + ++it; + if (it != end) + { + _absolute = true; + if (*it == '.') + { _absolute = false; ++it; } + else if (*it == ']' || *it == '-') + _absolute = false; + while (it != end && *it != ']') + { + name.clear(); + if (*it == '-') + name = "-"; + else + while (it != end && *it != '.' && *it != ']') name += *it++; + if (!name.empty()) + { + if (name == "-") + { + if (_dirs.empty() || _dirs.back() == "..") + _dirs.push_back(".."); + else + _dirs.pop_back(); + } + else _dirs.push_back(name); + } + if (it != end && *it != ']') ++it; + } + if (it == end) throw PathSyntaxException(path); + ++it; + if (it != end && *it == '[') + { + if (!_absolute) throw PathSyntaxException(path); + ++it; + if (it != end && *it == '.') throw PathSyntaxException(path); + int d = int(_dirs.size()); + while (it != end && *it != ']') + { + name.clear(); + if (*it == '-') + name = "-"; + else + while (it != end && *it != '.' && *it != ']') name += *it++; + if (!name.empty()) + { + if (name == "-") + { + if (_dirs.size() > d) + _dirs.pop_back(); + } + else _dirs.push_back(name); + } + if (it != end && *it != ']') ++it; + } + if (it == end) throw PathSyntaxException(path); + ++it; + } + } + _name.clear(); + } + while (it != end && *it != ';') _name += *it++; + } + else _name = name; + if (it != end && *it == ';') + { + ++it; + while (it != end) _version += *it++; + } + } + else _name = name; + } +} + + +void Path::parseGuess(const std::string& path) +{ + bool hasBackslash = false; + bool hasSlash = false; + bool hasOpenBracket = false; + bool hasClosBracket = false; + bool isWindows = path.length() > 2 && path[1] == ':' && (path[2] == '/' || path[2] == '\\'); + std::string::const_iterator end = path.end(); + std::string::const_iterator semiIt = end; + if (!isWindows) + { + for (std::string::const_iterator it = path.begin(); it != end; ++it) + { + switch (*it) + { + case '\\': hasBackslash = true; break; + case '/': hasSlash = true; break; + case '[': hasOpenBracket = true; + case ']': hasClosBracket = hasOpenBracket; + case ';': semiIt = it; break; + } + } + } + if (hasBackslash || isWindows) + { + parseWindows(path); + } + else if (hasSlash) + { + parseUnix(path); + } + else + { + bool isVMS = hasClosBracket; + if (!isVMS && semiIt != end) + { + isVMS = true; + ++semiIt; + while (semiIt != end) + { + if (*semiIt < '0' || *semiIt > '9') + { + isVMS = false; break; + } + ++semiIt; + } + } + if (isVMS) + parseVMS(path); + else + parseUnix(path); + } +} + + +std::string Path::buildUnix() const +{ + std::string result; + if (!_device.empty()) + { + result.append("/"); + result.append(_device); + result.append(":/"); + } + else if (_absolute) + { + result.append("/"); + } + for (StringVec::const_iterator it = _dirs.begin(); it != _dirs.end(); ++it) + { + result.append(*it); + result.append("/"); + } + result.append(_name); + return result; +} + + +std::string Path::buildWindows() const +{ + std::string result; + if (!_node.empty()) + { + result.append("\\\\"); + result.append(_node); + result.append("\\"); + } + else if (!_device.empty()) + { + result.append(_device); + result.append(":\\"); + } + else if (_absolute) + { + result.append("\\"); + } + for (StringVec::const_iterator it = _dirs.begin(); it != _dirs.end(); ++it) + { + result.append(*it); + result.append("\\"); + } + result.append(_name); + return result; +} + + +std::string Path::buildVMS() const +{ + std::string result; + if (!_node.empty()) + { + result.append(_node); + result.append("::"); + } + if (!_device.empty()) + { + result.append(_device); + result.append(":"); + } + if (!_dirs.empty()) + { + result.append("["); + if (!_absolute && _dirs[0] != "..") + result.append("."); + for (StringVec::const_iterator it = _dirs.begin(); it != _dirs.end(); ++it) + { + if (it != _dirs.begin() && *it != "..") + result.append("."); + if (*it == "..") + result.append("-"); + else + result.append(*it); + } + result.append("]"); + } + result.append(_name); + if (!_version.empty()) + { + result.append(";"); + result.append(_version); + } + return result; +} + + +} // namespace Poco diff --git a/Foundation/src/Path_UNIX.cpp b/Foundation/src/Path_UNIX.cpp index 6fe41e4cb..67279b551 100644 --- a/Foundation/src/Path_UNIX.cpp +++ b/Foundation/src/Path_UNIX.cpp @@ -1,162 +1,162 @@ -// -// Path_UNIX.cpp -// -// $Id: //poco/1.2/Foundation/src/Path_UNIX.cpp#1 $ -// -// Library: Foundation -// Package: Filesystem -// Module: Path -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/Path_UNIX.h" -#include "Poco/Exception.h" -#include "Poco/Environment_UNIX.h" -#include -#include -#include -#include -#include -#include -#include - - -#ifndef PATH_MAX -#define PATH_MAX 1024 // fallback -#endif - - -namespace Poco { - - -std::string PathImpl::currentImpl() -{ - std::string path; - char cwd[PATH_MAX]; - if (getcwd(cwd, sizeof(cwd))) - path = cwd; - else - throw SystemException("cannot get current directory"); - std::string::size_type n = path.size(); - if (n > 0 && path[n - 1] != '/') path.append("/"); - return path; -} - - -std::string PathImpl::homeImpl() -{ - std::string path; - struct passwd* pwd = getpwuid(getuid()); - if (pwd) - path = pwd->pw_dir; - else - { - pwd = getpwuid(geteuid()); - if (pwd) - path = pwd->pw_dir; - else - path = EnvironmentImpl::getImpl("HOME"); - } - std::string::size_type n = path.size(); - if (n > 0 && path[n - 1] != '/') path.append("/"); - return path; -} - - -std::string PathImpl::tempImpl() -{ - std::string path; - char* tmp = getenv("TMPDIR"); - if (tmp) - { - path = tmp; - std::string::size_type n = path.size(); - if (n > 0 && path[n - 1] != '/') path.append("/"); - } - else - { - path = "/tmp/"; - } - return path; -} - - -std::string PathImpl::nullImpl() -{ - return "/dev/null"; -} - - -std::string PathImpl::expandImpl(const std::string& path) -{ - std::locale loc; - std::string result; - std::string::const_iterator it = path.begin(); - std::string::const_iterator end = path.end(); - if (it != end && *it == '~') - { - ++it; - if (it != end && *it == '/') - { - result += homeImpl(); ++it; - } - else result += '~'; - } - while (it != end) - { - if (*it == '$') - { - std::string var; - ++it; - if (it != end && *it == '{') - { - ++it; - while (it != end && *it != '}') var += *it++; - if (it != end) ++it; - } - else - { - while (it != end && (isalnum(*it, loc) || *it == '_')) var += *it++; - } - char* val = getenv(var.c_str()); - if (val) result += val; - } - else result += *it++; - } - return result; -} - - -void PathImpl::listRootsImpl(std::vector& roots) -{ - roots.clear(); - roots.push_back("/"); -} - - -} // namespace Poco +// +// Path_UNIX.cpp +// +// $Id: //poco/1.2/Foundation/src/Path_UNIX.cpp#1 $ +// +// Library: Foundation +// Package: Filesystem +// Module: Path +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/Path_UNIX.h" +#include "Poco/Exception.h" +#include "Poco/Environment_UNIX.h" +#include +#include +#include +#include +#include +#include +#include + + +#ifndef PATH_MAX +#define PATH_MAX 1024 // fallback +#endif + + +namespace Poco { + + +std::string PathImpl::currentImpl() +{ + std::string path; + char cwd[PATH_MAX]; + if (getcwd(cwd, sizeof(cwd))) + path = cwd; + else + throw SystemException("cannot get current directory"); + std::string::size_type n = path.size(); + if (n > 0 && path[n - 1] != '/') path.append("/"); + return path; +} + + +std::string PathImpl::homeImpl() +{ + std::string path; + struct passwd* pwd = getpwuid(getuid()); + if (pwd) + path = pwd->pw_dir; + else + { + pwd = getpwuid(geteuid()); + if (pwd) + path = pwd->pw_dir; + else + path = EnvironmentImpl::getImpl("HOME"); + } + std::string::size_type n = path.size(); + if (n > 0 && path[n - 1] != '/') path.append("/"); + return path; +} + + +std::string PathImpl::tempImpl() +{ + std::string path; + char* tmp = getenv("TMPDIR"); + if (tmp) + { + path = tmp; + std::string::size_type n = path.size(); + if (n > 0 && path[n - 1] != '/') path.append("/"); + } + else + { + path = "/tmp/"; + } + return path; +} + + +std::string PathImpl::nullImpl() +{ + return "/dev/null"; +} + + +std::string PathImpl::expandImpl(const std::string& path) +{ + std::locale loc; + std::string result; + std::string::const_iterator it = path.begin(); + std::string::const_iterator end = path.end(); + if (it != end && *it == '~') + { + ++it; + if (it != end && *it == '/') + { + result += homeImpl(); ++it; + } + else result += '~'; + } + while (it != end) + { + if (*it == '$') + { + std::string var; + ++it; + if (it != end && *it == '{') + { + ++it; + while (it != end && *it != '}') var += *it++; + if (it != end) ++it; + } + else + { + while (it != end && (isalnum(*it, loc) || *it == '_')) var += *it++; + } + char* val = getenv(var.c_str()); + if (val) result += val; + } + else result += *it++; + } + return result; +} + + +void PathImpl::listRootsImpl(std::vector& roots) +{ + roots.clear(); + roots.push_back("/"); +} + + +} // namespace Poco diff --git a/Foundation/src/Path_VMS.cpp b/Foundation/src/Path_VMS.cpp index 7135f820a..f98852118 100644 --- a/Foundation/src/Path_VMS.cpp +++ b/Foundation/src/Path_VMS.cpp @@ -1,139 +1,139 @@ -// -// Path_VMS.cpp -// -// $Id: //poco/1.2/Foundation/src/Path_VMS.cpp#1 $ -// -// Library: Foundation -// Package: Filesystem -// Module: Path -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/Path_VMS.h" -#include "Poco/Environment_VMS.h" -#include -#include -#include -#include -#include -#include -#include - - -namespace Poco { - - -std::string PathImpl::currentImpl() -{ - std::string path; - char cwd[PATH_MAX]; - if (getcwd(cwd, sizeof(cwd))) - path = cwd; - else - throw SystemException("cannot get current directory"); - return path; -} - - -std::string PathImpl::homeImpl() -{ - return EnvironmentImpl::trnlnm("SYS$LOGIN"); -} - - -std::string PathImpl::tempImpl() -{ - std::string result = EnvironmentImpl::trnlnm("SYS$SCRATCH"); - if (result.empty()) - return homeImpl(); - else - return result; -} - - -std::string PathImpl::nullImpl() -{ - return "NLA0:"; -} - - -std::string PathImpl::expandImpl(const std::string& path) -{ - std::string result = path; - std::string::const_iterator it = result.begin(); - std::string::const_iterator end = result.end(); - int n = 0; - while (it != end && n < 10) - { - std::string logical; - while (it != end && *it != ':') logical += *it++; - if (it != end) - { - ++it; - if (it != end && *it == ':') return result; - std::string val = EnvironmentImpl::trnlnm(logical); - if (val.empty()) - return result; - else - result = val + std::string(it, end); - it = result.begin(); - end = result.end(); - ++n; - } - } - return result; -} - - -void PathImpl::listRootsImpl(std::vector& roots) -{ - char device[64]; - $DESCRIPTOR(deviceDsc, device); - int clss = DC$_DISK; - ILE3 items[2]; - items[0].ile3$w_code = DVS$_DEVCLASS; - items[0].ile3$w_length = sizeof(clss); - items[0].ile3$ps_bufaddr = &clss; - items[0].ile3$ps_retlen_addr = 0; - items[1].ile3$w_code = 0; - items[1].ile3$w_length = 0; - int stat; - GENERIC_64 context; - context.gen64$q_quadword = 0; - do - { - unsigned short length; - stat = sys$device_scan(&deviceDsc, &length, 0, &items, &context); - if (stat == SS$_NORMAL) - roots.push_back(std::string(device, length)); - } - while (stat == SS$_NORMAL); -} - - -} // namespace Poco +// +// Path_VMS.cpp +// +// $Id: //poco/1.2/Foundation/src/Path_VMS.cpp#1 $ +// +// Library: Foundation +// Package: Filesystem +// Module: Path +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/Path_VMS.h" +#include "Poco/Environment_VMS.h" +#include +#include +#include +#include +#include +#include +#include + + +namespace Poco { + + +std::string PathImpl::currentImpl() +{ + std::string path; + char cwd[PATH_MAX]; + if (getcwd(cwd, sizeof(cwd))) + path = cwd; + else + throw SystemException("cannot get current directory"); + return path; +} + + +std::string PathImpl::homeImpl() +{ + return EnvironmentImpl::trnlnm("SYS$LOGIN"); +} + + +std::string PathImpl::tempImpl() +{ + std::string result = EnvironmentImpl::trnlnm("SYS$SCRATCH"); + if (result.empty()) + return homeImpl(); + else + return result; +} + + +std::string PathImpl::nullImpl() +{ + return "NLA0:"; +} + + +std::string PathImpl::expandImpl(const std::string& path) +{ + std::string result = path; + std::string::const_iterator it = result.begin(); + std::string::const_iterator end = result.end(); + int n = 0; + while (it != end && n < 10) + { + std::string logical; + while (it != end && *it != ':') logical += *it++; + if (it != end) + { + ++it; + if (it != end && *it == ':') return result; + std::string val = EnvironmentImpl::trnlnm(logical); + if (val.empty()) + return result; + else + result = val + std::string(it, end); + it = result.begin(); + end = result.end(); + ++n; + } + } + return result; +} + + +void PathImpl::listRootsImpl(std::vector& roots) +{ + char device[64]; + $DESCRIPTOR(deviceDsc, device); + int clss = DC$_DISK; + ILE3 items[2]; + items[0].ile3$w_code = DVS$_DEVCLASS; + items[0].ile3$w_length = sizeof(clss); + items[0].ile3$ps_bufaddr = &clss; + items[0].ile3$ps_retlen_addr = 0; + items[1].ile3$w_code = 0; + items[1].ile3$w_length = 0; + int stat; + GENERIC_64 context; + context.gen64$q_quadword = 0; + do + { + unsigned short length; + stat = sys$device_scan(&deviceDsc, &length, 0, &items, &context); + if (stat == SS$_NORMAL) + roots.push_back(std::string(device, length)); + } + while (stat == SS$_NORMAL); +} + + +} // namespace Poco diff --git a/Foundation/src/Path_WIN32.cpp b/Foundation/src/Path_WIN32.cpp index 97557e36b..f92ca63f2 100644 --- a/Foundation/src/Path_WIN32.cpp +++ b/Foundation/src/Path_WIN32.cpp @@ -1,120 +1,120 @@ -// -// Path_WIN32.cpp -// -// $Id: //poco/1.2/Foundation/src/Path_WIN32.cpp#1 $ -// -// Library: Foundation -// Package: Filesystem -// Module: Path -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/Path_WIN32.h" -#include "Poco/Environment_WIN32.h" -#include - - -namespace Poco { - - -std::string PathImpl::currentImpl() -{ - char buffer[_MAX_PATH]; - DWORD n = GetCurrentDirectory(sizeof(buffer), buffer); - if (n > 0 && n < sizeof(buffer)) - { - std::string result(buffer, n); - if (result[n - 1] != '\\') - result.append("\\"); - return result; - } - else throw SystemException("Cannot get current directory"); -} - - -std::string PathImpl::homeImpl() -{ - std::string result = EnvironmentImpl::getImpl("HOMEDRIVE"); - result.append(EnvironmentImpl::getImpl("HOMEPATH")); - std::string::size_type n = result.size(); - if (n > 0 && result[n - 1] != '\\') - result.append("\\"); - return result; -} - - -std::string PathImpl::tempImpl() -{ - char buffer[_MAX_PATH]; - DWORD n = GetTempPath(sizeof(buffer), buffer); - if (n > 0 && n < sizeof(buffer)) - { - std::string result(buffer, n); - if (result[n - 1] != '\\') - result.append("\\"); - return result; - } - else throw SystemException("Cannot get current directory"); -} - - -std::string PathImpl::nullImpl() -{ - return "NUL:"; -} - - -std::string PathImpl::expandImpl(const std::string& path) -{ - char buffer[_MAX_PATH]; - DWORD n = ExpandEnvironmentStrings(path.c_str(), buffer, sizeof(buffer)); - if (n > 0 && n < sizeof(buffer)) - return std::string(buffer, n - 1); - else - return path; -} - - -void PathImpl::listRootsImpl(std::vector& roots) -{ - roots.clear(); - char buffer[128]; - DWORD n = GetLogicalDriveStrings(sizeof(buffer) - 1, buffer); - char* it = buffer; - char* end = buffer + (n > sizeof(buffer) ? sizeof(buffer) : n); - while (it < end) - { - std::string dev; - while (it < end && *it) dev += *it++; - roots.push_back(dev); - ++it; - } -} - - -} // namespace Poco +// +// Path_WIN32.cpp +// +// $Id: //poco/1.2/Foundation/src/Path_WIN32.cpp#1 $ +// +// Library: Foundation +// Package: Filesystem +// Module: Path +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/Path_WIN32.h" +#include "Poco/Environment_WIN32.h" +#include + + +namespace Poco { + + +std::string PathImpl::currentImpl() +{ + char buffer[_MAX_PATH]; + DWORD n = GetCurrentDirectory(sizeof(buffer), buffer); + if (n > 0 && n < sizeof(buffer)) + { + std::string result(buffer, n); + if (result[n - 1] != '\\') + result.append("\\"); + return result; + } + else throw SystemException("Cannot get current directory"); +} + + +std::string PathImpl::homeImpl() +{ + std::string result = EnvironmentImpl::getImpl("HOMEDRIVE"); + result.append(EnvironmentImpl::getImpl("HOMEPATH")); + std::string::size_type n = result.size(); + if (n > 0 && result[n - 1] != '\\') + result.append("\\"); + return result; +} + + +std::string PathImpl::tempImpl() +{ + char buffer[_MAX_PATH]; + DWORD n = GetTempPath(sizeof(buffer), buffer); + if (n > 0 && n < sizeof(buffer)) + { + std::string result(buffer, n); + if (result[n - 1] != '\\') + result.append("\\"); + return result; + } + else throw SystemException("Cannot get current directory"); +} + + +std::string PathImpl::nullImpl() +{ + return "NUL:"; +} + + +std::string PathImpl::expandImpl(const std::string& path) +{ + char buffer[_MAX_PATH]; + DWORD n = ExpandEnvironmentStrings(path.c_str(), buffer, sizeof(buffer)); + if (n > 0 && n < sizeof(buffer)) + return std::string(buffer, n - 1); + else + return path; +} + + +void PathImpl::listRootsImpl(std::vector& roots) +{ + roots.clear(); + char buffer[128]; + DWORD n = GetLogicalDriveStrings(sizeof(buffer) - 1, buffer); + char* it = buffer; + char* end = buffer + (n > sizeof(buffer) ? sizeof(buffer) : n); + while (it < end) + { + std::string dev; + while (it < end && *it) dev += *it++; + roots.push_back(dev); + ++it; + } +} + + +} // namespace Poco diff --git a/Foundation/src/Path_WIN32U.cpp b/Foundation/src/Path_WIN32U.cpp index df9bbf305..137ca9ecc 100644 --- a/Foundation/src/Path_WIN32U.cpp +++ b/Foundation/src/Path_WIN32U.cpp @@ -1,137 +1,137 @@ -// -// Path_WIN32U.cpp -// -// $Id: //poco/1.2/Foundation/src/Path_WIN32U.cpp#1 $ -// -// Library: Foundation -// Package: Filesystem -// Module: Path -// -// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/Path_WIN32U.h" -#include "Poco/Environment_WIN32.h" -#include "Poco/UnicodeConverter.h" -#include "Poco/Buffer.h" -#include "Poco/Exception.h" -#include - - -namespace Poco { - - -std::string PathImpl::currentImpl() -{ - std::string result; - DWORD len = GetCurrentDirectoryW(0, NULL); - if (len > 0) - { - Buffer buffer(len); - DWORD n = GetCurrentDirectoryW(len, buffer.begin()); - if (n > 0 && n <= len) - { - UnicodeConverter::toUTF8(buffer.begin(), result); - if (result[n - 1] != '\\') - result.append("\\"); - return result; - } - } - throw SystemException("Cannot get current directory"); -} - - -std::string PathImpl::homeImpl() -{ - std::string result = EnvironmentImpl::getImpl("HOMEDRIVE"); - result.append(EnvironmentImpl::getImpl("HOMEPATH")); - std::string::size_type n = result.size(); - if (n > 0 && result[n - 1] != '\\') - result.append("\\"); - return result; -} - - -std::string PathImpl::tempImpl() -{ - Buffer buffer(MAX_PATH_LEN); - DWORD n = GetTempPathW(buffer.size(), buffer.begin()); - if (n > 0) - { - std::string result; - UnicodeConverter::toUTF8(buffer.begin(), result); - if (result[n - 1] != '\\') - result.append("\\"); - return result; - } - throw SystemException("Cannot get current directory"); -} - - -std::string PathImpl::nullImpl() -{ - return "NUL:"; -} - - -std::string PathImpl::expandImpl(const std::string& path) -{ - std::wstring upath; - UnicodeConverter::toUTF16(path, upath); - Buffer buffer(MAX_PATH_LEN); - DWORD n = ExpandEnvironmentStringsW(upath.c_str(), buffer.begin(), buffer.size()); - if (n > 0 && n < buffer.size() - 1) - { - buffer[n + 1] = 0; - std::string result; - UnicodeConverter::toUTF8(buffer.begin(), result); - return result; - } - else return path; -} - - -void PathImpl::listRootsImpl(std::vector& roots) -{ - roots.clear(); - wchar_t buffer[128]; - DWORD n = GetLogicalDriveStringsW(sizeof(buffer)/sizeof(wchar_t) - 1, buffer); - wchar_t* it = buffer; - wchar_t* end = buffer + (n > sizeof(buffer) ? sizeof(buffer) : n); - while (it < end) - { - std::wstring udev; - while (it < end && *it) udev += *it++; - std::string dev; - UnicodeConverter::toUTF8(udev, dev); - roots.push_back(dev); - ++it; - } -} - - -} // namespace Poco +// +// Path_WIN32U.cpp +// +// $Id: //poco/1.2/Foundation/src/Path_WIN32U.cpp#1 $ +// +// Library: Foundation +// Package: Filesystem +// Module: Path +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/Path_WIN32U.h" +#include "Poco/Environment_WIN32.h" +#include "Poco/UnicodeConverter.h" +#include "Poco/Buffer.h" +#include "Poco/Exception.h" +#include + + +namespace Poco { + + +std::string PathImpl::currentImpl() +{ + std::string result; + DWORD len = GetCurrentDirectoryW(0, NULL); + if (len > 0) + { + Buffer buffer(len); + DWORD n = GetCurrentDirectoryW(len, buffer.begin()); + if (n > 0 && n <= len) + { + UnicodeConverter::toUTF8(buffer.begin(), result); + if (result[n - 1] != '\\') + result.append("\\"); + return result; + } + } + throw SystemException("Cannot get current directory"); +} + + +std::string PathImpl::homeImpl() +{ + std::string result = EnvironmentImpl::getImpl("HOMEDRIVE"); + result.append(EnvironmentImpl::getImpl("HOMEPATH")); + std::string::size_type n = result.size(); + if (n > 0 && result[n - 1] != '\\') + result.append("\\"); + return result; +} + + +std::string PathImpl::tempImpl() +{ + Buffer buffer(MAX_PATH_LEN); + DWORD n = GetTempPathW(buffer.size(), buffer.begin()); + if (n > 0) + { + std::string result; + UnicodeConverter::toUTF8(buffer.begin(), result); + if (result[n - 1] != '\\') + result.append("\\"); + return result; + } + throw SystemException("Cannot get current directory"); +} + + +std::string PathImpl::nullImpl() +{ + return "NUL:"; +} + + +std::string PathImpl::expandImpl(const std::string& path) +{ + std::wstring upath; + UnicodeConverter::toUTF16(path, upath); + Buffer buffer(MAX_PATH_LEN); + DWORD n = ExpandEnvironmentStringsW(upath.c_str(), buffer.begin(), buffer.size()); + if (n > 0 && n < buffer.size() - 1) + { + buffer[n + 1] = 0; + std::string result; + UnicodeConverter::toUTF8(buffer.begin(), result); + return result; + } + else return path; +} + + +void PathImpl::listRootsImpl(std::vector& roots) +{ + roots.clear(); + wchar_t buffer[128]; + DWORD n = GetLogicalDriveStringsW(sizeof(buffer)/sizeof(wchar_t) - 1, buffer); + wchar_t* it = buffer; + wchar_t* end = buffer + (n > sizeof(buffer) ? sizeof(buffer) : n); + while (it < end) + { + std::wstring udev; + while (it < end && *it) udev += *it++; + std::string dev; + UnicodeConverter::toUTF8(udev, dev); + roots.push_back(dev); + ++it; + } +} + + +} // namespace Poco diff --git a/Foundation/src/PatternFormatter.cpp b/Foundation/src/PatternFormatter.cpp index 1c7416423..f72ed3461 100644 --- a/Foundation/src/PatternFormatter.cpp +++ b/Foundation/src/PatternFormatter.cpp @@ -1,190 +1,190 @@ -// -// PatternFormatter.cpp -// -// $Id: //poco/1.2/Foundation/src/PatternFormatter.cpp#1 $ -// -// Library: Foundation -// Package: Logging -// Module: PatternFormatter -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/PatternFormatter.h" -#include "Poco/Message.h" -#include "Poco/DateTimeFormat.h" -#include "Poco/DateTimeFormatter.h" -#include "Poco/DateTime.h" -#include "Poco/Timestamp.h" -#include "Poco/Timezone.h" -#include "Poco/NumberFormatter.h" -#include "Poco/Environment.h" - - -namespace Poco { - - -const std::string PatternFormatter::PROP_PATTERN = "pattern"; -const std::string PatternFormatter::PROP_TIMES = "times"; - - -PatternFormatter::PatternFormatter(): - _localTime(false) -{ -} - - -PatternFormatter::PatternFormatter(const std::string& format): - _localTime(false), - _pattern(format) -{ -} - - -PatternFormatter::~PatternFormatter() -{ -} - - -void PatternFormatter::format(const Message& msg, std::string& text) -{ - Timestamp timestamp = msg.getTime(); - if (_localTime) - { - timestamp += Timezone::utcOffset()*Timestamp::resolution(); - timestamp += Timezone::dst()*Timestamp::resolution(); - } - DateTime dateTime = timestamp; - std::string::const_iterator it = _pattern.begin(); - std::string::const_iterator end = _pattern.end(); - while (it != end) - { - if (*it == '%') - { - if (++it != end) - { - switch (*it) - { - case 's': text.append(msg.getSource()); break; - case 't': text.append(msg.getText()); break; - case 'l': text.append(NumberFormatter::format((int) msg.getPriority())); break; - case 'p': text.append(getPriorityName((int) msg.getPriority())); break; - case 'q': text += getPriorityName((int) msg.getPriority()).at(0); break; - case 'P': text.append(NumberFormatter::format(msg.getPid())); break; - case 'T': text.append(msg.getThread()); break; - case 'I': text.append(NumberFormatter::format(msg.getTid())); break; - case 'N': text.append(Environment::nodeName()); break; - case 'w': text.append(DateTimeFormat::WEEKDAY_NAMES[dateTime.dayOfWeek()], 0, 3); break; - case 'W': text.append(DateTimeFormat::WEEKDAY_NAMES[dateTime.dayOfWeek()]); break; - case 'b': text.append(DateTimeFormat::MONTH_NAMES[dateTime.month() - 1], 0, 3); break; - case 'B': text.append(DateTimeFormat::MONTH_NAMES[dateTime.month() - 1]); break; - case 'd': text.append(NumberFormatter::format0(dateTime.day(), 2)); break; - case 'e': text.append(NumberFormatter::format(dateTime.day())); break; - case 'f': text.append(NumberFormatter::format(dateTime.day(), 2)); break; - case 'm': text.append(NumberFormatter::format0(dateTime.month(), 2)); break; - case 'n': text.append(NumberFormatter::format(dateTime.month())); break; - case 'o': text.append(NumberFormatter::format(dateTime.month(), 2)); break; - case 'y': text.append(NumberFormatter::format0(dateTime.year() % 100, 2)); break; - case 'Y': text.append(NumberFormatter::format0(dateTime.year(), 4)); break; - case 'H': text.append(NumberFormatter::format0(dateTime.hour(), 2)); break; - case 'h': text.append(NumberFormatter::format0(dateTime.hourAMPM(), 2)); break; - case 'a': text.append(dateTime.isAM() ? "am" : "pm"); break; - case 'A': text.append(dateTime.isAM() ? "AM" : "PM"); break; - case 'M': text.append(NumberFormatter::format0(dateTime.minute(), 2)); break; - case 'S': text.append(NumberFormatter::format0(dateTime.second(), 2)); break; - case 'i': text.append(NumberFormatter::format0(dateTime.millisecond(), 3)); break; - case 'c': text.append(NumberFormatter::format(dateTime.millisecond()/100)); break; - case 'z': text.append(DateTimeFormatter::tzdISO(_localTime ? Timezone::tzd() : DateTimeFormatter::UTC)); break; - case 'Z': text.append(DateTimeFormatter::tzdRFC(_localTime ? Timezone::tzd() : DateTimeFormatter::UTC)); break; - case '[': - { - ++it; - std::string prop; - while (it != end && *it != ']') prop += *it++; - if (it != end) ++it; - try - { - text.append(msg[prop]); - } - catch (...) - { - } - break; - } - default: text += *it; - } - ++it; - } - } - else text += *it++; - } -} - - -void PatternFormatter::setProperty(const std::string& name, const std::string& value) -{ - if (name == PROP_PATTERN) - _pattern = value; - else if (name == PROP_TIMES) - _localTime = (value == "local"); - else - Formatter::setProperty(name, value); -} - - -std::string PatternFormatter::getProperty(const std::string& name) const -{ - if (name == PROP_PATTERN) - return _pattern; - else if (name == PROP_TIMES) - return _localTime ? "local" : "UTC"; - else - return Formatter::getProperty(name); -} - - -const std::string& PatternFormatter::getPriorityName(int prio) -{ - static std::string priorities[] = - { - "", - "Fatal", - "Critical", - "Error", - "Warning", - "Notice", - "Information", - "Debug", - "Trace" - }; - - poco_assert (1 <= prio && prio <= 8); - return priorities[prio]; -} - - -} // namespace Poco +// +// PatternFormatter.cpp +// +// $Id: //poco/1.2/Foundation/src/PatternFormatter.cpp#1 $ +// +// Library: Foundation +// Package: Logging +// Module: PatternFormatter +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/PatternFormatter.h" +#include "Poco/Message.h" +#include "Poco/DateTimeFormat.h" +#include "Poco/DateTimeFormatter.h" +#include "Poco/DateTime.h" +#include "Poco/Timestamp.h" +#include "Poco/Timezone.h" +#include "Poco/NumberFormatter.h" +#include "Poco/Environment.h" + + +namespace Poco { + + +const std::string PatternFormatter::PROP_PATTERN = "pattern"; +const std::string PatternFormatter::PROP_TIMES = "times"; + + +PatternFormatter::PatternFormatter(): + _localTime(false) +{ +} + + +PatternFormatter::PatternFormatter(const std::string& format): + _localTime(false), + _pattern(format) +{ +} + + +PatternFormatter::~PatternFormatter() +{ +} + + +void PatternFormatter::format(const Message& msg, std::string& text) +{ + Timestamp timestamp = msg.getTime(); + if (_localTime) + { + timestamp += Timezone::utcOffset()*Timestamp::resolution(); + timestamp += Timezone::dst()*Timestamp::resolution(); + } + DateTime dateTime = timestamp; + std::string::const_iterator it = _pattern.begin(); + std::string::const_iterator end = _pattern.end(); + while (it != end) + { + if (*it == '%') + { + if (++it != end) + { + switch (*it) + { + case 's': text.append(msg.getSource()); break; + case 't': text.append(msg.getText()); break; + case 'l': text.append(NumberFormatter::format((int) msg.getPriority())); break; + case 'p': text.append(getPriorityName((int) msg.getPriority())); break; + case 'q': text += getPriorityName((int) msg.getPriority()).at(0); break; + case 'P': text.append(NumberFormatter::format(msg.getPid())); break; + case 'T': text.append(msg.getThread()); break; + case 'I': text.append(NumberFormatter::format(msg.getTid())); break; + case 'N': text.append(Environment::nodeName()); break; + case 'w': text.append(DateTimeFormat::WEEKDAY_NAMES[dateTime.dayOfWeek()], 0, 3); break; + case 'W': text.append(DateTimeFormat::WEEKDAY_NAMES[dateTime.dayOfWeek()]); break; + case 'b': text.append(DateTimeFormat::MONTH_NAMES[dateTime.month() - 1], 0, 3); break; + case 'B': text.append(DateTimeFormat::MONTH_NAMES[dateTime.month() - 1]); break; + case 'd': text.append(NumberFormatter::format0(dateTime.day(), 2)); break; + case 'e': text.append(NumberFormatter::format(dateTime.day())); break; + case 'f': text.append(NumberFormatter::format(dateTime.day(), 2)); break; + case 'm': text.append(NumberFormatter::format0(dateTime.month(), 2)); break; + case 'n': text.append(NumberFormatter::format(dateTime.month())); break; + case 'o': text.append(NumberFormatter::format(dateTime.month(), 2)); break; + case 'y': text.append(NumberFormatter::format0(dateTime.year() % 100, 2)); break; + case 'Y': text.append(NumberFormatter::format0(dateTime.year(), 4)); break; + case 'H': text.append(NumberFormatter::format0(dateTime.hour(), 2)); break; + case 'h': text.append(NumberFormatter::format0(dateTime.hourAMPM(), 2)); break; + case 'a': text.append(dateTime.isAM() ? "am" : "pm"); break; + case 'A': text.append(dateTime.isAM() ? "AM" : "PM"); break; + case 'M': text.append(NumberFormatter::format0(dateTime.minute(), 2)); break; + case 'S': text.append(NumberFormatter::format0(dateTime.second(), 2)); break; + case 'i': text.append(NumberFormatter::format0(dateTime.millisecond(), 3)); break; + case 'c': text.append(NumberFormatter::format(dateTime.millisecond()/100)); break; + case 'z': text.append(DateTimeFormatter::tzdISO(_localTime ? Timezone::tzd() : DateTimeFormatter::UTC)); break; + case 'Z': text.append(DateTimeFormatter::tzdRFC(_localTime ? Timezone::tzd() : DateTimeFormatter::UTC)); break; + case '[': + { + ++it; + std::string prop; + while (it != end && *it != ']') prop += *it++; + if (it != end) ++it; + try + { + text.append(msg[prop]); + } + catch (...) + { + } + break; + } + default: text += *it; + } + ++it; + } + } + else text += *it++; + } +} + + +void PatternFormatter::setProperty(const std::string& name, const std::string& value) +{ + if (name == PROP_PATTERN) + _pattern = value; + else if (name == PROP_TIMES) + _localTime = (value == "local"); + else + Formatter::setProperty(name, value); +} + + +std::string PatternFormatter::getProperty(const std::string& name) const +{ + if (name == PROP_PATTERN) + return _pattern; + else if (name == PROP_TIMES) + return _localTime ? "local" : "UTC"; + else + return Formatter::getProperty(name); +} + + +const std::string& PatternFormatter::getPriorityName(int prio) +{ + static std::string priorities[] = + { + "", + "Fatal", + "Critical", + "Error", + "Warning", + "Notice", + "Information", + "Debug", + "Trace" + }; + + poco_assert (1 <= prio && prio <= 8); + return priorities[prio]; +} + + +} // namespace Poco diff --git a/Foundation/src/Pipe.cpp b/Foundation/src/Pipe.cpp index 86cfcfc21..2380ec01e 100644 --- a/Foundation/src/Pipe.cpp +++ b/Foundation/src/Pipe.cpp @@ -1,92 +1,92 @@ -// -// Pipe.cpp -// -// $Id: //poco/1.2/Foundation/src/Pipe.cpp#1 $ -// -// Library: Foundation -// Package: Processes -// Module: Pipe -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/Pipe.h" - - -namespace Poco { - - -Pipe::Pipe(): - _pImpl(new PipeImpl) -{ -} - - -Pipe::Pipe(const Pipe& pipe): - _pImpl(pipe._pImpl) -{ - _pImpl->duplicate(); -} - - -Pipe::~Pipe() -{ - _pImpl->release(); -} - - -Pipe& Pipe::operator = (const Pipe& pipe) -{ - if (this != &pipe) - { - _pImpl->release(); - _pImpl = pipe._pImpl; - _pImpl->duplicate(); - } - return *this; -} - - -void Pipe::close(CloseMode mode) -{ - switch (mode) - { - case CLOSE_READ: - _pImpl->closeRead(); - break; - case CLOSE_WRITE: - _pImpl->closeWrite(); - break; - default: - _pImpl->closeRead(); - _pImpl->closeWrite(); - break; - } -} - - -} // namespace Poco +// +// Pipe.cpp +// +// $Id: //poco/1.2/Foundation/src/Pipe.cpp#1 $ +// +// Library: Foundation +// Package: Processes +// Module: Pipe +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/Pipe.h" + + +namespace Poco { + + +Pipe::Pipe(): + _pImpl(new PipeImpl) +{ +} + + +Pipe::Pipe(const Pipe& pipe): + _pImpl(pipe._pImpl) +{ + _pImpl->duplicate(); +} + + +Pipe::~Pipe() +{ + _pImpl->release(); +} + + +Pipe& Pipe::operator = (const Pipe& pipe) +{ + if (this != &pipe) + { + _pImpl->release(); + _pImpl = pipe._pImpl; + _pImpl->duplicate(); + } + return *this; +} + + +void Pipe::close(CloseMode mode) +{ + switch (mode) + { + case CLOSE_READ: + _pImpl->closeRead(); + break; + case CLOSE_WRITE: + _pImpl->closeWrite(); + break; + default: + _pImpl->closeRead(); + _pImpl->closeWrite(); + break; + } +} + + +} // namespace Poco diff --git a/Foundation/src/PipeImpl.cpp b/Foundation/src/PipeImpl.cpp index d1f495672..726512534 100644 --- a/Foundation/src/PipeImpl.cpp +++ b/Foundation/src/PipeImpl.cpp @@ -1,46 +1,46 @@ -// -// PipeImpl.cpp -// -// $Id: //poco/1.2/Foundation/src/PipeImpl.cpp#1 $ -// -// Library: Foundation -// Package: Processes -// Module: PipeImpl -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/PipeImpl.h" - - -#if defined(POCO_OS_FAMILY_WINDOWS) -#include "PipeImpl_WIN32.cpp" -#elif defined(POCO_OS_FAMILY_UNIX) -#include "PipeImpl_POSIX.cpp" -#else -#include "PipeImpl_DUMMY.cpp" -#endif +// +// PipeImpl.cpp +// +// $Id: //poco/1.2/Foundation/src/PipeImpl.cpp#1 $ +// +// Library: Foundation +// Package: Processes +// Module: PipeImpl +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/PipeImpl.h" + + +#if defined(POCO_OS_FAMILY_WINDOWS) +#include "PipeImpl_WIN32.cpp" +#elif defined(POCO_OS_FAMILY_UNIX) +#include "PipeImpl_POSIX.cpp" +#else +#include "PipeImpl_DUMMY.cpp" +#endif diff --git a/Foundation/src/PipeImpl_DUMMY.cpp b/Foundation/src/PipeImpl_DUMMY.cpp index 89e4f7c8d..ff74df06a 100644 --- a/Foundation/src/PipeImpl_DUMMY.cpp +++ b/Foundation/src/PipeImpl_DUMMY.cpp @@ -1,87 +1,87 @@ -// -// PipeImpl_DUMMY.cpp -// -// $Id: //poco/1.2/Foundation/src/PipeImpl_DUMMY.cpp#1 $ -// -// Library: Foundation -// Package: Processes -// Module: PipeImpl -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/PipeImpl_DUMMY.h" - - -namespace Poco { - - -PipeImpl::PipeImpl() -{ -} - - -PipeImpl::~PipeImpl() -{ -} - - -int PipeImpl::writeBytes(const void* buffer, int length) -{ - return 0; -} - - -int PipeImpl::readBytes(void* buffer, int length) -{ - return 0; -} - - -PipeImpl::Handle PipeImpl::readHandle() const -{ - return 0; -} - - -PipeImpl::Handle PipeImpl::writeHandle() const -{ - return 0; -} - - -void PipeImpl::closeRead() -{ -} - - -void PipeImpl::closeWrite() -{ -} - - -} // namespace Poco +// +// PipeImpl_DUMMY.cpp +// +// $Id: //poco/1.2/Foundation/src/PipeImpl_DUMMY.cpp#1 $ +// +// Library: Foundation +// Package: Processes +// Module: PipeImpl +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/PipeImpl_DUMMY.h" + + +namespace Poco { + + +PipeImpl::PipeImpl() +{ +} + + +PipeImpl::~PipeImpl() +{ +} + + +int PipeImpl::writeBytes(const void* buffer, int length) +{ + return 0; +} + + +int PipeImpl::readBytes(void* buffer, int length) +{ + return 0; +} + + +PipeImpl::Handle PipeImpl::readHandle() const +{ + return 0; +} + + +PipeImpl::Handle PipeImpl::writeHandle() const +{ + return 0; +} + + +void PipeImpl::closeRead() +{ +} + + +void PipeImpl::closeWrite() +{ +} + + +} // namespace Poco diff --git a/Foundation/src/PipeImpl_POSIX.cpp b/Foundation/src/PipeImpl_POSIX.cpp index 9fefa7f26..c5359fcbd 100644 --- a/Foundation/src/PipeImpl_POSIX.cpp +++ b/Foundation/src/PipeImpl_POSIX.cpp @@ -1,132 +1,132 @@ -// -// PipeImpl_POSIX.cpp -// -// $Id: //poco/1.2/Foundation/src/PipeImpl_POSIX.cpp#2 $ -// -// Library: Foundation -// Package: Processes -// Module: PipeImpl -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/PipeImpl_POSIX.h" -#include "Poco/Exception.h" -#include -#include - - -namespace Poco { - - -PipeImpl::PipeImpl() -{ - int fds[2]; - int rc = pipe(fds); - if (rc == 0) - { - _readfd = fds[0]; - _writefd = fds[1]; - } - else throw CreateFileException("anonymous pipe"); -} - - -PipeImpl::~PipeImpl() -{ - closeRead(); - closeWrite(); -} - - -int PipeImpl::writeBytes(const void* buffer, int length) -{ - poco_assert (_writefd != -1); - - int n; - do - { - n = write(_writefd, buffer, length); - } - while (n < 0 && errno == EINTR); - if (n >= 0) - return n; - else - throw WriteFileException("anonymous pipe"); -} - - -int PipeImpl::readBytes(void* buffer, int length) -{ - poco_assert (_readfd != -1); - - int n; - do - { - n = read(_readfd, buffer, length); - } - while (n < 0 && errno == EINTR); - if (n >= 0) - return n; - else - throw ReadFileException("anonymous pipe"); -} - - -PipeImpl::Handle PipeImpl::readHandle() const -{ - return _readfd; -} - - -PipeImpl::Handle PipeImpl::writeHandle() const -{ - return _writefd; -} - - -void PipeImpl::closeRead() -{ - if (_readfd != -1) - { - close(_readfd); - _readfd = -1; - } -} - - -void PipeImpl::closeWrite() -{ - if (_writefd != -1) - { - close(_writefd); - _writefd = -1; - } -} - - -} // namespace Poco +// +// PipeImpl_POSIX.cpp +// +// $Id: //poco/1.2/Foundation/src/PipeImpl_POSIX.cpp#2 $ +// +// Library: Foundation +// Package: Processes +// Module: PipeImpl +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/PipeImpl_POSIX.h" +#include "Poco/Exception.h" +#include +#include + + +namespace Poco { + + +PipeImpl::PipeImpl() +{ + int fds[2]; + int rc = pipe(fds); + if (rc == 0) + { + _readfd = fds[0]; + _writefd = fds[1]; + } + else throw CreateFileException("anonymous pipe"); +} + + +PipeImpl::~PipeImpl() +{ + closeRead(); + closeWrite(); +} + + +int PipeImpl::writeBytes(const void* buffer, int length) +{ + poco_assert (_writefd != -1); + + int n; + do + { + n = write(_writefd, buffer, length); + } + while (n < 0 && errno == EINTR); + if (n >= 0) + return n; + else + throw WriteFileException("anonymous pipe"); +} + + +int PipeImpl::readBytes(void* buffer, int length) +{ + poco_assert (_readfd != -1); + + int n; + do + { + n = read(_readfd, buffer, length); + } + while (n < 0 && errno == EINTR); + if (n >= 0) + return n; + else + throw ReadFileException("anonymous pipe"); +} + + +PipeImpl::Handle PipeImpl::readHandle() const +{ + return _readfd; +} + + +PipeImpl::Handle PipeImpl::writeHandle() const +{ + return _writefd; +} + + +void PipeImpl::closeRead() +{ + if (_readfd != -1) + { + close(_readfd); + _readfd = -1; + } +} + + +void PipeImpl::closeWrite() +{ + if (_writefd != -1) + { + close(_writefd); + _writefd = -1; + } +} + + +} // namespace Poco diff --git a/Foundation/src/PipeImpl_WIN32.cpp b/Foundation/src/PipeImpl_WIN32.cpp index 808500e07..fa75b5f71 100644 --- a/Foundation/src/PipeImpl_WIN32.cpp +++ b/Foundation/src/PipeImpl_WIN32.cpp @@ -1,119 +1,119 @@ -// -// PipeImpl_WIN32.cpp -// -// $Id: //poco/1.2/Foundation/src/PipeImpl_WIN32.cpp#1 $ -// -// Library: Foundation -// Package: Processes -// Module: PipeImpl -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/PipeImpl_WIN32.h" -#include "Poco/Exception.h" - - -namespace Poco { - - -PipeImpl::PipeImpl() -{ - SECURITY_ATTRIBUTES attr; - attr.nLength = sizeof(attr); - attr.lpSecurityDescriptor = NULL; - attr.bInheritHandle = FALSE; - - if (!CreatePipe(&_readHandle, &_writeHandle, &attr, 0)) - throw CreateFileException("anonymous pipe"); -} - - -PipeImpl::~PipeImpl() -{ - closeRead(); - closeWrite(); -} - - -int PipeImpl::writeBytes(const void* buffer, int length) -{ - poco_assert (_writeHandle != INVALID_HANDLE_VALUE); - - DWORD bytesWritten = 0; - if (!WriteFile(_writeHandle, buffer, length, &bytesWritten, NULL)) - throw WriteFileException("anonymous pipe"); - return bytesWritten; -} - - -int PipeImpl::readBytes(void* buffer, int length) -{ - poco_assert (_readHandle != INVALID_HANDLE_VALUE); - - DWORD bytesRead = 0; - BOOL ok = ReadFile(_readHandle, buffer, length, &bytesRead, NULL); - if (ok || GetLastError() == ERROR_BROKEN_PIPE) - return bytesRead; - else - throw ReadFileException("anonymous pipe"); -} - - -PipeImpl::Handle PipeImpl::readHandle() const -{ - return _readHandle; -} - - -PipeImpl::Handle PipeImpl::writeHandle() const -{ - return _writeHandle; -} - - -void PipeImpl::closeRead() -{ - if (_readHandle != INVALID_HANDLE_VALUE) - { - CloseHandle(_readHandle); - _readHandle = INVALID_HANDLE_VALUE; - } -} - - -void PipeImpl::closeWrite() -{ - if (_writeHandle != INVALID_HANDLE_VALUE) - { - CloseHandle(_writeHandle); - _writeHandle = INVALID_HANDLE_VALUE; - } -} - - -} // namespace Poco +// +// PipeImpl_WIN32.cpp +// +// $Id: //poco/1.2/Foundation/src/PipeImpl_WIN32.cpp#1 $ +// +// Library: Foundation +// Package: Processes +// Module: PipeImpl +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/PipeImpl_WIN32.h" +#include "Poco/Exception.h" + + +namespace Poco { + + +PipeImpl::PipeImpl() +{ + SECURITY_ATTRIBUTES attr; + attr.nLength = sizeof(attr); + attr.lpSecurityDescriptor = NULL; + attr.bInheritHandle = FALSE; + + if (!CreatePipe(&_readHandle, &_writeHandle, &attr, 0)) + throw CreateFileException("anonymous pipe"); +} + + +PipeImpl::~PipeImpl() +{ + closeRead(); + closeWrite(); +} + + +int PipeImpl::writeBytes(const void* buffer, int length) +{ + poco_assert (_writeHandle != INVALID_HANDLE_VALUE); + + DWORD bytesWritten = 0; + if (!WriteFile(_writeHandle, buffer, length, &bytesWritten, NULL)) + throw WriteFileException("anonymous pipe"); + return bytesWritten; +} + + +int PipeImpl::readBytes(void* buffer, int length) +{ + poco_assert (_readHandle != INVALID_HANDLE_VALUE); + + DWORD bytesRead = 0; + BOOL ok = ReadFile(_readHandle, buffer, length, &bytesRead, NULL); + if (ok || GetLastError() == ERROR_BROKEN_PIPE) + return bytesRead; + else + throw ReadFileException("anonymous pipe"); +} + + +PipeImpl::Handle PipeImpl::readHandle() const +{ + return _readHandle; +} + + +PipeImpl::Handle PipeImpl::writeHandle() const +{ + return _writeHandle; +} + + +void PipeImpl::closeRead() +{ + if (_readHandle != INVALID_HANDLE_VALUE) + { + CloseHandle(_readHandle); + _readHandle = INVALID_HANDLE_VALUE; + } +} + + +void PipeImpl::closeWrite() +{ + if (_writeHandle != INVALID_HANDLE_VALUE) + { + CloseHandle(_writeHandle); + _writeHandle = INVALID_HANDLE_VALUE; + } +} + + +} // namespace Poco diff --git a/Foundation/src/PipeStream.cpp b/Foundation/src/PipeStream.cpp index 02d0e6043..5ab658e27 100644 --- a/Foundation/src/PipeStream.cpp +++ b/Foundation/src/PipeStream.cpp @@ -1,149 +1,149 @@ -// -// PipeStream.cpp -// -// $Id: //poco/1.2/Foundation/src/PipeStream.cpp#1 $ -// -// Library: Foundation -// Package: Processes -// Module: PipeStream -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/PipeStream.h" - - -namespace Poco { - - -// -// PipeStreamBuf -// - - -PipeStreamBuf::PipeStreamBuf(const Pipe& pipe, openmode mode): - BufferedStreamBuf(STREAM_BUFFER_SIZE, mode), - _pipe(pipe) -{ -} - - -PipeStreamBuf::~PipeStreamBuf() -{ -} - - -int PipeStreamBuf::readFromDevice(char* buffer, std::streamsize length) -{ - return _pipe.readBytes(buffer, (int) length); -} - - -int PipeStreamBuf::writeToDevice(const char* buffer, std::streamsize length) -{ - return _pipe.writeBytes(buffer, (int) length); -} - - -void PipeStreamBuf::close() -{ - _pipe.close(Pipe::CLOSE_BOTH); -} - - -// -// PipeIOS -// - - -PipeIOS::PipeIOS(const Pipe& pipe, openmode mode): - _buf(pipe, mode) -{ - poco_ios_init(&_buf); -} - - -PipeIOS::~PipeIOS() -{ - try - { - _buf.sync(); - } - catch (...) - { - } -} - - -PipeStreamBuf* PipeIOS::rdbuf() -{ - return &_buf; -} - - -void PipeIOS::close() -{ - _buf.sync(); - _buf.close(); -} - - -// -// PipeOutputStream -// - - -PipeOutputStream::PipeOutputStream(const Pipe& pipe): - PipeIOS(pipe, std::ios::out), - std::ostream(&_buf) -{ -} - - -PipeOutputStream::~PipeOutputStream() -{ -} - - -// -// PipeInputStream -// - - -PipeInputStream::PipeInputStream(const Pipe& pipe): - PipeIOS(pipe, std::ios::in), - std::istream(&_buf) -{ -} - - -PipeInputStream::~PipeInputStream() -{ -} - - -} // namespace Poco +// +// PipeStream.cpp +// +// $Id: //poco/1.2/Foundation/src/PipeStream.cpp#1 $ +// +// Library: Foundation +// Package: Processes +// Module: PipeStream +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/PipeStream.h" + + +namespace Poco { + + +// +// PipeStreamBuf +// + + +PipeStreamBuf::PipeStreamBuf(const Pipe& pipe, openmode mode): + BufferedStreamBuf(STREAM_BUFFER_SIZE, mode), + _pipe(pipe) +{ +} + + +PipeStreamBuf::~PipeStreamBuf() +{ +} + + +int PipeStreamBuf::readFromDevice(char* buffer, std::streamsize length) +{ + return _pipe.readBytes(buffer, (int) length); +} + + +int PipeStreamBuf::writeToDevice(const char* buffer, std::streamsize length) +{ + return _pipe.writeBytes(buffer, (int) length); +} + + +void PipeStreamBuf::close() +{ + _pipe.close(Pipe::CLOSE_BOTH); +} + + +// +// PipeIOS +// + + +PipeIOS::PipeIOS(const Pipe& pipe, openmode mode): + _buf(pipe, mode) +{ + poco_ios_init(&_buf); +} + + +PipeIOS::~PipeIOS() +{ + try + { + _buf.sync(); + } + catch (...) + { + } +} + + +PipeStreamBuf* PipeIOS::rdbuf() +{ + return &_buf; +} + + +void PipeIOS::close() +{ + _buf.sync(); + _buf.close(); +} + + +// +// PipeOutputStream +// + + +PipeOutputStream::PipeOutputStream(const Pipe& pipe): + PipeIOS(pipe, std::ios::out), + std::ostream(&_buf) +{ +} + + +PipeOutputStream::~PipeOutputStream() +{ +} + + +// +// PipeInputStream +// + + +PipeInputStream::PipeInputStream(const Pipe& pipe): + PipeIOS(pipe, std::ios::in), + std::istream(&_buf) +{ +} + + +PipeInputStream::~PipeInputStream() +{ +} + + +} // namespace Poco diff --git a/Foundation/src/Process.cpp b/Foundation/src/Process.cpp index bdb8abc3a..6d16e0311 100644 --- a/Foundation/src/Process.cpp +++ b/Foundation/src/Process.cpp @@ -1,136 +1,136 @@ -// -// Process.cpp -// -// $Id: //poco/1.2/Foundation/src/Process.cpp#1 $ -// -// Library: Foundation -// Package: Processes -// Module: Process -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/Process.h" - - -#if defined(POCO_OS_FAMILY_WINDOWS) && defined(POCO_WIN32_UTF8) -#include "Process_WIN32U.cpp" -#elif defined(POCO_OS_FAMILY_WINDOWS) -#include "Process_WIN32.cpp" -#elif defined(POCO_OS_FAMILY_UNIX) -#include "Process_UNIX.cpp" -#else -#include "Process_VMS.cpp" -#endif - - -namespace Poco { - - -// -// ProcessHandle -// -ProcessHandle::ProcessHandle(const ProcessHandle& handle): - _pImpl(handle._pImpl) -{ - _pImpl->duplicate(); -} - - -ProcessHandle::~ProcessHandle() -{ - _pImpl->release(); -} - - -ProcessHandle::ProcessHandle(ProcessHandleImpl* pImpl): - _pImpl(pImpl) -{ - poco_check_ptr (_pImpl); -} - - -ProcessHandle& ProcessHandle::operator = (const ProcessHandle& handle) -{ - if (&handle != this) - { - _pImpl->release(); - _pImpl = handle._pImpl; - _pImpl->duplicate(); - } - return *this; -} - - -ProcessHandle::PID ProcessHandle::id() const -{ - return _pImpl->id(); -} - - -int ProcessHandle::wait() const -{ - return _pImpl->wait(); -} - - -// -// Process -// -ProcessHandle Process::launch(const std::string& command, const Args& args) -{ - return ProcessHandle(launchImpl(command, args, 0, 0, 0)); -} - - -ProcessHandle Process::launch(const std::string& command, const Args& args, Pipe* inPipe, Pipe* outPipe, Pipe* errPipe) -{ - poco_assert (inPipe == 0 || inPipe != outPipe && inPipe != errPipe); - - return ProcessHandle(launchImpl(command, args, inPipe, outPipe, errPipe)); -} - - -int Process::wait(const ProcessHandle& handle) -{ - return handle.wait(); -} - - -void Process::kill(PID pid) -{ - killImpl(pid); -} - - -void Process::requestTermination(PID pid) -{ - requestTerminationImpl(pid); -} - - -} // namespace Poco +// +// Process.cpp +// +// $Id: //poco/1.2/Foundation/src/Process.cpp#1 $ +// +// Library: Foundation +// Package: Processes +// Module: Process +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/Process.h" + + +#if defined(POCO_OS_FAMILY_WINDOWS) && defined(POCO_WIN32_UTF8) +#include "Process_WIN32U.cpp" +#elif defined(POCO_OS_FAMILY_WINDOWS) +#include "Process_WIN32.cpp" +#elif defined(POCO_OS_FAMILY_UNIX) +#include "Process_UNIX.cpp" +#else +#include "Process_VMS.cpp" +#endif + + +namespace Poco { + + +// +// ProcessHandle +// +ProcessHandle::ProcessHandle(const ProcessHandle& handle): + _pImpl(handle._pImpl) +{ + _pImpl->duplicate(); +} + + +ProcessHandle::~ProcessHandle() +{ + _pImpl->release(); +} + + +ProcessHandle::ProcessHandle(ProcessHandleImpl* pImpl): + _pImpl(pImpl) +{ + poco_check_ptr (_pImpl); +} + + +ProcessHandle& ProcessHandle::operator = (const ProcessHandle& handle) +{ + if (&handle != this) + { + _pImpl->release(); + _pImpl = handle._pImpl; + _pImpl->duplicate(); + } + return *this; +} + + +ProcessHandle::PID ProcessHandle::id() const +{ + return _pImpl->id(); +} + + +int ProcessHandle::wait() const +{ + return _pImpl->wait(); +} + + +// +// Process +// +ProcessHandle Process::launch(const std::string& command, const Args& args) +{ + return ProcessHandle(launchImpl(command, args, 0, 0, 0)); +} + + +ProcessHandle Process::launch(const std::string& command, const Args& args, Pipe* inPipe, Pipe* outPipe, Pipe* errPipe) +{ + poco_assert (inPipe == 0 || inPipe != outPipe && inPipe != errPipe); + + return ProcessHandle(launchImpl(command, args, inPipe, outPipe, errPipe)); +} + + +int Process::wait(const ProcessHandle& handle) +{ + return handle.wait(); +} + + +void Process::kill(PID pid) +{ + killImpl(pid); +} + + +void Process::requestTermination(PID pid) +{ + requestTerminationImpl(pid); +} + + +} // namespace Poco diff --git a/Foundation/src/Process_UNIX.cpp b/Foundation/src/Process_UNIX.cpp index faa327a90..82364095d 100644 --- a/Foundation/src/Process_UNIX.cpp +++ b/Foundation/src/Process_UNIX.cpp @@ -1,206 +1,206 @@ -// -// Process_UNIX.cpp -// -// $Id: //poco/1.2/Foundation/src/Process_UNIX.cpp#2 $ -// -// Library: Foundation -// Package: Processes -// Module: Process -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/Process_UNIX.h" -#include "Poco/Exception.h" -#include "Poco/NumberFormatter.h" -#include "Poco/Pipe.h" -#include -#include -#include -#include -#include -#include - - -#if defined(__QNX__) -#include -#include -#include -#endif - - -namespace Poco { - - -// -// ProcessHandleImpl -// -ProcessHandleImpl::ProcessHandleImpl(pid_t pid): - _pid(pid) -{ -} - - -ProcessHandleImpl::~ProcessHandleImpl() -{ -} - - -pid_t ProcessHandleImpl::id() const -{ - return _pid; -} - - -int ProcessHandleImpl::wait() const -{ - int status; - int rc; - do - { - rc = waitpid(_pid, &status, 0); - } - while (rc < 0 && errno == EINTR); - if (rc != _pid) - throw SystemException("Cannot wait for process", NumberFormatter::format(_pid)); - return WEXITSTATUS(status); -} - - -// -// ProcessImpl -// -ProcessImpl::PIDImpl ProcessImpl::idImpl() -{ - return getpid(); -} - - -void ProcessImpl::timesImpl(long& userTime, long& kernelTime) -{ - struct rusage usage; - getrusage(RUSAGE_SELF, &usage); - userTime = usage.ru_utime.tv_sec; - kernelTime = usage.ru_stime.tv_sec; -} - - -ProcessHandleImpl* ProcessImpl::launchImpl(const std::string& command, const ArgsImpl& args, Pipe* inPipe, Pipe* outPipe, Pipe* errPipe) -{ -#if defined(__QNX__) - /// use QNX's spawn system call which is more efficient than fork/exec. - char** argv = new char*[args.size() + 2]; - int i = 0; - argv[i++] = const_cast(command.c_str()); - for (ArgsImpl::const_iterator it = args.begin(); it != args.end(); ++it) - argv[i++] = const_cast(it->c_str()); - argv[i] = NULL; - struct inheritance inherit; - memset(&inherit, 0, sizeof(inherit)); - inherit.flags = SPAWN_ALIGN_DEFAULT | SPAWN_CHECK_SCRIPT | SPAWN_SEARCH_PATH; - int fdmap[3]; - fdmap[0] = inPipe ? inPipe->readHandle() : 0; - fdmap[1] = outPipe ? outPipe->writeHandle() : 1; - fdmap[2] = errPipe ? errPipe->writeHandle() : 2; - int pid = spawn(command.c_str(), 3, fdmap, &inherit, argv, NULL); - delete [] argv; - if (pid == -1) throw SystemException("cannot spawn", command); -#else - int pid = fork(); - if (pid < 0) - { - throw SystemException("Cannot fork process for", command); - } - else if (pid == 0) - { - // setup redirection - if (inPipe) - { - dup2(inPipe->readHandle(), STDIN_FILENO); - inPipe->close(Pipe::CLOSE_BOTH); - } - // outPipe and errPipe may be the same, so we dup first and close later - if (outPipe) dup2(outPipe->writeHandle(), STDOUT_FILENO); - if (errPipe) dup2(errPipe->writeHandle(), STDERR_FILENO); - if (outPipe) outPipe->close(Pipe::CLOSE_BOTH); - if (errPipe) errPipe->close(Pipe::CLOSE_BOTH); - // close all open file descriptors other than stdin, stdout, stderr - for (int i = 3; i < getdtablesize(); ++i) - close(i); - - char** argv = new char*[args.size() + 2]; - int i = 0; - argv[i++] = const_cast(command.c_str()); - for (ArgsImpl::const_iterator it = args.begin(); it != args.end(); ++it) - argv[i++] = const_cast(it->c_str()); - argv[i] = NULL; - execvp(command.c_str(), argv); - _exit(72); - } -#endif - if (inPipe) inPipe->close(Pipe::CLOSE_READ); - if (outPipe) outPipe->close(Pipe::CLOSE_WRITE); - if (errPipe) errPipe->close(Pipe::CLOSE_WRITE); - return new ProcessHandleImpl(pid); -} - - -void ProcessImpl::killImpl(PIDImpl pid) -{ - if (kill(pid, SIGKILL) != 0) - { - switch (errno) - { - case ESRCH: - throw NotFoundException("cannot kill process"); - case EPERM: - throw NoPermissionException("cannot kill process"); - default: - throw SystemException("cannot kill process"); - } - } -} - - -void ProcessImpl::requestTerminationImpl(PIDImpl pid) -{ - if (kill(pid, SIGINT) != 0) - { - switch (errno) - { - case ESRCH: - throw NotFoundException("cannot terminate process"); - case EPERM: - throw NoPermissionException("cannot terminate process"); - default: - throw SystemException("cannot terminate process"); - } - } -} - - -} // namespace Poco +// +// Process_UNIX.cpp +// +// $Id: //poco/1.2/Foundation/src/Process_UNIX.cpp#2 $ +// +// Library: Foundation +// Package: Processes +// Module: Process +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/Process_UNIX.h" +#include "Poco/Exception.h" +#include "Poco/NumberFormatter.h" +#include "Poco/Pipe.h" +#include +#include +#include +#include +#include +#include + + +#if defined(__QNX__) +#include +#include +#include +#endif + + +namespace Poco { + + +// +// ProcessHandleImpl +// +ProcessHandleImpl::ProcessHandleImpl(pid_t pid): + _pid(pid) +{ +} + + +ProcessHandleImpl::~ProcessHandleImpl() +{ +} + + +pid_t ProcessHandleImpl::id() const +{ + return _pid; +} + + +int ProcessHandleImpl::wait() const +{ + int status; + int rc; + do + { + rc = waitpid(_pid, &status, 0); + } + while (rc < 0 && errno == EINTR); + if (rc != _pid) + throw SystemException("Cannot wait for process", NumberFormatter::format(_pid)); + return WEXITSTATUS(status); +} + + +// +// ProcessImpl +// +ProcessImpl::PIDImpl ProcessImpl::idImpl() +{ + return getpid(); +} + + +void ProcessImpl::timesImpl(long& userTime, long& kernelTime) +{ + struct rusage usage; + getrusage(RUSAGE_SELF, &usage); + userTime = usage.ru_utime.tv_sec; + kernelTime = usage.ru_stime.tv_sec; +} + + +ProcessHandleImpl* ProcessImpl::launchImpl(const std::string& command, const ArgsImpl& args, Pipe* inPipe, Pipe* outPipe, Pipe* errPipe) +{ +#if defined(__QNX__) + /// use QNX's spawn system call which is more efficient than fork/exec. + char** argv = new char*[args.size() + 2]; + int i = 0; + argv[i++] = const_cast(command.c_str()); + for (ArgsImpl::const_iterator it = args.begin(); it != args.end(); ++it) + argv[i++] = const_cast(it->c_str()); + argv[i] = NULL; + struct inheritance inherit; + memset(&inherit, 0, sizeof(inherit)); + inherit.flags = SPAWN_ALIGN_DEFAULT | SPAWN_CHECK_SCRIPT | SPAWN_SEARCH_PATH; + int fdmap[3]; + fdmap[0] = inPipe ? inPipe->readHandle() : 0; + fdmap[1] = outPipe ? outPipe->writeHandle() : 1; + fdmap[2] = errPipe ? errPipe->writeHandle() : 2; + int pid = spawn(command.c_str(), 3, fdmap, &inherit, argv, NULL); + delete [] argv; + if (pid == -1) throw SystemException("cannot spawn", command); +#else + int pid = fork(); + if (pid < 0) + { + throw SystemException("Cannot fork process for", command); + } + else if (pid == 0) + { + // setup redirection + if (inPipe) + { + dup2(inPipe->readHandle(), STDIN_FILENO); + inPipe->close(Pipe::CLOSE_BOTH); + } + // outPipe and errPipe may be the same, so we dup first and close later + if (outPipe) dup2(outPipe->writeHandle(), STDOUT_FILENO); + if (errPipe) dup2(errPipe->writeHandle(), STDERR_FILENO); + if (outPipe) outPipe->close(Pipe::CLOSE_BOTH); + if (errPipe) errPipe->close(Pipe::CLOSE_BOTH); + // close all open file descriptors other than stdin, stdout, stderr + for (int i = 3; i < getdtablesize(); ++i) + close(i); + + char** argv = new char*[args.size() + 2]; + int i = 0; + argv[i++] = const_cast(command.c_str()); + for (ArgsImpl::const_iterator it = args.begin(); it != args.end(); ++it) + argv[i++] = const_cast(it->c_str()); + argv[i] = NULL; + execvp(command.c_str(), argv); + _exit(72); + } +#endif + if (inPipe) inPipe->close(Pipe::CLOSE_READ); + if (outPipe) outPipe->close(Pipe::CLOSE_WRITE); + if (errPipe) errPipe->close(Pipe::CLOSE_WRITE); + return new ProcessHandleImpl(pid); +} + + +void ProcessImpl::killImpl(PIDImpl pid) +{ + if (kill(pid, SIGKILL) != 0) + { + switch (errno) + { + case ESRCH: + throw NotFoundException("cannot kill process"); + case EPERM: + throw NoPermissionException("cannot kill process"); + default: + throw SystemException("cannot kill process"); + } + } +} + + +void ProcessImpl::requestTerminationImpl(PIDImpl pid) +{ + if (kill(pid, SIGINT) != 0) + { + switch (errno) + { + case ESRCH: + throw NotFoundException("cannot terminate process"); + case EPERM: + throw NoPermissionException("cannot terminate process"); + default: + throw SystemException("cannot terminate process"); + } + } +} + + +} // namespace Poco diff --git a/Foundation/src/Process_VMS.cpp b/Foundation/src/Process_VMS.cpp index 8f20baf75..192d942f2 100644 --- a/Foundation/src/Process_VMS.cpp +++ b/Foundation/src/Process_VMS.cpp @@ -1,154 +1,154 @@ -// -// Process_VMS.cpp -// -// $Id: //poco/1.2/Foundation/src/Process_VMS.cpp#1 $ -// -// Library: Foundation -// Package: Processes -// Module: Process -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/Process_VMS.h" -#include "Poco/NumberFormatter.h" -#include "Poco/NamedEvent.h" -#include -#include - - -namespace Poco { - - -// -// ProcessHandleImpl -// -ProcessHandleImpl::ProcessHandleImpl(pid_t pid): - _pid(pid) -{ -} - - -ProcessHandleImpl::~ProcessHandleImpl() -{ -} - - -pid_t ProcessHandleImpl::id() const -{ - return _pid; -} - - -int ProcessHandleImpl::wait() const -{ - int status; - if (waitpid(_pid, &status, 0) != _pid) - throw SystemException("Cannot wait for process", NumberFormatter::format(_pid)); - return WEXITSTATUS(status); -} - - -// -// ProcessImpl -// -ProcessImpl::PIDImpl ProcessImpl::idImpl() -{ - return getpid(); -} - - -void ProcessImpl::timesImpl(long& userTime, long& kernelTime) -{ - struct tms buffer; - times(&buffer)*1000/CLOCKS_PER_SEC; - userTime = buffer.tms_utime/CLOCKS_PER_SEC; - kernelTime = buffer.tms_stime/CLOCKS_PER_SEC; -} - - -ProcessHandleImpl* ProcessImpl::launchImpl(const std::string& command, const ArgsImpl& args, Pipe* inPipe, Pipe* outPipe, Pipe* errPipe) -{ - char** argv = new char*[args.size() + 2]; - int i = 0; - argv[i++] = const_cast(command.c_str()); - for (ArgsImpl::const_iterator it = args.begin(); it != args.end(); ++it) - argv[i++] = const_cast(it->c_str()); - argv[i] = NULL; - try - { - int pid = vfork(); - if (pid < 0) - { - throw SystemException("Cannot fork process for", command); - } - else if (pid == 0) - { - if (execvp(command.c_str(), argv) == -1) - throw SystemException("Cannot execute command", command); - } - else - { - delete [] argv; - return new ProcessHandleImpl(pid); - } - } - catch (...) - { - delete [] argv; - throw; - } -} - - -void ProcessImpl::killImpl(PIDImpl pid) -{ - if (kill(pid, SIGKILL) != 0) - { - switch (errno) - { - case ESRCH: - throw NotFoundException("cannot kill process"); - case EPERM: - throw NoPermissionException("cannot kill process"); - default: - throw SystemException("cannot kill process"); - } - } -} - - -void ProcessImpl::requestTerminationImpl(PIDImpl pid) -{ - std::string evName("POCOTRM"); - evName.append(NumberFormatter::formatHex(pid, 8)); - NamedEvent ev(evName); - ev.set(); -} - - -} // namespace Poco +// +// Process_VMS.cpp +// +// $Id: //poco/1.2/Foundation/src/Process_VMS.cpp#1 $ +// +// Library: Foundation +// Package: Processes +// Module: Process +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/Process_VMS.h" +#include "Poco/NumberFormatter.h" +#include "Poco/NamedEvent.h" +#include +#include + + +namespace Poco { + + +// +// ProcessHandleImpl +// +ProcessHandleImpl::ProcessHandleImpl(pid_t pid): + _pid(pid) +{ +} + + +ProcessHandleImpl::~ProcessHandleImpl() +{ +} + + +pid_t ProcessHandleImpl::id() const +{ + return _pid; +} + + +int ProcessHandleImpl::wait() const +{ + int status; + if (waitpid(_pid, &status, 0) != _pid) + throw SystemException("Cannot wait for process", NumberFormatter::format(_pid)); + return WEXITSTATUS(status); +} + + +// +// ProcessImpl +// +ProcessImpl::PIDImpl ProcessImpl::idImpl() +{ + return getpid(); +} + + +void ProcessImpl::timesImpl(long& userTime, long& kernelTime) +{ + struct tms buffer; + times(&buffer)*1000/CLOCKS_PER_SEC; + userTime = buffer.tms_utime/CLOCKS_PER_SEC; + kernelTime = buffer.tms_stime/CLOCKS_PER_SEC; +} + + +ProcessHandleImpl* ProcessImpl::launchImpl(const std::string& command, const ArgsImpl& args, Pipe* inPipe, Pipe* outPipe, Pipe* errPipe) +{ + char** argv = new char*[args.size() + 2]; + int i = 0; + argv[i++] = const_cast(command.c_str()); + for (ArgsImpl::const_iterator it = args.begin(); it != args.end(); ++it) + argv[i++] = const_cast(it->c_str()); + argv[i] = NULL; + try + { + int pid = vfork(); + if (pid < 0) + { + throw SystemException("Cannot fork process for", command); + } + else if (pid == 0) + { + if (execvp(command.c_str(), argv) == -1) + throw SystemException("Cannot execute command", command); + } + else + { + delete [] argv; + return new ProcessHandleImpl(pid); + } + } + catch (...) + { + delete [] argv; + throw; + } +} + + +void ProcessImpl::killImpl(PIDImpl pid) +{ + if (kill(pid, SIGKILL) != 0) + { + switch (errno) + { + case ESRCH: + throw NotFoundException("cannot kill process"); + case EPERM: + throw NoPermissionException("cannot kill process"); + default: + throw SystemException("cannot kill process"); + } + } +} + + +void ProcessImpl::requestTerminationImpl(PIDImpl pid) +{ + std::string evName("POCOTRM"); + evName.append(NumberFormatter::formatHex(pid, 8)); + NamedEvent ev(evName); + ev.set(); +} + + +} // namespace Poco diff --git a/Foundation/src/Process_WIN32.cpp b/Foundation/src/Process_WIN32.cpp index 99ca0da01..f7601a947 100644 --- a/Foundation/src/Process_WIN32.cpp +++ b/Foundation/src/Process_WIN32.cpp @@ -1,215 +1,215 @@ -// -// Process_WIN32.cpp -// -// $Id: //poco/1.2/Foundation/src/Process_WIN32.cpp#1 $ -// -// Library: Foundation -// Package: Processes -// Module: Process -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/Process_WIN32.h" -#include "Poco/Exception.h" -#include "Poco/NumberFormatter.h" -#include "Poco/NamedEvent.h" -#include "Poco/Pipe.h" - - -namespace Poco { - - -// -// ProcessHandleImpl -// -ProcessHandleImpl::ProcessHandleImpl(HANDLE hProcess, UInt32 pid): - _hProcess(hProcess), - _pid(pid) -{ -} - - -ProcessHandleImpl::~ProcessHandleImpl() -{ - CloseHandle(_hProcess); -} - - -UInt32 ProcessHandleImpl::id() const -{ - return _pid; -} - - -int ProcessHandleImpl::wait() const -{ - DWORD rc = WaitForSingleObject(_hProcess, INFINITE); - if (rc != WAIT_OBJECT_0) - throw SystemException("Wait failed for process", NumberFormatter::format(_pid)); - - DWORD exitCode; - if (GetExitCodeProcess(_hProcess, &exitCode) == 0) - throw SystemException("Cannot get exit code for process", NumberFormatter::format(_pid)); - - return exitCode; -} - - -// -// ProcessImpl -// -ProcessImpl::PIDImpl ProcessImpl::idImpl() -{ - return GetCurrentProcessId(); -} - - -void ProcessImpl::timesImpl(long& userTime, long& kernelTime) -{ - FILETIME ftCreation; - FILETIME ftExit; - FILETIME ftKernel; - FILETIME ftUser; - - if (GetProcessTimes(GetCurrentProcess(), &ftCreation, &ftExit, &ftKernel, &ftUser) != 0) - { - ULARGE_INTEGER time; - time.LowPart = ftKernel.dwLowDateTime; - time.HighPart = ftKernel.dwHighDateTime; - kernelTime = long(time.QuadPart/10000000L); - time.LowPart = ftUser.dwLowDateTime; - time.HighPart = ftUser.dwHighDateTime; - userTime = long(time.QuadPart/10000000L); - } - else - { - userTime = kernelTime = -1; - } -} - - -ProcessHandleImpl* ProcessImpl::launchImpl(const std::string& command, const ArgsImpl& args, Pipe* inPipe, Pipe* outPipe, Pipe* errPipe) -{ - std::string commandLine = command; - for (ArgsImpl::const_iterator it = args.begin(); it != args.end(); ++it) - { - commandLine.append(" "); - commandLine.append(*it); - } - - STARTUPINFO startupInfo; - GetStartupInfo(&startupInfo); // take defaults from current process - startupInfo.cb = sizeof(STARTUPINFO); - startupInfo.lpReserved = NULL; - startupInfo.lpDesktop = NULL; - startupInfo.lpTitle = NULL; - startupInfo.dwFlags = STARTF_FORCEOFFFEEDBACK | STARTF_USESTDHANDLES; - startupInfo.cbReserved2 = 0; - startupInfo.lpReserved2 = NULL; - - HANDLE hProc = GetCurrentProcess(); - if (inPipe) - { - DuplicateHandle(hProc, inPipe->readHandle(), hProc, &startupInfo.hStdInput, 0, TRUE, DUPLICATE_SAME_ACCESS); - inPipe->close(Pipe::CLOSE_READ); - } - else DuplicateHandle(hProc, GetStdHandle(STD_INPUT_HANDLE), hProc, &startupInfo.hStdInput, 0, TRUE, DUPLICATE_SAME_ACCESS); - // outPipe may be the same as errPipe, so we duplicate first and close later. - if (outPipe) - DuplicateHandle(hProc, outPipe->writeHandle(), hProc, &startupInfo.hStdOutput, 0, TRUE, DUPLICATE_SAME_ACCESS); - else - DuplicateHandle(hProc, GetStdHandle(STD_OUTPUT_HANDLE), hProc, &startupInfo.hStdOutput, 0, TRUE, DUPLICATE_SAME_ACCESS); - if (errPipe) - DuplicateHandle(hProc, errPipe->writeHandle(), hProc, &startupInfo.hStdError, 0, TRUE, DUPLICATE_SAME_ACCESS); - else - DuplicateHandle(hProc, GetStdHandle(STD_ERROR_HANDLE), hProc, &startupInfo.hStdError, 0, TRUE, DUPLICATE_SAME_ACCESS); - if (outPipe) outPipe->close(Pipe::CLOSE_WRITE); - if (errPipe) errPipe->close(Pipe::CLOSE_WRITE); - - PROCESS_INFORMATION processInfo; - BOOL rc = CreateProcess( - NULL, - const_cast(commandLine.c_str()), - NULL, - NULL, - TRUE, - 0, - NULL, - NULL, - &startupInfo, - &processInfo - ); - CloseHandle(startupInfo.hStdInput); - CloseHandle(startupInfo.hStdOutput); - CloseHandle(startupInfo.hStdError); - if (rc) - { - CloseHandle(processInfo.hThread); - return new ProcessHandleImpl(processInfo.hProcess, processInfo.dwProcessId); - } - else throw SystemException("Cannot launch process", command); -} - - -void ProcessImpl::killImpl(PIDImpl pid) -{ - HANDLE hProc = OpenProcess(PROCESS_TERMINATE, FALSE, pid); - if (hProc) - { - if (TerminateProcess(hProc, 0) == 0) - { - CloseHandle(hProc); - throw SystemException("cannot kill process"); - } - CloseHandle(hProc); - } - else - { - switch (GetLastError()) - { - case ERROR_ACCESS_DENIED: - throw NoPermissionException("cannot kill process"); - case ERROR_NOT_FOUND: - throw NotFoundException("cannot kill process"); - default: - throw SystemException("cannot kill process"); - } - } -} - - -void ProcessImpl::requestTerminationImpl(PIDImpl pid) -{ - std::string evName("POCOTRM"); - evName.append(NumberFormatter::formatHex(pid, 8)); - NamedEvent ev(evName); - ev.set(); -} - - -} // namespace Poco +// +// Process_WIN32.cpp +// +// $Id: //poco/1.2/Foundation/src/Process_WIN32.cpp#1 $ +// +// Library: Foundation +// Package: Processes +// Module: Process +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/Process_WIN32.h" +#include "Poco/Exception.h" +#include "Poco/NumberFormatter.h" +#include "Poco/NamedEvent.h" +#include "Poco/Pipe.h" + + +namespace Poco { + + +// +// ProcessHandleImpl +// +ProcessHandleImpl::ProcessHandleImpl(HANDLE hProcess, UInt32 pid): + _hProcess(hProcess), + _pid(pid) +{ +} + + +ProcessHandleImpl::~ProcessHandleImpl() +{ + CloseHandle(_hProcess); +} + + +UInt32 ProcessHandleImpl::id() const +{ + return _pid; +} + + +int ProcessHandleImpl::wait() const +{ + DWORD rc = WaitForSingleObject(_hProcess, INFINITE); + if (rc != WAIT_OBJECT_0) + throw SystemException("Wait failed for process", NumberFormatter::format(_pid)); + + DWORD exitCode; + if (GetExitCodeProcess(_hProcess, &exitCode) == 0) + throw SystemException("Cannot get exit code for process", NumberFormatter::format(_pid)); + + return exitCode; +} + + +// +// ProcessImpl +// +ProcessImpl::PIDImpl ProcessImpl::idImpl() +{ + return GetCurrentProcessId(); +} + + +void ProcessImpl::timesImpl(long& userTime, long& kernelTime) +{ + FILETIME ftCreation; + FILETIME ftExit; + FILETIME ftKernel; + FILETIME ftUser; + + if (GetProcessTimes(GetCurrentProcess(), &ftCreation, &ftExit, &ftKernel, &ftUser) != 0) + { + ULARGE_INTEGER time; + time.LowPart = ftKernel.dwLowDateTime; + time.HighPart = ftKernel.dwHighDateTime; + kernelTime = long(time.QuadPart/10000000L); + time.LowPart = ftUser.dwLowDateTime; + time.HighPart = ftUser.dwHighDateTime; + userTime = long(time.QuadPart/10000000L); + } + else + { + userTime = kernelTime = -1; + } +} + + +ProcessHandleImpl* ProcessImpl::launchImpl(const std::string& command, const ArgsImpl& args, Pipe* inPipe, Pipe* outPipe, Pipe* errPipe) +{ + std::string commandLine = command; + for (ArgsImpl::const_iterator it = args.begin(); it != args.end(); ++it) + { + commandLine.append(" "); + commandLine.append(*it); + } + + STARTUPINFO startupInfo; + GetStartupInfo(&startupInfo); // take defaults from current process + startupInfo.cb = sizeof(STARTUPINFO); + startupInfo.lpReserved = NULL; + startupInfo.lpDesktop = NULL; + startupInfo.lpTitle = NULL; + startupInfo.dwFlags = STARTF_FORCEOFFFEEDBACK | STARTF_USESTDHANDLES; + startupInfo.cbReserved2 = 0; + startupInfo.lpReserved2 = NULL; + + HANDLE hProc = GetCurrentProcess(); + if (inPipe) + { + DuplicateHandle(hProc, inPipe->readHandle(), hProc, &startupInfo.hStdInput, 0, TRUE, DUPLICATE_SAME_ACCESS); + inPipe->close(Pipe::CLOSE_READ); + } + else DuplicateHandle(hProc, GetStdHandle(STD_INPUT_HANDLE), hProc, &startupInfo.hStdInput, 0, TRUE, DUPLICATE_SAME_ACCESS); + // outPipe may be the same as errPipe, so we duplicate first and close later. + if (outPipe) + DuplicateHandle(hProc, outPipe->writeHandle(), hProc, &startupInfo.hStdOutput, 0, TRUE, DUPLICATE_SAME_ACCESS); + else + DuplicateHandle(hProc, GetStdHandle(STD_OUTPUT_HANDLE), hProc, &startupInfo.hStdOutput, 0, TRUE, DUPLICATE_SAME_ACCESS); + if (errPipe) + DuplicateHandle(hProc, errPipe->writeHandle(), hProc, &startupInfo.hStdError, 0, TRUE, DUPLICATE_SAME_ACCESS); + else + DuplicateHandle(hProc, GetStdHandle(STD_ERROR_HANDLE), hProc, &startupInfo.hStdError, 0, TRUE, DUPLICATE_SAME_ACCESS); + if (outPipe) outPipe->close(Pipe::CLOSE_WRITE); + if (errPipe) errPipe->close(Pipe::CLOSE_WRITE); + + PROCESS_INFORMATION processInfo; + BOOL rc = CreateProcess( + NULL, + const_cast(commandLine.c_str()), + NULL, + NULL, + TRUE, + 0, + NULL, + NULL, + &startupInfo, + &processInfo + ); + CloseHandle(startupInfo.hStdInput); + CloseHandle(startupInfo.hStdOutput); + CloseHandle(startupInfo.hStdError); + if (rc) + { + CloseHandle(processInfo.hThread); + return new ProcessHandleImpl(processInfo.hProcess, processInfo.dwProcessId); + } + else throw SystemException("Cannot launch process", command); +} + + +void ProcessImpl::killImpl(PIDImpl pid) +{ + HANDLE hProc = OpenProcess(PROCESS_TERMINATE, FALSE, pid); + if (hProc) + { + if (TerminateProcess(hProc, 0) == 0) + { + CloseHandle(hProc); + throw SystemException("cannot kill process"); + } + CloseHandle(hProc); + } + else + { + switch (GetLastError()) + { + case ERROR_ACCESS_DENIED: + throw NoPermissionException("cannot kill process"); + case ERROR_NOT_FOUND: + throw NotFoundException("cannot kill process"); + default: + throw SystemException("cannot kill process"); + } + } +} + + +void ProcessImpl::requestTerminationImpl(PIDImpl pid) +{ + std::string evName("POCOTRM"); + evName.append(NumberFormatter::formatHex(pid, 8)); + NamedEvent ev(evName); + ev.set(); +} + + +} // namespace Poco diff --git a/Foundation/src/Process_WIN32U.cpp b/Foundation/src/Process_WIN32U.cpp index e40d21a8b..45317e3a5 100644 --- a/Foundation/src/Process_WIN32U.cpp +++ b/Foundation/src/Process_WIN32U.cpp @@ -1,219 +1,219 @@ -// -// Process_WIN32U.cpp -// -// $Id: //poco/1.2/Foundation/src/Process_WIN32U.cpp#1 $ -// -// Library: Foundation -// Package: Processes -// Module: Process -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/Process_WIN32U.h" -#include "Poco/Exception.h" -#include "Poco/NumberFormatter.h" -#include "Poco/NamedEvent.h" -#include "Poco/UnicodeConverter.h" -#include "Poco/Pipe.h" - - -namespace Poco { - - -// -// ProcessHandleImpl -// -ProcessHandleImpl::ProcessHandleImpl(HANDLE hProcess, UInt32 pid): - _hProcess(hProcess), - _pid(pid) -{ -} - - -ProcessHandleImpl::~ProcessHandleImpl() -{ - CloseHandle(_hProcess); -} - - -UInt32 ProcessHandleImpl::id() const -{ - return _pid; -} - - -int ProcessHandleImpl::wait() const -{ - DWORD rc = WaitForSingleObject(_hProcess, INFINITE); - if (rc != WAIT_OBJECT_0) - throw SystemException("Wait failed for process", NumberFormatter::format(_pid)); - - DWORD exitCode; - if (GetExitCodeProcess(_hProcess, &exitCode) == 0) - throw SystemException("Cannot get exit code for process", NumberFormatter::format(_pid)); - - return exitCode; -} - - -// -// ProcessImpl -// -ProcessImpl::PIDImpl ProcessImpl::idImpl() -{ - return GetCurrentProcessId(); -} - - -void ProcessImpl::timesImpl(long& userTime, long& kernelTime) -{ - FILETIME ftCreation; - FILETIME ftExit; - FILETIME ftKernel; - FILETIME ftUser; - - if (GetProcessTimes(GetCurrentProcess(), &ftCreation, &ftExit, &ftKernel, &ftUser) != 0) - { - ULARGE_INTEGER time; - time.LowPart = ftKernel.dwLowDateTime; - time.HighPart = ftKernel.dwHighDateTime; - kernelTime = long(time.QuadPart/10000000L); - time.LowPart = ftUser.dwLowDateTime; - time.HighPart = ftUser.dwHighDateTime; - userTime = long(time.QuadPart/10000000L); - } - else - { - userTime = kernelTime = -1; - } -} - - -ProcessHandleImpl* ProcessImpl::launchImpl(const std::string& command, const ArgsImpl& args, Pipe* inPipe, Pipe* outPipe, Pipe* errPipe) -{ - std::string commandLine = command; - for (ArgsImpl::const_iterator it = args.begin(); it != args.end(); ++it) - { - commandLine.append(" "); - commandLine.append(*it); - } - - std::wstring ucommandLine; - UnicodeConverter::toUTF16(commandLine, ucommandLine); - - STARTUPINFOW startupInfo; - GetStartupInfoW(&startupInfo); // take defaults from current process - startupInfo.cb = sizeof(STARTUPINFO); - startupInfo.lpReserved = NULL; - startupInfo.lpDesktop = NULL; - startupInfo.lpTitle = NULL; - startupInfo.dwFlags = STARTF_FORCEOFFFEEDBACK | STARTF_USESTDHANDLES; - startupInfo.cbReserved2 = 0; - startupInfo.lpReserved2 = NULL; - - HANDLE hProc = GetCurrentProcess(); - if (inPipe) - { - DuplicateHandle(hProc, inPipe->readHandle(), hProc, &startupInfo.hStdInput, 0, TRUE, DUPLICATE_SAME_ACCESS); - inPipe->close(Pipe::CLOSE_READ); - } - else DuplicateHandle(hProc, GetStdHandle(STD_INPUT_HANDLE), hProc, &startupInfo.hStdInput, 0, TRUE, DUPLICATE_SAME_ACCESS); - // outPipe may be the same as errPipe, so we duplicate first and close later. - if (outPipe) - DuplicateHandle(hProc, outPipe->writeHandle(), hProc, &startupInfo.hStdOutput, 0, TRUE, DUPLICATE_SAME_ACCESS); - else - DuplicateHandle(hProc, GetStdHandle(STD_OUTPUT_HANDLE), hProc, &startupInfo.hStdOutput, 0, TRUE, DUPLICATE_SAME_ACCESS); - if (errPipe) - DuplicateHandle(hProc, errPipe->writeHandle(), hProc, &startupInfo.hStdError, 0, TRUE, DUPLICATE_SAME_ACCESS); - else - DuplicateHandle(hProc, GetStdHandle(STD_ERROR_HANDLE), hProc, &startupInfo.hStdError, 0, TRUE, DUPLICATE_SAME_ACCESS); - if (outPipe) outPipe->close(Pipe::CLOSE_WRITE); - if (errPipe) errPipe->close(Pipe::CLOSE_WRITE); - - PROCESS_INFORMATION processInfo; - BOOL rc = CreateProcessW( - NULL, - const_cast(ucommandLine.c_str()), - NULL, - NULL, - TRUE, - 0, - NULL, - NULL, - &startupInfo, - &processInfo - ); - CloseHandle(startupInfo.hStdInput); - CloseHandle(startupInfo.hStdOutput); - CloseHandle(startupInfo.hStdError); - if (rc) - { - CloseHandle(processInfo.hThread); - return new ProcessHandleImpl(processInfo.hProcess, processInfo.dwProcessId); - } - else throw SystemException("Cannot launch process", command); -} - - -void ProcessImpl::killImpl(PIDImpl pid) -{ - HANDLE hProc = OpenProcess(PROCESS_TERMINATE, FALSE, pid); - if (hProc) - { - if (TerminateProcess(hProc, 0) == 0) - { - CloseHandle(hProc); - throw SystemException("cannot kill process"); - } - CloseHandle(hProc); - } - else - { - switch (GetLastError()) - { - case ERROR_ACCESS_DENIED: - throw NoPermissionException("cannot kill process"); - case ERROR_NOT_FOUND: - throw NotFoundException("cannot kill process"); - default: - throw SystemException("cannot kill process"); - } - } -} - - -void ProcessImpl::requestTerminationImpl(PIDImpl pid) -{ - std::string evName("POCOTRM"); - evName.append(NumberFormatter::formatHex(pid, 8)); - NamedEvent ev(evName); - ev.set(); -} - - -} // namespace Poco +// +// Process_WIN32U.cpp +// +// $Id: //poco/1.2/Foundation/src/Process_WIN32U.cpp#1 $ +// +// Library: Foundation +// Package: Processes +// Module: Process +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/Process_WIN32U.h" +#include "Poco/Exception.h" +#include "Poco/NumberFormatter.h" +#include "Poco/NamedEvent.h" +#include "Poco/UnicodeConverter.h" +#include "Poco/Pipe.h" + + +namespace Poco { + + +// +// ProcessHandleImpl +// +ProcessHandleImpl::ProcessHandleImpl(HANDLE hProcess, UInt32 pid): + _hProcess(hProcess), + _pid(pid) +{ +} + + +ProcessHandleImpl::~ProcessHandleImpl() +{ + CloseHandle(_hProcess); +} + + +UInt32 ProcessHandleImpl::id() const +{ + return _pid; +} + + +int ProcessHandleImpl::wait() const +{ + DWORD rc = WaitForSingleObject(_hProcess, INFINITE); + if (rc != WAIT_OBJECT_0) + throw SystemException("Wait failed for process", NumberFormatter::format(_pid)); + + DWORD exitCode; + if (GetExitCodeProcess(_hProcess, &exitCode) == 0) + throw SystemException("Cannot get exit code for process", NumberFormatter::format(_pid)); + + return exitCode; +} + + +// +// ProcessImpl +// +ProcessImpl::PIDImpl ProcessImpl::idImpl() +{ + return GetCurrentProcessId(); +} + + +void ProcessImpl::timesImpl(long& userTime, long& kernelTime) +{ + FILETIME ftCreation; + FILETIME ftExit; + FILETIME ftKernel; + FILETIME ftUser; + + if (GetProcessTimes(GetCurrentProcess(), &ftCreation, &ftExit, &ftKernel, &ftUser) != 0) + { + ULARGE_INTEGER time; + time.LowPart = ftKernel.dwLowDateTime; + time.HighPart = ftKernel.dwHighDateTime; + kernelTime = long(time.QuadPart/10000000L); + time.LowPart = ftUser.dwLowDateTime; + time.HighPart = ftUser.dwHighDateTime; + userTime = long(time.QuadPart/10000000L); + } + else + { + userTime = kernelTime = -1; + } +} + + +ProcessHandleImpl* ProcessImpl::launchImpl(const std::string& command, const ArgsImpl& args, Pipe* inPipe, Pipe* outPipe, Pipe* errPipe) +{ + std::string commandLine = command; + for (ArgsImpl::const_iterator it = args.begin(); it != args.end(); ++it) + { + commandLine.append(" "); + commandLine.append(*it); + } + + std::wstring ucommandLine; + UnicodeConverter::toUTF16(commandLine, ucommandLine); + + STARTUPINFOW startupInfo; + GetStartupInfoW(&startupInfo); // take defaults from current process + startupInfo.cb = sizeof(STARTUPINFO); + startupInfo.lpReserved = NULL; + startupInfo.lpDesktop = NULL; + startupInfo.lpTitle = NULL; + startupInfo.dwFlags = STARTF_FORCEOFFFEEDBACK | STARTF_USESTDHANDLES; + startupInfo.cbReserved2 = 0; + startupInfo.lpReserved2 = NULL; + + HANDLE hProc = GetCurrentProcess(); + if (inPipe) + { + DuplicateHandle(hProc, inPipe->readHandle(), hProc, &startupInfo.hStdInput, 0, TRUE, DUPLICATE_SAME_ACCESS); + inPipe->close(Pipe::CLOSE_READ); + } + else DuplicateHandle(hProc, GetStdHandle(STD_INPUT_HANDLE), hProc, &startupInfo.hStdInput, 0, TRUE, DUPLICATE_SAME_ACCESS); + // outPipe may be the same as errPipe, so we duplicate first and close later. + if (outPipe) + DuplicateHandle(hProc, outPipe->writeHandle(), hProc, &startupInfo.hStdOutput, 0, TRUE, DUPLICATE_SAME_ACCESS); + else + DuplicateHandle(hProc, GetStdHandle(STD_OUTPUT_HANDLE), hProc, &startupInfo.hStdOutput, 0, TRUE, DUPLICATE_SAME_ACCESS); + if (errPipe) + DuplicateHandle(hProc, errPipe->writeHandle(), hProc, &startupInfo.hStdError, 0, TRUE, DUPLICATE_SAME_ACCESS); + else + DuplicateHandle(hProc, GetStdHandle(STD_ERROR_HANDLE), hProc, &startupInfo.hStdError, 0, TRUE, DUPLICATE_SAME_ACCESS); + if (outPipe) outPipe->close(Pipe::CLOSE_WRITE); + if (errPipe) errPipe->close(Pipe::CLOSE_WRITE); + + PROCESS_INFORMATION processInfo; + BOOL rc = CreateProcessW( + NULL, + const_cast(ucommandLine.c_str()), + NULL, + NULL, + TRUE, + 0, + NULL, + NULL, + &startupInfo, + &processInfo + ); + CloseHandle(startupInfo.hStdInput); + CloseHandle(startupInfo.hStdOutput); + CloseHandle(startupInfo.hStdError); + if (rc) + { + CloseHandle(processInfo.hThread); + return new ProcessHandleImpl(processInfo.hProcess, processInfo.dwProcessId); + } + else throw SystemException("Cannot launch process", command); +} + + +void ProcessImpl::killImpl(PIDImpl pid) +{ + HANDLE hProc = OpenProcess(PROCESS_TERMINATE, FALSE, pid); + if (hProc) + { + if (TerminateProcess(hProc, 0) == 0) + { + CloseHandle(hProc); + throw SystemException("cannot kill process"); + } + CloseHandle(hProc); + } + else + { + switch (GetLastError()) + { + case ERROR_ACCESS_DENIED: + throw NoPermissionException("cannot kill process"); + case ERROR_NOT_FOUND: + throw NotFoundException("cannot kill process"); + default: + throw SystemException("cannot kill process"); + } + } +} + + +void ProcessImpl::requestTerminationImpl(PIDImpl pid) +{ + std::string evName("POCOTRM"); + evName.append(NumberFormatter::formatHex(pid, 8)); + NamedEvent ev(evName); + ev.set(); +} + + +} // namespace Poco diff --git a/Foundation/src/PurgeStrategy.cpp b/Foundation/src/PurgeStrategy.cpp index ac05f2b54..46312424a 100644 --- a/Foundation/src/PurgeStrategy.cpp +++ b/Foundation/src/PurgeStrategy.cpp @@ -1,153 +1,153 @@ -// -// PurgeStrategy.cpp -// -// $Id: //poco/1.2/Foundation/src/PurgeStrategy.cpp#1 $ -// -// Library: Foundation -// Package: Logging -// Module: FileChannel -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/PurgeStrategy.h" -#include "Poco/Path.h" -#include "Poco/DirectoryIterator.h" -#include "Poco/Timestamp.h" - - -namespace Poco { - - -// -// PurgeStrategy -// - - -PurgeStrategy::PurgeStrategy() -{ -} - - -PurgeStrategy::~PurgeStrategy() -{ -} - - -void PurgeStrategy::list(const std::string& path, std::vector& files) -{ - Path p(path); - p.makeAbsolute(); - Path parent = p.parent(); - std::string baseName = p.getFileName(); - baseName.append("."); - - DirectoryIterator it(Path::current()); - DirectoryIterator end; - while (it != end) - { - if (it.name().compare(0, baseName.size(), baseName) == 0) - { - files.push_back(*it); - } - ++it; - } -} - - -// -// PurgeByAgeStrategy -// - - -PurgeByAgeStrategy::PurgeByAgeStrategy(const Timespan& age): _age(age) -{ -} - - -PurgeByAgeStrategy::~PurgeByAgeStrategy() -{ -} - - -void PurgeByAgeStrategy::purge(const std::string& path) -{ - std::vector files; - list(path, files); - for (std::vector::iterator it = files.begin(); it != files.end(); ++it) - { - if (it->getLastModified().isElapsed(_age.totalMicroseconds())) - { - it->remove(); - } - } -} - - -// -// PurgeByCountStrategy -// - - -PurgeByCountStrategy::PurgeByCountStrategy(int count): _count(count) -{ - poco_assert(count > 0); -} - - -PurgeByCountStrategy::~PurgeByCountStrategy() -{ -} - - -void PurgeByCountStrategy::purge(const std::string& path) -{ - std::vector files; - list(path, files); - while (files.size() > _count) - { - std::vector::iterator it = files.begin(); - std::vector::iterator purgeIt = it; - Timestamp purgeTS = purgeIt->getLastModified(); - ++it; - while (it != files.end()) - { - Timestamp md(it->getLastModified()); - if (md <= purgeTS) - { - purgeTS = md; - purgeIt = it; - } - ++it; - } - purgeIt->remove(); - files.erase(purgeIt); - } -} - - -} // namespace Poco +// +// PurgeStrategy.cpp +// +// $Id: //poco/1.2/Foundation/src/PurgeStrategy.cpp#1 $ +// +// Library: Foundation +// Package: Logging +// Module: FileChannel +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/PurgeStrategy.h" +#include "Poco/Path.h" +#include "Poco/DirectoryIterator.h" +#include "Poco/Timestamp.h" + + +namespace Poco { + + +// +// PurgeStrategy +// + + +PurgeStrategy::PurgeStrategy() +{ +} + + +PurgeStrategy::~PurgeStrategy() +{ +} + + +void PurgeStrategy::list(const std::string& path, std::vector& files) +{ + Path p(path); + p.makeAbsolute(); + Path parent = p.parent(); + std::string baseName = p.getFileName(); + baseName.append("."); + + DirectoryIterator it(Path::current()); + DirectoryIterator end; + while (it != end) + { + if (it.name().compare(0, baseName.size(), baseName) == 0) + { + files.push_back(*it); + } + ++it; + } +} + + +// +// PurgeByAgeStrategy +// + + +PurgeByAgeStrategy::PurgeByAgeStrategy(const Timespan& age): _age(age) +{ +} + + +PurgeByAgeStrategy::~PurgeByAgeStrategy() +{ +} + + +void PurgeByAgeStrategy::purge(const std::string& path) +{ + std::vector files; + list(path, files); + for (std::vector::iterator it = files.begin(); it != files.end(); ++it) + { + if (it->getLastModified().isElapsed(_age.totalMicroseconds())) + { + it->remove(); + } + } +} + + +// +// PurgeByCountStrategy +// + + +PurgeByCountStrategy::PurgeByCountStrategy(int count): _count(count) +{ + poco_assert(count > 0); +} + + +PurgeByCountStrategy::~PurgeByCountStrategy() +{ +} + + +void PurgeByCountStrategy::purge(const std::string& path) +{ + std::vector files; + list(path, files); + while (files.size() > _count) + { + std::vector::iterator it = files.begin(); + std::vector::iterator purgeIt = it; + Timestamp purgeTS = purgeIt->getLastModified(); + ++it; + while (it != files.end()) + { + Timestamp md(it->getLastModified()); + if (md <= purgeTS) + { + purgeTS = md; + purgeIt = it; + } + ++it; + } + purgeIt->remove(); + files.erase(purgeIt); + } +} + + +} // namespace Poco diff --git a/Foundation/src/RWLock.cpp b/Foundation/src/RWLock.cpp index 2b580eb45..6b1e34be6 100644 --- a/Foundation/src/RWLock.cpp +++ b/Foundation/src/RWLock.cpp @@ -1,60 +1,60 @@ -// -// RWLock.cpp -// -// $Id: //poco/1.2/Foundation/src/RWLock.cpp#1 $ -// -// Library: Foundation -// Package: Threading -// Module: RWLock -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/RWLock.h" - - -#if defined(POCO_OS_FAMILY_WINDOWS) -#include "RWLock_WIN32.cpp" -#else -#include "RWLock_POSIX.cpp" -#endif - - -namespace Poco { - - -RWLock::RWLock() -{ -} - - -RWLock::~RWLock() -{ -} - - -} // namespace Poco +// +// RWLock.cpp +// +// $Id: //poco/1.2/Foundation/src/RWLock.cpp#1 $ +// +// Library: Foundation +// Package: Threading +// Module: RWLock +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/RWLock.h" + + +#if defined(POCO_OS_FAMILY_WINDOWS) +#include "RWLock_WIN32.cpp" +#else +#include "RWLock_POSIX.cpp" +#endif + + +namespace Poco { + + +RWLock::RWLock() +{ +} + + +RWLock::~RWLock() +{ +} + + +} // namespace Poco diff --git a/Foundation/src/RWLock_POSIX.cpp b/Foundation/src/RWLock_POSIX.cpp index ab6b0471a..c580c563b 100644 --- a/Foundation/src/RWLock_POSIX.cpp +++ b/Foundation/src/RWLock_POSIX.cpp @@ -1,56 +1,56 @@ -// -// RWLock_POSIX.cpp -// -// $Id: //poco/1.2/Foundation/src/RWLock_POSIX.cpp#1 $ -// -// Library: Foundation -// Package: Threading -// Module: RWLock -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/RWLock_POSIX.h" - - -namespace Poco { - - -RWLockImpl::RWLockImpl() -{ - if (pthread_rwlock_init(&_rwl, NULL)) - throw SystemException("cannot create reader/writer lock"); -} - - -RWLockImpl::~RWLockImpl() -{ - pthread_rwlock_destroy(&_rwl); -} - - -} // namespace Poco +// +// RWLock_POSIX.cpp +// +// $Id: //poco/1.2/Foundation/src/RWLock_POSIX.cpp#1 $ +// +// Library: Foundation +// Package: Threading +// Module: RWLock +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/RWLock_POSIX.h" + + +namespace Poco { + + +RWLockImpl::RWLockImpl() +{ + if (pthread_rwlock_init(&_rwl, NULL)) + throw SystemException("cannot create reader/writer lock"); +} + + +RWLockImpl::~RWLockImpl() +{ + pthread_rwlock_destroy(&_rwl); +} + + +} // namespace Poco diff --git a/Foundation/src/RWLock_WIN32.cpp b/Foundation/src/RWLock_WIN32.cpp index e6198257b..0ed9cd8d5 100644 --- a/Foundation/src/RWLock_WIN32.cpp +++ b/Foundation/src/RWLock_WIN32.cpp @@ -1,199 +1,199 @@ -// -// RWLock_WIN32.cpp -// -// $Id: //poco/1.2/Foundation/src/RWLock_WIN32.cpp#1 $ -// -// Library: Foundation -// Package: Threading -// Module: RWLock -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/RWLock_WIN32.h" - - -namespace Poco { - - -RWLockImpl::RWLockImpl(): _readers(0), _writers(0) -{ - _mutex = CreateMutex(NULL, FALSE, NULL); - if (_mutex == NULL) - throw SystemException("cannot create reader/writer lock"); - - _readEvent = CreateEvent(NULL, TRUE, TRUE, NULL); - if (_readEvent == NULL) - throw SystemException("cannot create reader/writer lock"); - - _writeEvent = CreateEvent(NULL, TRUE, TRUE, NULL); - if (_writeEvent == NULL) - throw SystemException("cannot create reader/writer lock"); -} - - -RWLockImpl::~RWLockImpl() -{ - CloseHandle(_mutex); - CloseHandle(_readEvent); - CloseHandle(_writeEvent); -} - - -inline void RWLockImpl::addWriter() -{ - switch (WaitForSingleObject(_mutex, INFINITE)) - { - case WAIT_OBJECT_0: - if (++_writers == 1) ResetEvent(_readEvent); - ReleaseMutex(_mutex); - break; - default: - throw SystemException("cannot lock reader/writer lock"); - } -} - - -inline void RWLockImpl::removeWriter() -{ - switch (WaitForSingleObject(_mutex, INFINITE)) - { - case WAIT_OBJECT_0: - if (--_writers == 0) SetEvent(_readEvent); - ReleaseMutex(_mutex); - break; - default: - throw SystemException("cannot lock reader/writer lock"); - } -} - - -void RWLockImpl::readLockImpl() -{ - HANDLE h[2]; - h[0] = _mutex; - h[1] = _readEvent; - switch (WaitForMultipleObjects(2, h, TRUE, INFINITE)) - { - case WAIT_OBJECT_0: - case WAIT_OBJECT_0 + 1: - ++_readers; - ResetEvent(_writeEvent); - ReleaseMutex(_mutex); - break; - default: - throw SystemException("cannot lock reader/writer lock"); - } -} - - -bool RWLockImpl::tryReadLockImpl() -{ - HANDLE h[2]; - h[0] = _mutex; - h[1] = _readEvent; - switch (WaitForMultipleObjects(2, h, TRUE, 1)) - { - case WAIT_OBJECT_0: - case WAIT_OBJECT_0 + 1: - ++_readers; - ResetEvent(_writeEvent); - ReleaseMutex(_mutex); - return true; - case WAIT_TIMEOUT: - return false; - default: - throw SystemException("cannot lock reader/writer lock"); - } -} - - -void RWLockImpl::writeLockImpl() -{ - addWriter(); - HANDLE h[2]; - h[0] = _mutex; - h[1] = _writeEvent; - switch (WaitForMultipleObjects(2, h, TRUE, INFINITE)) - { - case WAIT_OBJECT_0: - case WAIT_OBJECT_0 + 1: - --_writers; - ++_readers; - ResetEvent(_readEvent); - ResetEvent(_writeEvent); - ReleaseMutex(_mutex); - break; - default: - removeWriter(); - throw SystemException("cannot lock reader/writer lock"); - } -} - - -bool RWLockImpl::tryWriteLockImpl() -{ - addWriter(); - HANDLE h[2]; - h[0] = _mutex; - h[1] = _writeEvent; - switch (WaitForMultipleObjects(2, h, TRUE, 1)) - { - case WAIT_OBJECT_0: - case WAIT_OBJECT_0 + 1: - --_writers; - ++_readers; - ResetEvent(_readEvent); - ResetEvent(_writeEvent); - ReleaseMutex(_mutex); - return true; - case WAIT_TIMEOUT: - removeWriter(); - return false; - default: - removeWriter(); - throw SystemException("cannot lock reader/writer lock"); - } -} - - -void RWLockImpl::unlockImpl() -{ - switch (WaitForSingleObject(_mutex, INFINITE)) - { - case WAIT_OBJECT_0: - if (_writers == 0) SetEvent(_readEvent); - if (--_readers == 0) SetEvent(_writeEvent); - ReleaseMutex(_mutex); - break; - default: - throw SystemException("cannot unlock reader/writer lock"); - } -} - - -} // namespace Poco +// +// RWLock_WIN32.cpp +// +// $Id: //poco/1.2/Foundation/src/RWLock_WIN32.cpp#1 $ +// +// Library: Foundation +// Package: Threading +// Module: RWLock +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/RWLock_WIN32.h" + + +namespace Poco { + + +RWLockImpl::RWLockImpl(): _readers(0), _writers(0) +{ + _mutex = CreateMutex(NULL, FALSE, NULL); + if (_mutex == NULL) + throw SystemException("cannot create reader/writer lock"); + + _readEvent = CreateEvent(NULL, TRUE, TRUE, NULL); + if (_readEvent == NULL) + throw SystemException("cannot create reader/writer lock"); + + _writeEvent = CreateEvent(NULL, TRUE, TRUE, NULL); + if (_writeEvent == NULL) + throw SystemException("cannot create reader/writer lock"); +} + + +RWLockImpl::~RWLockImpl() +{ + CloseHandle(_mutex); + CloseHandle(_readEvent); + CloseHandle(_writeEvent); +} + + +inline void RWLockImpl::addWriter() +{ + switch (WaitForSingleObject(_mutex, INFINITE)) + { + case WAIT_OBJECT_0: + if (++_writers == 1) ResetEvent(_readEvent); + ReleaseMutex(_mutex); + break; + default: + throw SystemException("cannot lock reader/writer lock"); + } +} + + +inline void RWLockImpl::removeWriter() +{ + switch (WaitForSingleObject(_mutex, INFINITE)) + { + case WAIT_OBJECT_0: + if (--_writers == 0) SetEvent(_readEvent); + ReleaseMutex(_mutex); + break; + default: + throw SystemException("cannot lock reader/writer lock"); + } +} + + +void RWLockImpl::readLockImpl() +{ + HANDLE h[2]; + h[0] = _mutex; + h[1] = _readEvent; + switch (WaitForMultipleObjects(2, h, TRUE, INFINITE)) + { + case WAIT_OBJECT_0: + case WAIT_OBJECT_0 + 1: + ++_readers; + ResetEvent(_writeEvent); + ReleaseMutex(_mutex); + break; + default: + throw SystemException("cannot lock reader/writer lock"); + } +} + + +bool RWLockImpl::tryReadLockImpl() +{ + HANDLE h[2]; + h[0] = _mutex; + h[1] = _readEvent; + switch (WaitForMultipleObjects(2, h, TRUE, 1)) + { + case WAIT_OBJECT_0: + case WAIT_OBJECT_0 + 1: + ++_readers; + ResetEvent(_writeEvent); + ReleaseMutex(_mutex); + return true; + case WAIT_TIMEOUT: + return false; + default: + throw SystemException("cannot lock reader/writer lock"); + } +} + + +void RWLockImpl::writeLockImpl() +{ + addWriter(); + HANDLE h[2]; + h[0] = _mutex; + h[1] = _writeEvent; + switch (WaitForMultipleObjects(2, h, TRUE, INFINITE)) + { + case WAIT_OBJECT_0: + case WAIT_OBJECT_0 + 1: + --_writers; + ++_readers; + ResetEvent(_readEvent); + ResetEvent(_writeEvent); + ReleaseMutex(_mutex); + break; + default: + removeWriter(); + throw SystemException("cannot lock reader/writer lock"); + } +} + + +bool RWLockImpl::tryWriteLockImpl() +{ + addWriter(); + HANDLE h[2]; + h[0] = _mutex; + h[1] = _writeEvent; + switch (WaitForMultipleObjects(2, h, TRUE, 1)) + { + case WAIT_OBJECT_0: + case WAIT_OBJECT_0 + 1: + --_writers; + ++_readers; + ResetEvent(_readEvent); + ResetEvent(_writeEvent); + ReleaseMutex(_mutex); + return true; + case WAIT_TIMEOUT: + removeWriter(); + return false; + default: + removeWriter(); + throw SystemException("cannot lock reader/writer lock"); + } +} + + +void RWLockImpl::unlockImpl() +{ + switch (WaitForSingleObject(_mutex, INFINITE)) + { + case WAIT_OBJECT_0: + if (_writers == 0) SetEvent(_readEvent); + if (--_readers == 0) SetEvent(_writeEvent); + ReleaseMutex(_mutex); + break; + default: + throw SystemException("cannot unlock reader/writer lock"); + } +} + + +} // namespace Poco diff --git a/Foundation/src/Random.cpp b/Foundation/src/Random.cpp index 075c91156..5b23502e7 100644 --- a/Foundation/src/Random.cpp +++ b/Foundation/src/Random.cpp @@ -1,382 +1,382 @@ -// -// Random.cpp -// -// $Id: //poco/1.2/Foundation/src/Random.cpp#2 $ -// -// Library: Foundation -// Package: Crypt -// Module: Random -// -// Definition of class Random. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// -// -// Based on the FreeBSD random number generator. -// src/lib/libc/stdlib/random.c,v 1.13 2000/01/27 23:06:49 jasone Exp -// -// Copyright (c) 1983, 1993 -// The Regents of the University of California. 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. -// 3. All advertising materials mentioning features or use of this software -// must display the following acknowledgement: -// This product includes software developed by the University of -// California, Berkeley and its contributors. -// 4. Neither the name of the University nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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. -// - - -#include "Poco/Random.h" -#include "Poco/RandomStream.h" -#include "time.h" - - -/* - * random.c: - * - * An improved random number generation package. In addition to the standard - * rand()/srand() like interface, this package also has a special state info - * interface. The initstate() routine is called with a seed, an array of - * bytes, and a count of how many bytes are being passed in; this array is - * then initialized to contain information for random number generation with - * that much state information. Good sizes for the amount of state - * information are 32, 64, 128, and 256 bytes. The state can be switched by - * calling the setstate() routine with the same array as was initiallized - * with initstate(). By default, the package runs with 128 bytes of state - * information and generates far better random numbers than a linear - * congruential generator. If the amount of state information is less than - * 32 bytes, a simple linear congruential R.N.G. is used. - * - * Internally, the state information is treated as an array of longs; the - * zeroeth element of the array is the type of R.N.G. being used (small - * integer); the remainder of the array is the state information for the - * R.N.G. Thus, 32 bytes of state information will give 7 longs worth of - * state information, which will allow a degree seven polynomial. (Note: - * the zeroeth word of state information also has some other information - * stored in it -- see setstate() for details). - * - * The random number generation technique is a linear feedback shift register - * approach, employing trinomials (since there are fewer terms to sum up that - * way). In this approach, the least significant bit of all the numbers in - * the state table will act as a linear feedback shift register, and will - * have period 2^deg - 1 (where deg is the degree of the polynomial being - * used, assuming that the polynomial is irreducible and primitive). The - * higher order bits will have longer periods, since their values are also - * influenced by pseudo-random carries out of the lower bits. The total - * period of the generator is approximately deg*(2**deg - 1); thus doubling - * the amount of state information has a vast influence on the period of the - * generator. Note: the deg*(2**deg - 1) is an approximation only good for - * large deg, when the period of the shift register is the dominant factor. - * With deg equal to seven, the period is actually much longer than the - * 7*(2**7 - 1) predicted by this formula. - * - * Modified 28 December 1994 by Jacob S. Rosenberg. - * The following changes have been made: - * All references to the type u_int have been changed to unsigned long. - * All references to type int have been changed to type long. Other - * cleanups have been made as well. A warning for both initstate and - * setstate has been inserted to the effect that on Sparc platforms - * the 'arg_state' variable must be forced to begin on word boundaries. - * This can be easily done by casting a long integer array to char *. - * The overall logic has been left STRICTLY alone. This software was - * tested on both a VAX and Sun SpacsStation with exactly the same - * results. The new version and the original give IDENTICAL results. - * The new version is somewhat faster than the original. As the - * documentation says: "By default, the package runs with 128 bytes of - * state information and generates far better random numbers than a linear - * congruential generator. If the amount of state information is less than - * 32 bytes, a simple linear congruential R.N.G. is used." For a buffer of - * 128 bytes, this new version runs about 19 percent faster and for a 16 - * byte buffer it is about 5 percent faster. - */ - - -/* - * For each of the currently supported random number generators, we have a - * break value on the amount of state information (you need at least this - * many bytes of state info to support this random number generator), a degree - * for the polynomial (actually a trinomial) that the R.N.G. is based on, and - * the separation between the two lower order coefficients of the trinomial. - */ -#define TYPE_0 0 /* linear congruential */ -#define BREAK_0 8 -#define DEG_0 0 -#define SEP_0 0 - -#define TYPE_1 1 /* x**7 + x**3 + 1 */ -#define BREAK_1 32 -#define DEG_1 7 -#define SEP_1 3 - -#define TYPE_2 2 /* x**15 + x + 1 */ -#define BREAK_2 64 -#define DEG_2 15 -#define SEP_2 1 - -#define TYPE_3 3 /* x**31 + x**3 + 1 */ -#define BREAK_3 128 -#define DEG_3 31 -#define SEP_3 3 - -#define TYPE_4 4 /* x**63 + x + 1 */ -#define BREAK_4 256 -#define DEG_4 63 -#define SEP_4 1 - - -namespace Poco { - - -Random::Random(int stateSize) -{ - poco_assert (BREAK_0 <= stateSize && stateSize <= BREAK_4); - - _pBuffer = new char[stateSize]; - initState((UInt32) time(NULL), _pBuffer, stateSize); -} - - -Random::~Random() -{ - delete [] _pBuffer; -} - - -/* - * Compute x = (7^5 * x) mod (2^31 - 1) - * wihout overflowing 31 bits: - * (2^31 - 1) = 127773 * (7^5) + 2836 - * From "Random number generators: good ones are hard to find", - * Park and Miller, Communications of the ACM, vol. 31, no. 10, - * October 1988, p. 1195. - */ -inline UInt32 Random::goodRand(Int32 x) -{ - Int32 hi, lo; - - if (x == 0) x = 123459876; - hi = x / 127773; - lo = x % 127773; - x = 16807 * lo - 2836 * hi; - if (x < 0) x += 0x7FFFFFFF; - - return x; -} - - -/* - * Initialize the random number generator based on the given seed. If the - * type is the trivial no-state-information type, just remember the seed. - * Otherwise, initializes state[] based on the given "seed" via a linear - * congruential generator. Then, the pointers are set to known locations - * that are exactly rand_sep places apart. Lastly, it cycles the state - * information a given number of times to get rid of any initial dependencies - * introduced by the L.C.R.N.G. Note that the initialization of randtbl[] - * for default usage relies on values produced by this routine. - */ -void Random::seed(UInt32 x) -{ - int i, lim; - - _state[0] = x; - if (_randType == TYPE_0) - lim = NSHUFF; - else - { - for (i = 1; i < _randDeg; i++) - _state[i] = goodRand(_state[i - 1]); - _fptr = &_state[_randSep]; - _rptr = &_state[0]; - lim = 10 * _randDeg; - } - for (i = 0; i < lim; i++) - next(); -} - - -/* - * Many programs choose the seed value in a totally predictable manner. - * This often causes problems. We seed the generator using the much more - * secure random(4) interface. Note that this particular seeding - * procedure can generate states which are impossible to reproduce by - * calling srandom() with any value, since the succeeding terms in the - * state buffer are no longer derived from the LC algorithm applied to - * a fixed seed. - */ -void Random::seed() -{ - std::streamsize len; - - if (_randType == TYPE_0) - len = sizeof _state[0]; - else - len = _randDeg * sizeof _state[0]; - - RandomInputStream rstr; - rstr.read((char*) _state, len); -} - - -/* - * Initialize the state information in the given array of n bytes for future - * random number generation. Based on the number of bytes we are given, and - * the break values for the different R.N.G.'s, we choose the best (largest) - * one we can and set things up for it. srandom() is then called to - * initialize the state information. - * - * Note that on return from srandom(), we set state[-1] to be the type - * multiplexed with the current value of the rear pointer; this is so - * successive calls to initstate() won't lose this information and will be - * able to restart with setstate(). - * - * Note: the first thing we do is save the current state, if any, just like - * setstate() so that it doesn't matter when initstate is called. - * - * Returns a pointer to the old state. - * - * word boundary; otherwise a bus error will occur. Even so, lint will - * complain about mis-alignment, but you should disregard these messages. - */ -void Random::initState(UInt32 s, char* argState, Int32 n) -{ - UInt32* intArgState = (UInt32*) argState; - - if (n < BREAK_0) - { - poco_bugcheck_msg("not enough state"); - return; - } - if (n < BREAK_1) - { - _randType = TYPE_0; - _randDeg = DEG_0; - _randSep = SEP_0; - } - else if (n < BREAK_2) - { - _randType = TYPE_1; - _randDeg = DEG_1; - _randSep = SEP_1; - } - else if (n < BREAK_3) - { - _randType = TYPE_2; - _randDeg = DEG_2; - _randSep = SEP_2; - } - else if (n < BREAK_4) - { - _randType = TYPE_3; - _randDeg = DEG_3; - _randSep = SEP_3; - } - else - { - _randType = TYPE_4; - _randDeg = DEG_4; - _randSep = SEP_4; - } - _state = intArgState + 1; /* first location */ - _endPtr = &_state[_randDeg]; /* must set end_ptr before seed */ - seed(s); - if (_randType == TYPE_0) - intArgState[0] = _randType; - else - intArgState[0] = MAX_TYPES * (int) (_rptr - _state) + _randType; -} - - -/* - * Next: - * - * If we are using the trivial TYPE_0 R.N.G., just do the old linear - * congruential bit. Otherwise, we do our fancy trinomial stuff, which is - * the same in all the other cases due to all the global variables that have - * been set up. The basic operation is to add the number at the rear pointer - * into the one at the front pointer. Then both pointers are advanced to - * the next location cyclically in the table. The value returned is the sum - * generated, reduced to 31 bits by throwing away the "least random" low bit. - * - * Note: the code takes advantage of the fact that both the front and - * rear pointers can't wrap on the same call by not testing the rear - * pointer if the front one has wrapped. - * - * Returns a 31-bit random number. - */ -UInt32 Random::next() -{ - UInt32 i; - UInt32 *f, *r; - - if (_randType == TYPE_0) - { - i = _state[0]; - _state[0] = i = goodRand(i) & 0x7FFFFFFF; - } - else - { - /* - * Use local variables rather than static variables for speed. - */ - f = _fptr; r = _rptr; - *f += *r; - i = (*f >> 1) & 0x7FFFFFFF; /* chucking least random bit */ - if (++f >= _endPtr) { - f = _state; - ++r; - } - else if (++r >= _endPtr) { - r = _state; - } - - _fptr = f; _rptr = r; - } - return i; -} - - -} // namespace Poco +// +// Random.cpp +// +// $Id: //poco/1.2/Foundation/src/Random.cpp#2 $ +// +// Library: Foundation +// Package: Crypt +// Module: Random +// +// Definition of class Random. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// +// +// Based on the FreeBSD random number generator. +// src/lib/libc/stdlib/random.c,v 1.13 2000/01/27 23:06:49 jasone Exp +// +// Copyright (c) 1983, 1993 +// The Regents of the University of California. 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. +// 3. All advertising materials mentioning features or use of this software +// must display the following acknowledgement: +// This product includes software developed by the University of +// California, Berkeley and its contributors. +// 4. Neither the name of the University nor the names of its contributors +// may be used to endorse or promote products derived from this software +// without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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. +// + + +#include "Poco/Random.h" +#include "Poco/RandomStream.h" +#include "time.h" + + +/* + * random.c: + * + * An improved random number generation package. In addition to the standard + * rand()/srand() like interface, this package also has a special state info + * interface. The initstate() routine is called with a seed, an array of + * bytes, and a count of how many bytes are being passed in; this array is + * then initialized to contain information for random number generation with + * that much state information. Good sizes for the amount of state + * information are 32, 64, 128, and 256 bytes. The state can be switched by + * calling the setstate() routine with the same array as was initiallized + * with initstate(). By default, the package runs with 128 bytes of state + * information and generates far better random numbers than a linear + * congruential generator. If the amount of state information is less than + * 32 bytes, a simple linear congruential R.N.G. is used. + * + * Internally, the state information is treated as an array of longs; the + * zeroeth element of the array is the type of R.N.G. being used (small + * integer); the remainder of the array is the state information for the + * R.N.G. Thus, 32 bytes of state information will give 7 longs worth of + * state information, which will allow a degree seven polynomial. (Note: + * the zeroeth word of state information also has some other information + * stored in it -- see setstate() for details). + * + * The random number generation technique is a linear feedback shift register + * approach, employing trinomials (since there are fewer terms to sum up that + * way). In this approach, the least significant bit of all the numbers in + * the state table will act as a linear feedback shift register, and will + * have period 2^deg - 1 (where deg is the degree of the polynomial being + * used, assuming that the polynomial is irreducible and primitive). The + * higher order bits will have longer periods, since their values are also + * influenced by pseudo-random carries out of the lower bits. The total + * period of the generator is approximately deg*(2**deg - 1); thus doubling + * the amount of state information has a vast influence on the period of the + * generator. Note: the deg*(2**deg - 1) is an approximation only good for + * large deg, when the period of the shift register is the dominant factor. + * With deg equal to seven, the period is actually much longer than the + * 7*(2**7 - 1) predicted by this formula. + * + * Modified 28 December 1994 by Jacob S. Rosenberg. + * The following changes have been made: + * All references to the type u_int have been changed to unsigned long. + * All references to type int have been changed to type long. Other + * cleanups have been made as well. A warning for both initstate and + * setstate has been inserted to the effect that on Sparc platforms + * the 'arg_state' variable must be forced to begin on word boundaries. + * This can be easily done by casting a long integer array to char *. + * The overall logic has been left STRICTLY alone. This software was + * tested on both a VAX and Sun SpacsStation with exactly the same + * results. The new version and the original give IDENTICAL results. + * The new version is somewhat faster than the original. As the + * documentation says: "By default, the package runs with 128 bytes of + * state information and generates far better random numbers than a linear + * congruential generator. If the amount of state information is less than + * 32 bytes, a simple linear congruential R.N.G. is used." For a buffer of + * 128 bytes, this new version runs about 19 percent faster and for a 16 + * byte buffer it is about 5 percent faster. + */ + + +/* + * For each of the currently supported random number generators, we have a + * break value on the amount of state information (you need at least this + * many bytes of state info to support this random number generator), a degree + * for the polynomial (actually a trinomial) that the R.N.G. is based on, and + * the separation between the two lower order coefficients of the trinomial. + */ +#define TYPE_0 0 /* linear congruential */ +#define BREAK_0 8 +#define DEG_0 0 +#define SEP_0 0 + +#define TYPE_1 1 /* x**7 + x**3 + 1 */ +#define BREAK_1 32 +#define DEG_1 7 +#define SEP_1 3 + +#define TYPE_2 2 /* x**15 + x + 1 */ +#define BREAK_2 64 +#define DEG_2 15 +#define SEP_2 1 + +#define TYPE_3 3 /* x**31 + x**3 + 1 */ +#define BREAK_3 128 +#define DEG_3 31 +#define SEP_3 3 + +#define TYPE_4 4 /* x**63 + x + 1 */ +#define BREAK_4 256 +#define DEG_4 63 +#define SEP_4 1 + + +namespace Poco { + + +Random::Random(int stateSize) +{ + poco_assert (BREAK_0 <= stateSize && stateSize <= BREAK_4); + + _pBuffer = new char[stateSize]; + initState((UInt32) time(NULL), _pBuffer, stateSize); +} + + +Random::~Random() +{ + delete [] _pBuffer; +} + + +/* + * Compute x = (7^5 * x) mod (2^31 - 1) + * wihout overflowing 31 bits: + * (2^31 - 1) = 127773 * (7^5) + 2836 + * From "Random number generators: good ones are hard to find", + * Park and Miller, Communications of the ACM, vol. 31, no. 10, + * October 1988, p. 1195. + */ +inline UInt32 Random::goodRand(Int32 x) +{ + Int32 hi, lo; + + if (x == 0) x = 123459876; + hi = x / 127773; + lo = x % 127773; + x = 16807 * lo - 2836 * hi; + if (x < 0) x += 0x7FFFFFFF; + + return x; +} + + +/* + * Initialize the random number generator based on the given seed. If the + * type is the trivial no-state-information type, just remember the seed. + * Otherwise, initializes state[] based on the given "seed" via a linear + * congruential generator. Then, the pointers are set to known locations + * that are exactly rand_sep places apart. Lastly, it cycles the state + * information a given number of times to get rid of any initial dependencies + * introduced by the L.C.R.N.G. Note that the initialization of randtbl[] + * for default usage relies on values produced by this routine. + */ +void Random::seed(UInt32 x) +{ + int i, lim; + + _state[0] = x; + if (_randType == TYPE_0) + lim = NSHUFF; + else + { + for (i = 1; i < _randDeg; i++) + _state[i] = goodRand(_state[i - 1]); + _fptr = &_state[_randSep]; + _rptr = &_state[0]; + lim = 10 * _randDeg; + } + for (i = 0; i < lim; i++) + next(); +} + + +/* + * Many programs choose the seed value in a totally predictable manner. + * This often causes problems. We seed the generator using the much more + * secure random(4) interface. Note that this particular seeding + * procedure can generate states which are impossible to reproduce by + * calling srandom() with any value, since the succeeding terms in the + * state buffer are no longer derived from the LC algorithm applied to + * a fixed seed. + */ +void Random::seed() +{ + std::streamsize len; + + if (_randType == TYPE_0) + len = sizeof _state[0]; + else + len = _randDeg * sizeof _state[0]; + + RandomInputStream rstr; + rstr.read((char*) _state, len); +} + + +/* + * Initialize the state information in the given array of n bytes for future + * random number generation. Based on the number of bytes we are given, and + * the break values for the different R.N.G.'s, we choose the best (largest) + * one we can and set things up for it. srandom() is then called to + * initialize the state information. + * + * Note that on return from srandom(), we set state[-1] to be the type + * multiplexed with the current value of the rear pointer; this is so + * successive calls to initstate() won't lose this information and will be + * able to restart with setstate(). + * + * Note: the first thing we do is save the current state, if any, just like + * setstate() so that it doesn't matter when initstate is called. + * + * Returns a pointer to the old state. + * + * word boundary; otherwise a bus error will occur. Even so, lint will + * complain about mis-alignment, but you should disregard these messages. + */ +void Random::initState(UInt32 s, char* argState, Int32 n) +{ + UInt32* intArgState = (UInt32*) argState; + + if (n < BREAK_0) + { + poco_bugcheck_msg("not enough state"); + return; + } + if (n < BREAK_1) + { + _randType = TYPE_0; + _randDeg = DEG_0; + _randSep = SEP_0; + } + else if (n < BREAK_2) + { + _randType = TYPE_1; + _randDeg = DEG_1; + _randSep = SEP_1; + } + else if (n < BREAK_3) + { + _randType = TYPE_2; + _randDeg = DEG_2; + _randSep = SEP_2; + } + else if (n < BREAK_4) + { + _randType = TYPE_3; + _randDeg = DEG_3; + _randSep = SEP_3; + } + else + { + _randType = TYPE_4; + _randDeg = DEG_4; + _randSep = SEP_4; + } + _state = intArgState + 1; /* first location */ + _endPtr = &_state[_randDeg]; /* must set end_ptr before seed */ + seed(s); + if (_randType == TYPE_0) + intArgState[0] = _randType; + else + intArgState[0] = MAX_TYPES * (int) (_rptr - _state) + _randType; +} + + +/* + * Next: + * + * If we are using the trivial TYPE_0 R.N.G., just do the old linear + * congruential bit. Otherwise, we do our fancy trinomial stuff, which is + * the same in all the other cases due to all the global variables that have + * been set up. The basic operation is to add the number at the rear pointer + * into the one at the front pointer. Then both pointers are advanced to + * the next location cyclically in the table. The value returned is the sum + * generated, reduced to 31 bits by throwing away the "least random" low bit. + * + * Note: the code takes advantage of the fact that both the front and + * rear pointers can't wrap on the same call by not testing the rear + * pointer if the front one has wrapped. + * + * Returns a 31-bit random number. + */ +UInt32 Random::next() +{ + UInt32 i; + UInt32 *f, *r; + + if (_randType == TYPE_0) + { + i = _state[0]; + _state[0] = i = goodRand(i) & 0x7FFFFFFF; + } + else + { + /* + * Use local variables rather than static variables for speed. + */ + f = _fptr; r = _rptr; + *f += *r; + i = (*f >> 1) & 0x7FFFFFFF; /* chucking least random bit */ + if (++f >= _endPtr) { + f = _state; + ++r; + } + else if (++r >= _endPtr) { + r = _state; + } + + _fptr = f; _rptr = r; + } + return i; +} + + +} // namespace Poco diff --git a/Foundation/src/RandomStream.cpp b/Foundation/src/RandomStream.cpp index 335a580c0..4dc56515c 100644 --- a/Foundation/src/RandomStream.cpp +++ b/Foundation/src/RandomStream.cpp @@ -1,149 +1,149 @@ -// -// RandomStream.cpp -// -// $Id: //poco/1.2/Foundation/src/RandomStream.cpp#1 $ -// -// Library: Foundation -// Package: Crypt -// Module: RandomStream -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/RandomStream.h" -#include "Poco/Random.h" -#include "Poco/SHA1Engine.h" -#if defined(POCO_OS_FAMILY_WINDOWS) -#include -#include -#elif defined(POCO_OS_FAMILY_UNIX) -#include -#include -#endif -#include - - -namespace Poco { - - -RandomBuf::RandomBuf(): BufferedStreamBuf(256, std::ios::in) -{ -} - - -RandomBuf::~RandomBuf() -{ -} - - -int RandomBuf::readFromDevice(char* buffer, std::streamsize length) -{ - int n = 0; - -#if defined(POCO_OS_FAMILY_WINDOWS) - HCRYPTPROV hProvider = 0; - CryptAcquireContext(&hProvider, 0, 0, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT); - CryptGenRandom(hProvider, length, (BYTE*) buffer); - CryptReleaseContext(hProvider, 0); - n = length; -#else - #if defined(POCO_OS_FAMILY_UNIX) - int fd = open("/dev/urandom", O_RDONLY, 0); - if (fd >= 0) - { - n = read(fd, buffer, length); - close(fd); - } - #endif - if (n <= 0) - { - // x is here as a source of randomness, so it does not make - // much sense to protect it with a Mutex. - static UInt32 x = 0; - Random rnd1(256); - Random rnd2(64); - x += rnd1.next(); - - n = 0; - SHA1Engine engine; - UInt32 t = (UInt32) time(NULL); - engine.update(&t, sizeof(t)); - void* p = this; - engine.update(&p, sizeof(p)); - engine.update(buffer, length); - UInt32 junk[32]; - engine.update(junk, sizeof(junk)); - while (n < length) - { - for (int i = 0; i < 100; ++i) - { - UInt32 r = rnd2.next(); - engine.update(&r, sizeof(r)); - engine.update(&x, sizeof(x)); - x += rnd1.next(); - } - DigestEngine::Digest d = engine.digest(); - for (DigestEngine::Digest::const_iterator it = d.begin(); it != d.end() && n < length; ++it, ++n) - { - engine.update(*it); - *buffer++ = *it++; - } - } - } -#endif - return n; -} - - -RandomIOS::RandomIOS() -{ - poco_ios_init(&_buf); -} - - -RandomIOS::~RandomIOS() -{ -} - - -RandomBuf* RandomIOS::rdbuf() -{ - return &_buf; -} - - -RandomInputStream::RandomInputStream(): std::istream(&_buf) -{ -} - - -RandomInputStream::~RandomInputStream() -{ -} - - -} // namespace Poco +// +// RandomStream.cpp +// +// $Id: //poco/1.2/Foundation/src/RandomStream.cpp#1 $ +// +// Library: Foundation +// Package: Crypt +// Module: RandomStream +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/RandomStream.h" +#include "Poco/Random.h" +#include "Poco/SHA1Engine.h" +#if defined(POCO_OS_FAMILY_WINDOWS) +#include +#include +#elif defined(POCO_OS_FAMILY_UNIX) +#include +#include +#endif +#include + + +namespace Poco { + + +RandomBuf::RandomBuf(): BufferedStreamBuf(256, std::ios::in) +{ +} + + +RandomBuf::~RandomBuf() +{ +} + + +int RandomBuf::readFromDevice(char* buffer, std::streamsize length) +{ + int n = 0; + +#if defined(POCO_OS_FAMILY_WINDOWS) + HCRYPTPROV hProvider = 0; + CryptAcquireContext(&hProvider, 0, 0, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT); + CryptGenRandom(hProvider, length, (BYTE*) buffer); + CryptReleaseContext(hProvider, 0); + n = length; +#else + #if defined(POCO_OS_FAMILY_UNIX) + int fd = open("/dev/urandom", O_RDONLY, 0); + if (fd >= 0) + { + n = read(fd, buffer, length); + close(fd); + } + #endif + if (n <= 0) + { + // x is here as a source of randomness, so it does not make + // much sense to protect it with a Mutex. + static UInt32 x = 0; + Random rnd1(256); + Random rnd2(64); + x += rnd1.next(); + + n = 0; + SHA1Engine engine; + UInt32 t = (UInt32) time(NULL); + engine.update(&t, sizeof(t)); + void* p = this; + engine.update(&p, sizeof(p)); + engine.update(buffer, length); + UInt32 junk[32]; + engine.update(junk, sizeof(junk)); + while (n < length) + { + for (int i = 0; i < 100; ++i) + { + UInt32 r = rnd2.next(); + engine.update(&r, sizeof(r)); + engine.update(&x, sizeof(x)); + x += rnd1.next(); + } + DigestEngine::Digest d = engine.digest(); + for (DigestEngine::Digest::const_iterator it = d.begin(); it != d.end() && n < length; ++it, ++n) + { + engine.update(*it); + *buffer++ = *it++; + } + } + } +#endif + return n; +} + + +RandomIOS::RandomIOS() +{ + poco_ios_init(&_buf); +} + + +RandomIOS::~RandomIOS() +{ +} + + +RandomBuf* RandomIOS::rdbuf() +{ + return &_buf; +} + + +RandomInputStream::RandomInputStream(): std::istream(&_buf) +{ +} + + +RandomInputStream::~RandomInputStream() +{ +} + + +} // namespace Poco diff --git a/Foundation/src/RefCountedObject.cpp b/Foundation/src/RefCountedObject.cpp index 01c1ba74c..529a6b50a 100644 --- a/Foundation/src/RefCountedObject.cpp +++ b/Foundation/src/RefCountedObject.cpp @@ -1,70 +1,70 @@ -// -// RefCountedObject.cpp -// -// $Id: //poco/1.2/Foundation/src/RefCountedObject.cpp#1 $ -// -// Library: Foundation -// Package: Core -// Module: RefCountedObject -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/RefCountedObject.h" - - -namespace Poco { - - -RefCountedObject::RefCountedObject(): _rc(1) -{ -} - - -RefCountedObject::~RefCountedObject() -{ -} - - -void RefCountedObject::duplicate() const -{ - _rcMutex.lock(); - ++_rc; - _rcMutex.unlock(); -} - - -void RefCountedObject::release() const -{ - _rcMutex.lock(); - int rc = --_rc; - _rcMutex.unlock(); - if (rc == 0) delete this; -} - - -} // namespace Poco +// +// RefCountedObject.cpp +// +// $Id: //poco/1.2/Foundation/src/RefCountedObject.cpp#1 $ +// +// Library: Foundation +// Package: Core +// Module: RefCountedObject +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/RefCountedObject.h" + + +namespace Poco { + + +RefCountedObject::RefCountedObject(): _rc(1) +{ +} + + +RefCountedObject::~RefCountedObject() +{ +} + + +void RefCountedObject::duplicate() const +{ + _rcMutex.lock(); + ++_rc; + _rcMutex.unlock(); +} + + +void RefCountedObject::release() const +{ + _rcMutex.lock(); + int rc = --_rc; + _rcMutex.unlock(); + if (rc == 0) delete this; +} + + +} // namespace Poco diff --git a/Foundation/src/RegularExpression.cpp b/Foundation/src/RegularExpression.cpp index 3f3e85aa5..87639d9b5 100644 --- a/Foundation/src/RegularExpression.cpp +++ b/Foundation/src/RegularExpression.cpp @@ -1,291 +1,291 @@ -// -// RegularExpression.h -// -// $Id: //poco/1.2/Foundation/src/RegularExpression.cpp#1 $ -// -// Library: Foundation -// Package: RegExp -// Module: RegularExpression -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/RegularExpression.h" -#include "Poco/Exception.h" -#include -#include "pcre.h" - - -namespace Poco { - - -const int RegularExpression::OVEC_SIZE = 64; - - -RegularExpression::RegularExpression(const std::string& pattern, int options, bool study): _pcre(0), _extra(0) -{ - const char* error; - int offs; - _pcre = pcre_compile(pattern.c_str(), options, &error, &offs, 0); - if (!_pcre) - { - std::ostringstream msg; - msg << error << " (at offset " << offs << ")"; - throw RegularExpressionException(msg.str()); - } - if (study) - _extra = pcre_study(_pcre, 0, &error); -} - - -RegularExpression::~RegularExpression() -{ - if (_pcre) pcre_free(_pcre); - if (_extra) pcre_free(_extra); -} - - -int RegularExpression::match(const std::string& subject, std::string::size_type offset, Match& mtch, int options) const -{ - poco_assert (offset <= subject.length()); - - int ovec[OVEC_SIZE]; - int rc = pcre_exec(_pcre, _extra, subject.c_str(), int(subject.size()), int(offset), options & 0xFFFF, ovec, OVEC_SIZE); - if (rc == PCRE_ERROR_NOMATCH) - { - mtch.offset = std::string::npos; - mtch.length = 0; - return 0; - } - else if (rc == PCRE_ERROR_BADOPTION) - { - throw RegularExpressionException("bad option"); - } - else if (rc == 0) - { - throw RegularExpressionException("too many captured substrings"); - } - else if (rc < 0) - { - std::ostringstream msg; - msg << "PCRE error " << rc; - throw RegularExpressionException(msg.str()); - } - mtch.offset = ovec[0] < 0 ? std::string::npos : ovec[0]; - mtch.length = ovec[1] - mtch.offset; - return rc; -} - - -int RegularExpression::match(const std::string& subject, std::string::size_type offset, MatchVec& matches, int options) const -{ - poco_assert (offset <= subject.length()); - - matches.clear(); - - int ovec[OVEC_SIZE]; - int rc = pcre_exec(_pcre, _extra, subject.c_str(), int(subject.size()), int(offset), options & 0xFFFF, ovec, OVEC_SIZE); - if (rc == PCRE_ERROR_NOMATCH) - { - return 0; - } - else if (rc == PCRE_ERROR_BADOPTION) - { - throw RegularExpressionException("bad option"); - } - else if (rc == 0) - { - throw RegularExpressionException("too many captured substrings"); - } - else if (rc < 0) - { - std::ostringstream msg; - msg << "PCRE error " << rc; - throw RegularExpressionException(msg.str()); - } - matches.reserve(rc); - for (int i = 0; i < rc; ++i) - { - Match m; - m.offset = ovec[i*2] < 0 ? std::string::npos : ovec[i*2] ; - m.length = ovec[i*2 + 1] - m.offset; - matches.push_back(m); - } - return rc; -} - - -bool RegularExpression::match(const std::string& subject, std::string::size_type offset) const -{ - Match mtch; - match(subject, offset, mtch, RE_ANCHORED | RE_NOTEMPTY); - return mtch.offset == offset && mtch.length == subject.length() - offset; -} - - -int RegularExpression::extract(const std::string& subject, std::string& str, int options) const -{ - Match mtch; - int rc = match(subject, 0, mtch, options); - if (mtch.offset != std::string::npos) - str.assign(subject, mtch.offset, mtch.length); - else - str.clear(); - return rc; -} - - -int RegularExpression::extract(const std::string& subject, std::string::size_type offset, std::string& str, int options) const -{ - Match mtch; - int rc = match(subject, offset, mtch, options); - if (mtch.offset != std::string::npos) - str.assign(subject, mtch.offset, mtch.length); - else - str.clear(); - return rc; -} - - -int RegularExpression::split(const std::string& subject, std::string::size_type offset, std::vector& strings, int options) const -{ - MatchVec matches; - strings.clear(); - int rc = match(subject, offset, matches, options); - strings.reserve(matches.size()); - for (MatchVec::const_iterator it = matches.begin(); it != matches.end(); ++it) - { - if (it->offset != std::string::npos) - strings.push_back(subject.substr(it->offset, it->length)); - else - strings.push_back(std::string()); - } - return rc; -} - - -int RegularExpression::subst(std::string& subject, std::string::size_type offset, const std::string& replacement, int options) const -{ - if (options & RE_GLOBAL) - { - int rc = 0; - std::string::size_type pos = substOne(subject, offset, replacement, options); - while (pos != std::string::npos) - { - ++rc; - pos = substOne(subject, pos, replacement, options); - } - return rc; - } - else - { - return substOne(subject, offset, replacement, options) != std::string::npos ? 1 : 0; - } -} - - -std::string::size_type RegularExpression::substOne(std::string& subject, std::string::size_type offset, const std::string& replacement, int options) const -{ - if (offset >= subject.length()) return std::string::npos; - - int ovec[OVEC_SIZE]; - int rc = pcre_exec(_pcre, _extra, subject.c_str(), int(subject.size()), int(offset), options & 0xFFFF, ovec, OVEC_SIZE); - if (rc == PCRE_ERROR_NOMATCH) - { - return std::string::npos; - } - else if (rc == PCRE_ERROR_BADOPTION) - { - throw RegularExpressionException("bad option"); - } - else if (rc == 0) - { - throw RegularExpressionException("too many captured substrings"); - } - else if (rc < 0) - { - std::ostringstream msg; - msg << "PCRE error " << rc; - throw RegularExpressionException(msg.str()); - } - std::string result; - std::string::size_type len = subject.length(); - std::string::size_type pos = 0; - std::string::size_type rp = std::string::npos; - while (pos < len) - { - if (ovec[0] == pos) - { - std::string::const_iterator it = replacement.begin(); - std::string::const_iterator end = replacement.end(); - while (it != end) - { - if (*it == '$' && !(options & RE_NO_VARS)) - { - ++it; - if (it != end) - { - char d = *it; - if (d >= '0' && d <= '9') - { - int c = d - '0'; - if (c < rc) - { - int o = ovec[c*2]; - int l = ovec[c*2 + 1] - o; - result.append(subject, o, l); - } - } - else - { - result += '$'; - result += d; - } - ++it; - } - else result += '$'; - } - else result += *it++; - } - pos = ovec[1]; - rp = result.length(); - } - else result += subject[pos++]; - } - subject = result; - return rp; -} - - -bool RegularExpression::match(const std::string& subject, const std::string& pattern, int options) -{ - RegularExpression re(pattern, options, false); - return re.match(subject); -} - - -} // namespace Poco +// +// RegularExpression.h +// +// $Id: //poco/1.2/Foundation/src/RegularExpression.cpp#1 $ +// +// Library: Foundation +// Package: RegExp +// Module: RegularExpression +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/RegularExpression.h" +#include "Poco/Exception.h" +#include +#include "pcre.h" + + +namespace Poco { + + +const int RegularExpression::OVEC_SIZE = 64; + + +RegularExpression::RegularExpression(const std::string& pattern, int options, bool study): _pcre(0), _extra(0) +{ + const char* error; + int offs; + _pcre = pcre_compile(pattern.c_str(), options, &error, &offs, 0); + if (!_pcre) + { + std::ostringstream msg; + msg << error << " (at offset " << offs << ")"; + throw RegularExpressionException(msg.str()); + } + if (study) + _extra = pcre_study(_pcre, 0, &error); +} + + +RegularExpression::~RegularExpression() +{ + if (_pcre) pcre_free(_pcre); + if (_extra) pcre_free(_extra); +} + + +int RegularExpression::match(const std::string& subject, std::string::size_type offset, Match& mtch, int options) const +{ + poco_assert (offset <= subject.length()); + + int ovec[OVEC_SIZE]; + int rc = pcre_exec(_pcre, _extra, subject.c_str(), int(subject.size()), int(offset), options & 0xFFFF, ovec, OVEC_SIZE); + if (rc == PCRE_ERROR_NOMATCH) + { + mtch.offset = std::string::npos; + mtch.length = 0; + return 0; + } + else if (rc == PCRE_ERROR_BADOPTION) + { + throw RegularExpressionException("bad option"); + } + else if (rc == 0) + { + throw RegularExpressionException("too many captured substrings"); + } + else if (rc < 0) + { + std::ostringstream msg; + msg << "PCRE error " << rc; + throw RegularExpressionException(msg.str()); + } + mtch.offset = ovec[0] < 0 ? std::string::npos : ovec[0]; + mtch.length = ovec[1] - mtch.offset; + return rc; +} + + +int RegularExpression::match(const std::string& subject, std::string::size_type offset, MatchVec& matches, int options) const +{ + poco_assert (offset <= subject.length()); + + matches.clear(); + + int ovec[OVEC_SIZE]; + int rc = pcre_exec(_pcre, _extra, subject.c_str(), int(subject.size()), int(offset), options & 0xFFFF, ovec, OVEC_SIZE); + if (rc == PCRE_ERROR_NOMATCH) + { + return 0; + } + else if (rc == PCRE_ERROR_BADOPTION) + { + throw RegularExpressionException("bad option"); + } + else if (rc == 0) + { + throw RegularExpressionException("too many captured substrings"); + } + else if (rc < 0) + { + std::ostringstream msg; + msg << "PCRE error " << rc; + throw RegularExpressionException(msg.str()); + } + matches.reserve(rc); + for (int i = 0; i < rc; ++i) + { + Match m; + m.offset = ovec[i*2] < 0 ? std::string::npos : ovec[i*2] ; + m.length = ovec[i*2 + 1] - m.offset; + matches.push_back(m); + } + return rc; +} + + +bool RegularExpression::match(const std::string& subject, std::string::size_type offset) const +{ + Match mtch; + match(subject, offset, mtch, RE_ANCHORED | RE_NOTEMPTY); + return mtch.offset == offset && mtch.length == subject.length() - offset; +} + + +int RegularExpression::extract(const std::string& subject, std::string& str, int options) const +{ + Match mtch; + int rc = match(subject, 0, mtch, options); + if (mtch.offset != std::string::npos) + str.assign(subject, mtch.offset, mtch.length); + else + str.clear(); + return rc; +} + + +int RegularExpression::extract(const std::string& subject, std::string::size_type offset, std::string& str, int options) const +{ + Match mtch; + int rc = match(subject, offset, mtch, options); + if (mtch.offset != std::string::npos) + str.assign(subject, mtch.offset, mtch.length); + else + str.clear(); + return rc; +} + + +int RegularExpression::split(const std::string& subject, std::string::size_type offset, std::vector& strings, int options) const +{ + MatchVec matches; + strings.clear(); + int rc = match(subject, offset, matches, options); + strings.reserve(matches.size()); + for (MatchVec::const_iterator it = matches.begin(); it != matches.end(); ++it) + { + if (it->offset != std::string::npos) + strings.push_back(subject.substr(it->offset, it->length)); + else + strings.push_back(std::string()); + } + return rc; +} + + +int RegularExpression::subst(std::string& subject, std::string::size_type offset, const std::string& replacement, int options) const +{ + if (options & RE_GLOBAL) + { + int rc = 0; + std::string::size_type pos = substOne(subject, offset, replacement, options); + while (pos != std::string::npos) + { + ++rc; + pos = substOne(subject, pos, replacement, options); + } + return rc; + } + else + { + return substOne(subject, offset, replacement, options) != std::string::npos ? 1 : 0; + } +} + + +std::string::size_type RegularExpression::substOne(std::string& subject, std::string::size_type offset, const std::string& replacement, int options) const +{ + if (offset >= subject.length()) return std::string::npos; + + int ovec[OVEC_SIZE]; + int rc = pcre_exec(_pcre, _extra, subject.c_str(), int(subject.size()), int(offset), options & 0xFFFF, ovec, OVEC_SIZE); + if (rc == PCRE_ERROR_NOMATCH) + { + return std::string::npos; + } + else if (rc == PCRE_ERROR_BADOPTION) + { + throw RegularExpressionException("bad option"); + } + else if (rc == 0) + { + throw RegularExpressionException("too many captured substrings"); + } + else if (rc < 0) + { + std::ostringstream msg; + msg << "PCRE error " << rc; + throw RegularExpressionException(msg.str()); + } + std::string result; + std::string::size_type len = subject.length(); + std::string::size_type pos = 0; + std::string::size_type rp = std::string::npos; + while (pos < len) + { + if (ovec[0] == pos) + { + std::string::const_iterator it = replacement.begin(); + std::string::const_iterator end = replacement.end(); + while (it != end) + { + if (*it == '$' && !(options & RE_NO_VARS)) + { + ++it; + if (it != end) + { + char d = *it; + if (d >= '0' && d <= '9') + { + int c = d - '0'; + if (c < rc) + { + int o = ovec[c*2]; + int l = ovec[c*2 + 1] - o; + result.append(subject, o, l); + } + } + else + { + result += '$'; + result += d; + } + ++it; + } + else result += '$'; + } + else result += *it++; + } + pos = ovec[1]; + rp = result.length(); + } + else result += subject[pos++]; + } + subject = result; + return rp; +} + + +bool RegularExpression::match(const std::string& subject, const std::string& pattern, int options) +{ + RegularExpression re(pattern, options, false); + return re.match(subject); +} + + +} // namespace Poco diff --git a/Foundation/src/RotateStrategy.cpp b/Foundation/src/RotateStrategy.cpp index 52e5c10b4..385466dfe 100644 --- a/Foundation/src/RotateStrategy.cpp +++ b/Foundation/src/RotateStrategy.cpp @@ -1,103 +1,103 @@ -// -// RotateStrategy.cpp -// -// $Id: //poco/1.2/Foundation/src/RotateStrategy.cpp#1 $ -// -// Library: Foundation -// Package: Logging -// Module: FileChannel -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/RotateStrategy.h" - - -namespace Poco { - - -// -// RotateStrategy -// - - -RotateStrategy::RotateStrategy() -{ -} - - -RotateStrategy::~RotateStrategy() -{ -} - - -// -// RotateByIntervalStrategy -// - - -RotateByIntervalStrategy::RotateByIntervalStrategy(const Timespan& span): _span(span) -{ - if (span.totalMicroseconds() <= 0) throw InvalidArgumentException("time span must be greater than zero"); -} - - -RotateByIntervalStrategy::~RotateByIntervalStrategy() -{ -} - - -bool RotateByIntervalStrategy::mustRotate(LogFile* pFile) -{ - Timestamp now; - return _span <= now - pFile->creationDate(); -} - - -// -// RotateBySizeStrategy -// - - -RotateBySizeStrategy::RotateBySizeStrategy(UInt64 size): _size(size) -{ - if (size == 0) throw InvalidArgumentException("size must be greater than zero"); -} - - -RotateBySizeStrategy::~RotateBySizeStrategy() -{ -} - - -bool RotateBySizeStrategy::mustRotate(LogFile* pFile) -{ - return pFile->size() >= _size; -} - - -} // namespace Poco +// +// RotateStrategy.cpp +// +// $Id: //poco/1.2/Foundation/src/RotateStrategy.cpp#1 $ +// +// Library: Foundation +// Package: Logging +// Module: FileChannel +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/RotateStrategy.h" + + +namespace Poco { + + +// +// RotateStrategy +// + + +RotateStrategy::RotateStrategy() +{ +} + + +RotateStrategy::~RotateStrategy() +{ +} + + +// +// RotateByIntervalStrategy +// + + +RotateByIntervalStrategy::RotateByIntervalStrategy(const Timespan& span): _span(span) +{ + if (span.totalMicroseconds() <= 0) throw InvalidArgumentException("time span must be greater than zero"); +} + + +RotateByIntervalStrategy::~RotateByIntervalStrategy() +{ +} + + +bool RotateByIntervalStrategy::mustRotate(LogFile* pFile) +{ + Timestamp now; + return _span <= now - pFile->creationDate(); +} + + +// +// RotateBySizeStrategy +// + + +RotateBySizeStrategy::RotateBySizeStrategy(UInt64 size): _size(size) +{ + if (size == 0) throw InvalidArgumentException("size must be greater than zero"); +} + + +RotateBySizeStrategy::~RotateBySizeStrategy() +{ +} + + +bool RotateBySizeStrategy::mustRotate(LogFile* pFile) +{ + return pFile->size() >= _size; +} + + +} // namespace Poco diff --git a/Foundation/src/Runnable.cpp b/Foundation/src/Runnable.cpp index 530010e02..f05d594c6 100644 --- a/Foundation/src/Runnable.cpp +++ b/Foundation/src/Runnable.cpp @@ -1,53 +1,53 @@ -// -// Runnable.cpp -// -// $Id: //poco/1.2/Foundation/src/Runnable.cpp#1 $ -// -// Library: Foundation -// Package: Threading -// Module: Thread -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/Runnable.h" - - -namespace Poco { - - -Runnable::Runnable() -{ -} - - -Runnable::~Runnable() -{ -} - - -} // namespace Poco +// +// Runnable.cpp +// +// $Id: //poco/1.2/Foundation/src/Runnable.cpp#1 $ +// +// Library: Foundation +// Package: Threading +// Module: Thread +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/Runnable.h" + + +namespace Poco { + + +Runnable::Runnable() +{ +} + + +Runnable::~Runnable() +{ +} + + +} // namespace Poco diff --git a/Foundation/src/SHA1Engine.cpp b/Foundation/src/SHA1Engine.cpp index 33f467d67..a21c4d3f7 100644 --- a/Foundation/src/SHA1Engine.cpp +++ b/Foundation/src/SHA1Engine.cpp @@ -1,305 +1,305 @@ -// -// SHA1Engine.cpp -// -// $Id: //poco/1.2/Foundation/src/SHA1Engine.cpp#2 $ -// -// Library: Foundation -// Package: Crypt -// Module: SHA1Engine -// -// Based on the public domain implementation by Peter C. Gutmann -// on 2 Sep 1992, modified by Carl Ellison to be SHA-1. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/SHA1Engine.h" -#include - - -#ifdef POCO_ARCH_LITTLE_ENDIAN - #define SHA1_BYTE_REVERSE(x, y) byteReverse(x, y) -#else - #define SHA1_BYTE_REVERSE(x, y) -#endif - - -namespace Poco { - - -SHA1Engine::SHA1Engine() -{ - _digest.reserve(16); - reset(); -} - - -SHA1Engine::~SHA1Engine() -{ - reset(); -} - - -inline void SHA1Engine::byteReverse(UInt32* buffer, int byteCount) -{ -#ifdef POCO_ARCH_LITTLE_ENDIAN - byteCount /= sizeof(UInt32); - for(int count = 0; count < byteCount; count++) - { - UInt32 value = (buffer[ count ] << 16) | (buffer[ count ] >> 16); - buffer[count] = ((value & 0xFF00FF00L) >> 8) | ((value & 0x00FF00FFL) << 8); - } -#endif // POCO_ARCH_LITTLE_ENDIAN -} - - -void SHA1Engine::updateImpl(const void* buffer_, unsigned count) -{ - const BYTE* buffer = (const BYTE*) buffer_; - BYTE* db = (BYTE*) &_context.data[0]; - - /* Update bitcount */ - if ((_context.countLo + ((UInt32) count << 3)) < _context.countLo) - _context.countHi++; /* Carry from low to high bitCount */ - _context.countLo += ((UInt32) count << 3); - _context.countHi += ((UInt32 ) count >> 29); - - /* Process data in BLOCK_SIZE chunks */ - while (count-- > 0) - { - db[_context.slop++] = *(buffer++); - if (_context.slop == BLOCK_SIZE) - { - /* transform this one block */ - SHA1_BYTE_REVERSE(_context.data, BLOCK_SIZE); - transform(); - _context.slop = 0 ; /* no slop left */ - } - } -} - - -unsigned SHA1Engine::digestLength() const -{ - return DIGEST_SIZE; -} - - -void SHA1Engine::reset() -{ - _context.digest[0] = 0x67452301L; - _context.digest[1] = 0xEFCDAB89L; - _context.digest[2] = 0x98BADCFEL; - _context.digest[3] = 0x10325476L; - _context.digest[4] = 0xC3D2E1F0L; - _context.countLo = 0; - _context.countHi = 0; - _context.slop = 0; - memset(_context.data, 0, sizeof(_context.data)); -} - - -const DigestEngine::Digest& SHA1Engine::digest() -{ - int count; - UInt32 lowBitcount = _context.countLo; - UInt32 highBitcount = _context.countHi; - - /* Compute number of bytes mod 64 */ - count = (int) ((_context.countLo >> 3) & 0x3F); - - /* Set the first char of padding to 0x80. This is safe since there is - always at least one byte free */ - ((BYTE*) _context.data)[count++] = 0x80; - - /* Pad out to 56 mod 64 */ - if (count > 56) - { - /* Two lots of padding: Pad the first block to 64 bytes */ - memset((BYTE*) &_context.data + count, 0, 64 - count); - SHA1_BYTE_REVERSE(_context.data, BLOCK_SIZE); - transform(); - - /* Now fill the next block with 56 bytes */ - memset(&_context.data, 0, 56); - } - else - { - /* Pad block to 56 bytes */ - memset((BYTE*) &_context.data + count, 0, 56 - count); - } - SHA1_BYTE_REVERSE(_context.data, BLOCK_SIZE); - - /* Append length in bits and transform */ - _context.data[14] = highBitcount; - _context.data[15] = lowBitcount; - - transform(); - SHA1_BYTE_REVERSE(_context.data, DIGEST_SIZE); - - unsigned char hash[DIGEST_SIZE]; - for (count = 0; count < DIGEST_SIZE; count++) - hash[count] = (BYTE) ((_context.digest[count>>2]) >> (8*(3-(count & 0x3)))) & 0xff; - _digest.clear(); - _digest.insert(_digest.begin(), hash, hash + DIGEST_SIZE); - reset(); - return _digest; -} - - -/* The SHA f()-functions */ -#define f1(x,y,z) ( ( x & y ) | ( ~x & z ) ) /* Rounds 0-19 */ -#define f2(x,y,z) ( x ^ y ^ z ) /* Rounds 20-39 */ -#define f3(x,y,z) ( ( x & y ) | ( x & z ) | ( y & z ) ) /* Rounds 40-59 */ -#define f4(x,y,z) ( x ^ y ^ z ) /* Rounds 60-79 */ - - -/* The SHA Mysterious Constants */ -#define K1 0x5A827999L /* Rounds 0-19 */ -#define K2 0x6ED9EBA1L /* Rounds 20-39 */ -#define K3 0x8F1BBCDCL /* Rounds 40-59 */ -#define K4 0xCA62C1D6L /* Rounds 60-79 */ - - -/* 32-bit rotate - kludged with shifts */ -typedef UInt32 UL; /* to save space */ - - -#define S(n,X) ( ( ((UL)X) << n ) | ( ((UL)X) >> ( 32 - n ) ) ) - - -/* The initial expanding function */ -#define expand(count) W[ count ] = S(1,(W[ count - 3 ] ^ W[ count - 8 ] ^ W[ count - 14 ] ^ W[ count - 16 ])) /* to make this SHA-1 */ - - -/* The four SHA sub-rounds */ -#define subRound1(count) \ -{ \ - temp = S( 5, A ) + f1( B, C, D ) + E + W[ count ] + K1; \ - E = D; \ - D = C; \ - C = S( 30, B ); \ - B = A; \ - A = temp; \ -} - -#define subRound2(count) \ -{ \ - temp = S( 5, A ) + f2( B, C, D ) + E + W[ count ] + K2; \ - E = D; \ - D = C; \ - C = S( 30, B ); \ - B = A; \ - A = temp; \ -} - -#define subRound3(count) \ -{ \ - temp = S( 5, A ) + f3( B, C, D ) + E + W[ count ] + K3; \ - E = D; \ - D = C; \ - C = S( 30, B ); \ - B = A; \ - A = temp; \ -} - -#define subRound4(count) \ -{ \ - temp = S( 5, A ) + f4( B, C, D ) + E + W[ count ] + K4; \ - E = D; \ - D = C; \ - C = S( 30, B ); \ - B = A; \ - A = temp; \ -} - - -void SHA1Engine::transform() -{ - UInt32 W[80]; - UInt32 temp; - UInt32 A, B, C, D, E; - int i; - - /* Step A. Copy the data buffer into the local work buffer */ - for( i = 0; i < 16; i++ ) - W[ i ] = _context.data[ i ]; - - /* Step B. Expand the 16 words into 64 temporary data words */ - expand( 16 ); expand( 17 ); expand( 18 ); expand( 19 ); expand( 20 ); - expand( 21 ); expand( 22 ); expand( 23 ); expand( 24 ); expand( 25 ); - expand( 26 ); expand( 27 ); expand( 28 ); expand( 29 ); expand( 30 ); - expand( 31 ); expand( 32 ); expand( 33 ); expand( 34 ); expand( 35 ); - expand( 36 ); expand( 37 ); expand( 38 ); expand( 39 ); expand( 40 ); - expand( 41 ); expand( 42 ); expand( 43 ); expand( 44 ); expand( 45 ); - expand( 46 ); expand( 47 ); expand( 48 ); expand( 49 ); expand( 50 ); - expand( 51 ); expand( 52 ); expand( 53 ); expand( 54 ); expand( 55 ); - expand( 56 ); expand( 57 ); expand( 58 ); expand( 59 ); expand( 60 ); - expand( 61 ); expand( 62 ); expand( 63 ); expand( 64 ); expand( 65 ); - expand( 66 ); expand( 67 ); expand( 68 ); expand( 69 ); expand( 70 ); - expand( 71 ); expand( 72 ); expand( 73 ); expand( 74 ); expand( 75 ); - expand( 76 ); expand( 77 ); expand( 78 ); expand( 79 ); - - /* Step C. Set up first buffer */ - A = _context.digest[ 0 ]; - B = _context.digest[ 1 ]; - C = _context.digest[ 2 ]; - D = _context.digest[ 3 ]; - E = _context.digest[ 4 ]; - - /* Step D. Serious mangling, divided into four sub-rounds */ - subRound1( 0 ); subRound1( 1 ); subRound1( 2 ); subRound1( 3 ); - subRound1( 4 ); subRound1( 5 ); subRound1( 6 ); subRound1( 7 ); - subRound1( 8 ); subRound1( 9 ); subRound1( 10 ); subRound1( 11 ); - subRound1( 12 ); subRound1( 13 ); subRound1( 14 ); subRound1( 15 ); - subRound1( 16 ); subRound1( 17 ); subRound1( 18 ); subRound1( 19 ); - subRound2( 20 ); subRound2( 21 ); subRound2( 22 ); subRound2( 23 ); - subRound2( 24 ); subRound2( 25 ); subRound2( 26 ); subRound2( 27 ); - subRound2( 28 ); subRound2( 29 ); subRound2( 30 ); subRound2( 31 ); - subRound2( 32 ); subRound2( 33 ); subRound2( 34 ); subRound2( 35 ); - subRound2( 36 ); subRound2( 37 ); subRound2( 38 ); subRound2( 39 ); - subRound3( 40 ); subRound3( 41 ); subRound3( 42 ); subRound3( 43 ); - subRound3( 44 ); subRound3( 45 ); subRound3( 46 ); subRound3( 47 ); - subRound3( 48 ); subRound3( 49 ); subRound3( 50 ); subRound3( 51 ); - subRound3( 52 ); subRound3( 53 ); subRound3( 54 ); subRound3( 55 ); - subRound3( 56 ); subRound3( 57 ); subRound3( 58 ); subRound3( 59 ); - subRound4( 60 ); subRound4( 61 ); subRound4( 62 ); subRound4( 63 ); - subRound4( 64 ); subRound4( 65 ); subRound4( 66 ); subRound4( 67 ); - subRound4( 68 ); subRound4( 69 ); subRound4( 70 ); subRound4( 71 ); - subRound4( 72 ); subRound4( 73 ); subRound4( 74 ); subRound4( 75 ); - subRound4( 76 ); subRound4( 77 ); subRound4( 78 ); subRound4( 79 ); - - /* Step E. Build message digest */ - _context.digest[ 0 ] += A; - _context.digest[ 1 ] += B; - _context.digest[ 2 ] += C; - _context.digest[ 3 ] += D; - _context.digest[ 4 ] += E; -} - - -} // namespace Poco +// +// SHA1Engine.cpp +// +// $Id: //poco/1.2/Foundation/src/SHA1Engine.cpp#2 $ +// +// Library: Foundation +// Package: Crypt +// Module: SHA1Engine +// +// Based on the public domain implementation by Peter C. Gutmann +// on 2 Sep 1992, modified by Carl Ellison to be SHA-1. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/SHA1Engine.h" +#include + + +#ifdef POCO_ARCH_LITTLE_ENDIAN + #define SHA1_BYTE_REVERSE(x, y) byteReverse(x, y) +#else + #define SHA1_BYTE_REVERSE(x, y) +#endif + + +namespace Poco { + + +SHA1Engine::SHA1Engine() +{ + _digest.reserve(16); + reset(); +} + + +SHA1Engine::~SHA1Engine() +{ + reset(); +} + + +inline void SHA1Engine::byteReverse(UInt32* buffer, int byteCount) +{ +#ifdef POCO_ARCH_LITTLE_ENDIAN + byteCount /= sizeof(UInt32); + for(int count = 0; count < byteCount; count++) + { + UInt32 value = (buffer[ count ] << 16) | (buffer[ count ] >> 16); + buffer[count] = ((value & 0xFF00FF00L) >> 8) | ((value & 0x00FF00FFL) << 8); + } +#endif // POCO_ARCH_LITTLE_ENDIAN +} + + +void SHA1Engine::updateImpl(const void* buffer_, unsigned count) +{ + const BYTE* buffer = (const BYTE*) buffer_; + BYTE* db = (BYTE*) &_context.data[0]; + + /* Update bitcount */ + if ((_context.countLo + ((UInt32) count << 3)) < _context.countLo) + _context.countHi++; /* Carry from low to high bitCount */ + _context.countLo += ((UInt32) count << 3); + _context.countHi += ((UInt32 ) count >> 29); + + /* Process data in BLOCK_SIZE chunks */ + while (count-- > 0) + { + db[_context.slop++] = *(buffer++); + if (_context.slop == BLOCK_SIZE) + { + /* transform this one block */ + SHA1_BYTE_REVERSE(_context.data, BLOCK_SIZE); + transform(); + _context.slop = 0 ; /* no slop left */ + } + } +} + + +unsigned SHA1Engine::digestLength() const +{ + return DIGEST_SIZE; +} + + +void SHA1Engine::reset() +{ + _context.digest[0] = 0x67452301L; + _context.digest[1] = 0xEFCDAB89L; + _context.digest[2] = 0x98BADCFEL; + _context.digest[3] = 0x10325476L; + _context.digest[4] = 0xC3D2E1F0L; + _context.countLo = 0; + _context.countHi = 0; + _context.slop = 0; + memset(_context.data, 0, sizeof(_context.data)); +} + + +const DigestEngine::Digest& SHA1Engine::digest() +{ + int count; + UInt32 lowBitcount = _context.countLo; + UInt32 highBitcount = _context.countHi; + + /* Compute number of bytes mod 64 */ + count = (int) ((_context.countLo >> 3) & 0x3F); + + /* Set the first char of padding to 0x80. This is safe since there is + always at least one byte free */ + ((BYTE*) _context.data)[count++] = 0x80; + + /* Pad out to 56 mod 64 */ + if (count > 56) + { + /* Two lots of padding: Pad the first block to 64 bytes */ + memset((BYTE*) &_context.data + count, 0, 64 - count); + SHA1_BYTE_REVERSE(_context.data, BLOCK_SIZE); + transform(); + + /* Now fill the next block with 56 bytes */ + memset(&_context.data, 0, 56); + } + else + { + /* Pad block to 56 bytes */ + memset((BYTE*) &_context.data + count, 0, 56 - count); + } + SHA1_BYTE_REVERSE(_context.data, BLOCK_SIZE); + + /* Append length in bits and transform */ + _context.data[14] = highBitcount; + _context.data[15] = lowBitcount; + + transform(); + SHA1_BYTE_REVERSE(_context.data, DIGEST_SIZE); + + unsigned char hash[DIGEST_SIZE]; + for (count = 0; count < DIGEST_SIZE; count++) + hash[count] = (BYTE) ((_context.digest[count>>2]) >> (8*(3-(count & 0x3)))) & 0xff; + _digest.clear(); + _digest.insert(_digest.begin(), hash, hash + DIGEST_SIZE); + reset(); + return _digest; +} + + +/* The SHA f()-functions */ +#define f1(x,y,z) ( ( x & y ) | ( ~x & z ) ) /* Rounds 0-19 */ +#define f2(x,y,z) ( x ^ y ^ z ) /* Rounds 20-39 */ +#define f3(x,y,z) ( ( x & y ) | ( x & z ) | ( y & z ) ) /* Rounds 40-59 */ +#define f4(x,y,z) ( x ^ y ^ z ) /* Rounds 60-79 */ + + +/* The SHA Mysterious Constants */ +#define K1 0x5A827999L /* Rounds 0-19 */ +#define K2 0x6ED9EBA1L /* Rounds 20-39 */ +#define K3 0x8F1BBCDCL /* Rounds 40-59 */ +#define K4 0xCA62C1D6L /* Rounds 60-79 */ + + +/* 32-bit rotate - kludged with shifts */ +typedef UInt32 UL; /* to save space */ + + +#define S(n,X) ( ( ((UL)X) << n ) | ( ((UL)X) >> ( 32 - n ) ) ) + + +/* The initial expanding function */ +#define expand(count) W[ count ] = S(1,(W[ count - 3 ] ^ W[ count - 8 ] ^ W[ count - 14 ] ^ W[ count - 16 ])) /* to make this SHA-1 */ + + +/* The four SHA sub-rounds */ +#define subRound1(count) \ +{ \ + temp = S( 5, A ) + f1( B, C, D ) + E + W[ count ] + K1; \ + E = D; \ + D = C; \ + C = S( 30, B ); \ + B = A; \ + A = temp; \ +} + +#define subRound2(count) \ +{ \ + temp = S( 5, A ) + f2( B, C, D ) + E + W[ count ] + K2; \ + E = D; \ + D = C; \ + C = S( 30, B ); \ + B = A; \ + A = temp; \ +} + +#define subRound3(count) \ +{ \ + temp = S( 5, A ) + f3( B, C, D ) + E + W[ count ] + K3; \ + E = D; \ + D = C; \ + C = S( 30, B ); \ + B = A; \ + A = temp; \ +} + +#define subRound4(count) \ +{ \ + temp = S( 5, A ) + f4( B, C, D ) + E + W[ count ] + K4; \ + E = D; \ + D = C; \ + C = S( 30, B ); \ + B = A; \ + A = temp; \ +} + + +void SHA1Engine::transform() +{ + UInt32 W[80]; + UInt32 temp; + UInt32 A, B, C, D, E; + int i; + + /* Step A. Copy the data buffer into the local work buffer */ + for( i = 0; i < 16; i++ ) + W[ i ] = _context.data[ i ]; + + /* Step B. Expand the 16 words into 64 temporary data words */ + expand( 16 ); expand( 17 ); expand( 18 ); expand( 19 ); expand( 20 ); + expand( 21 ); expand( 22 ); expand( 23 ); expand( 24 ); expand( 25 ); + expand( 26 ); expand( 27 ); expand( 28 ); expand( 29 ); expand( 30 ); + expand( 31 ); expand( 32 ); expand( 33 ); expand( 34 ); expand( 35 ); + expand( 36 ); expand( 37 ); expand( 38 ); expand( 39 ); expand( 40 ); + expand( 41 ); expand( 42 ); expand( 43 ); expand( 44 ); expand( 45 ); + expand( 46 ); expand( 47 ); expand( 48 ); expand( 49 ); expand( 50 ); + expand( 51 ); expand( 52 ); expand( 53 ); expand( 54 ); expand( 55 ); + expand( 56 ); expand( 57 ); expand( 58 ); expand( 59 ); expand( 60 ); + expand( 61 ); expand( 62 ); expand( 63 ); expand( 64 ); expand( 65 ); + expand( 66 ); expand( 67 ); expand( 68 ); expand( 69 ); expand( 70 ); + expand( 71 ); expand( 72 ); expand( 73 ); expand( 74 ); expand( 75 ); + expand( 76 ); expand( 77 ); expand( 78 ); expand( 79 ); + + /* Step C. Set up first buffer */ + A = _context.digest[ 0 ]; + B = _context.digest[ 1 ]; + C = _context.digest[ 2 ]; + D = _context.digest[ 3 ]; + E = _context.digest[ 4 ]; + + /* Step D. Serious mangling, divided into four sub-rounds */ + subRound1( 0 ); subRound1( 1 ); subRound1( 2 ); subRound1( 3 ); + subRound1( 4 ); subRound1( 5 ); subRound1( 6 ); subRound1( 7 ); + subRound1( 8 ); subRound1( 9 ); subRound1( 10 ); subRound1( 11 ); + subRound1( 12 ); subRound1( 13 ); subRound1( 14 ); subRound1( 15 ); + subRound1( 16 ); subRound1( 17 ); subRound1( 18 ); subRound1( 19 ); + subRound2( 20 ); subRound2( 21 ); subRound2( 22 ); subRound2( 23 ); + subRound2( 24 ); subRound2( 25 ); subRound2( 26 ); subRound2( 27 ); + subRound2( 28 ); subRound2( 29 ); subRound2( 30 ); subRound2( 31 ); + subRound2( 32 ); subRound2( 33 ); subRound2( 34 ); subRound2( 35 ); + subRound2( 36 ); subRound2( 37 ); subRound2( 38 ); subRound2( 39 ); + subRound3( 40 ); subRound3( 41 ); subRound3( 42 ); subRound3( 43 ); + subRound3( 44 ); subRound3( 45 ); subRound3( 46 ); subRound3( 47 ); + subRound3( 48 ); subRound3( 49 ); subRound3( 50 ); subRound3( 51 ); + subRound3( 52 ); subRound3( 53 ); subRound3( 54 ); subRound3( 55 ); + subRound3( 56 ); subRound3( 57 ); subRound3( 58 ); subRound3( 59 ); + subRound4( 60 ); subRound4( 61 ); subRound4( 62 ); subRound4( 63 ); + subRound4( 64 ); subRound4( 65 ); subRound4( 66 ); subRound4( 67 ); + subRound4( 68 ); subRound4( 69 ); subRound4( 70 ); subRound4( 71 ); + subRound4( 72 ); subRound4( 73 ); subRound4( 74 ); subRound4( 75 ); + subRound4( 76 ); subRound4( 77 ); subRound4( 78 ); subRound4( 79 ); + + /* Step E. Build message digest */ + _context.digest[ 0 ] += A; + _context.digest[ 1 ] += B; + _context.digest[ 2 ] += C; + _context.digest[ 3 ] += D; + _context.digest[ 4 ] += E; +} + + +} // namespace Poco diff --git a/Foundation/src/Semaphore.cpp b/Foundation/src/Semaphore.cpp index 676c1c000..50d14ddff 100644 --- a/Foundation/src/Semaphore.cpp +++ b/Foundation/src/Semaphore.cpp @@ -1,65 +1,65 @@ -// -// Semaphore.cpp -// -// $Id: //poco/1.2/Foundation/src/Semaphore.cpp#1 $ -// -// Library: Foundation -// Package: Threading -// Module: Semaphore -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/Semaphore.h" - - -#if defined(POCO_OS_FAMILY_WINDOWS) -#include "Semaphore_WIN32.cpp" -#else -#include "Semaphore_POSIX.cpp" -#endif - - -namespace Poco { - - -Semaphore::Semaphore(int n): SemaphoreImpl(n, n) -{ -} - - -Semaphore::Semaphore(int n, int max): SemaphoreImpl(n, max) -{ -} - - -Semaphore::~Semaphore() -{ -} - - -} // namespace Poco +// +// Semaphore.cpp +// +// $Id: //poco/1.2/Foundation/src/Semaphore.cpp#1 $ +// +// Library: Foundation +// Package: Threading +// Module: Semaphore +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/Semaphore.h" + + +#if defined(POCO_OS_FAMILY_WINDOWS) +#include "Semaphore_WIN32.cpp" +#else +#include "Semaphore_POSIX.cpp" +#endif + + +namespace Poco { + + +Semaphore::Semaphore(int n): SemaphoreImpl(n, n) +{ +} + + +Semaphore::Semaphore(int n, int max): SemaphoreImpl(n, max) +{ +} + + +Semaphore::~Semaphore() +{ +} + + +} // namespace Poco diff --git a/Foundation/src/Semaphore_POSIX.cpp b/Foundation/src/Semaphore_POSIX.cpp index 10f7fb49c..2c50c69d1 100644 --- a/Foundation/src/Semaphore_POSIX.cpp +++ b/Foundation/src/Semaphore_POSIX.cpp @@ -1,118 +1,118 @@ -// -// Semaphore_POSIX.cpp -// -// $Id: //poco/1.2/Foundation/src/Semaphore_POSIX.cpp#1 $ -// -// Library: Foundation -// Package: Threading -// Module: Semaphore -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/Semaphore_POSIX.h" -#include - - -namespace Poco { - - -SemaphoreImpl::SemaphoreImpl(int n, int max): _n(n), _max(max) -{ - poco_assert (n >= 0 && max > 0 && n <= max); - - if (pthread_mutex_init(&_mutex, NULL)) - throw SystemException("cannot create semaphore (mutex)"); - if (pthread_cond_init(&_cond, NULL)) - throw SystemException("cannot create semaphore (condition)"); -} - - -SemaphoreImpl::~SemaphoreImpl() -{ - pthread_cond_destroy(&_cond); - pthread_mutex_destroy(&_mutex); -} - - -void SemaphoreImpl::waitImpl() -{ - if (pthread_mutex_lock(&_mutex)) - throw SystemException("wait for semaphore failed (lock)"); - while (_n < 1) - { - if (pthread_cond_wait(&_cond, &_mutex)) - { - pthread_mutex_unlock(&_mutex); - throw SystemException("wait for semaphore failed"); - } - } - --_n; - pthread_mutex_unlock(&_mutex); -} - - -bool SemaphoreImpl::waitImpl(long milliseconds) -{ - int rc = 0; - struct timespec abstime; - -#if defined(__VMS) - struct timespec delta; - delta.tv_sec = milliseconds / 1000; - delta.tv_nsec = (milliseconds % 1000)*1000000; - pthread_get_expiration_np(&delta, &abstime); -#else - struct timeval tv; - gettimeofday(&tv, NULL); - abstime.tv_sec = tv.tv_sec + milliseconds / 1000; - abstime.tv_nsec = tv.tv_usec*1000 + (milliseconds % 1000)*1000000; - if (abstime.tv_nsec >= 1000000000) - { - abstime.tv_nsec -= 1000000000; - abstime.tv_sec++; - } -#endif - - if (pthread_mutex_lock(&_mutex) != 0) - throw SystemException("wait for semaphore failed (lock)"); - while (_n < 1) - { - if ((rc = pthread_cond_timedwait(&_cond, &_mutex, &abstime))) - { - if (rc == ETIMEDOUT) break; - pthread_mutex_unlock(&_mutex); - throw SystemException("cannot wait for semaphore"); - } - } - if (rc == 0) --_n; - pthread_mutex_unlock(&_mutex); - return rc == 0; -} - - -} // namespace Poco +// +// Semaphore_POSIX.cpp +// +// $Id: //poco/1.2/Foundation/src/Semaphore_POSIX.cpp#1 $ +// +// Library: Foundation +// Package: Threading +// Module: Semaphore +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/Semaphore_POSIX.h" +#include + + +namespace Poco { + + +SemaphoreImpl::SemaphoreImpl(int n, int max): _n(n), _max(max) +{ + poco_assert (n >= 0 && max > 0 && n <= max); + + if (pthread_mutex_init(&_mutex, NULL)) + throw SystemException("cannot create semaphore (mutex)"); + if (pthread_cond_init(&_cond, NULL)) + throw SystemException("cannot create semaphore (condition)"); +} + + +SemaphoreImpl::~SemaphoreImpl() +{ + pthread_cond_destroy(&_cond); + pthread_mutex_destroy(&_mutex); +} + + +void SemaphoreImpl::waitImpl() +{ + if (pthread_mutex_lock(&_mutex)) + throw SystemException("wait for semaphore failed (lock)"); + while (_n < 1) + { + if (pthread_cond_wait(&_cond, &_mutex)) + { + pthread_mutex_unlock(&_mutex); + throw SystemException("wait for semaphore failed"); + } + } + --_n; + pthread_mutex_unlock(&_mutex); +} + + +bool SemaphoreImpl::waitImpl(long milliseconds) +{ + int rc = 0; + struct timespec abstime; + +#if defined(__VMS) + struct timespec delta; + delta.tv_sec = milliseconds / 1000; + delta.tv_nsec = (milliseconds % 1000)*1000000; + pthread_get_expiration_np(&delta, &abstime); +#else + struct timeval tv; + gettimeofday(&tv, NULL); + abstime.tv_sec = tv.tv_sec + milliseconds / 1000; + abstime.tv_nsec = tv.tv_usec*1000 + (milliseconds % 1000)*1000000; + if (abstime.tv_nsec >= 1000000000) + { + abstime.tv_nsec -= 1000000000; + abstime.tv_sec++; + } +#endif + + if (pthread_mutex_lock(&_mutex) != 0) + throw SystemException("wait for semaphore failed (lock)"); + while (_n < 1) + { + if ((rc = pthread_cond_timedwait(&_cond, &_mutex, &abstime))) + { + if (rc == ETIMEDOUT) break; + pthread_mutex_unlock(&_mutex); + throw SystemException("cannot wait for semaphore"); + } + } + if (rc == 0) --_n; + pthread_mutex_unlock(&_mutex); + return rc == 0; +} + + +} // namespace Poco diff --git a/Foundation/src/Semaphore_WIN32.cpp b/Foundation/src/Semaphore_WIN32.cpp index 8946d5c42..0e1ce4e93 100644 --- a/Foundation/src/Semaphore_WIN32.cpp +++ b/Foundation/src/Semaphore_WIN32.cpp @@ -1,87 +1,87 @@ -// -// Semaphore_WIN32.cpp -// -// $Id: //poco/1.2/Foundation/src/Semaphore_WIN32.cpp#1 $ -// -// Library: Foundation -// Package: Threading -// Module: Semaphore -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/Semaphore_WIN32.h" - - -namespace Poco { - - -SemaphoreImpl::SemaphoreImpl(int n, int max) -{ - poco_assert (n >= 0 && max > 0 && n <= max); - - _sema = CreateSemaphore(NULL, n, max, NULL); - if (!_sema) - { - throw SystemException("cannot create semaphore"); - } -} - - -SemaphoreImpl::~SemaphoreImpl() -{ - CloseHandle(_sema); -} - - -void SemaphoreImpl::waitImpl() -{ - switch (WaitForSingleObject(_sema, INFINITE)) - { - case WAIT_OBJECT_0: - return; - default: - throw SystemException("wait for semaphore failed"); - } -} - - -bool SemaphoreImpl::waitImpl(long milliseconds) -{ - switch (WaitForSingleObject(_sema, milliseconds + 1)) - { - case WAIT_TIMEOUT: - return false; - case WAIT_OBJECT_0: - return true; - default: - throw SystemException("wait for semaphore failed"); - } -} - - -} // namespace Poco +// +// Semaphore_WIN32.cpp +// +// $Id: //poco/1.2/Foundation/src/Semaphore_WIN32.cpp#1 $ +// +// Library: Foundation +// Package: Threading +// Module: Semaphore +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/Semaphore_WIN32.h" + + +namespace Poco { + + +SemaphoreImpl::SemaphoreImpl(int n, int max) +{ + poco_assert (n >= 0 && max > 0 && n <= max); + + _sema = CreateSemaphore(NULL, n, max, NULL); + if (!_sema) + { + throw SystemException("cannot create semaphore"); + } +} + + +SemaphoreImpl::~SemaphoreImpl() +{ + CloseHandle(_sema); +} + + +void SemaphoreImpl::waitImpl() +{ + switch (WaitForSingleObject(_sema, INFINITE)) + { + case WAIT_OBJECT_0: + return; + default: + throw SystemException("wait for semaphore failed"); + } +} + + +bool SemaphoreImpl::waitImpl(long milliseconds) +{ + switch (WaitForSingleObject(_sema, milliseconds + 1)) + { + case WAIT_TIMEOUT: + return false; + case WAIT_OBJECT_0: + return true; + default: + throw SystemException("wait for semaphore failed"); + } +} + + +} // namespace Poco diff --git a/Foundation/src/SharedLibrary.cpp b/Foundation/src/SharedLibrary.cpp index c503539ab..fef27cb65 100644 --- a/Foundation/src/SharedLibrary.cpp +++ b/Foundation/src/SharedLibrary.cpp @@ -1,119 +1,119 @@ -// -// SharedLibrary.cpp -// -// $Id: //poco/1.2/Foundation/src/SharedLibrary.cpp#1 $ -// -// Library: Foundation -// Package: SharedLibrary -// Module: SharedLibrary -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/SharedLibrary.h" -#include "Poco/Exception.h" - - -#if defined(hpux) || defined(_hpux) -#include "SharedLibrary_HPUX.cpp" -#elif defined(POCO_OS_FAMILY_UNIX) -#include "SharedLibrary_UNIX.cpp" -#elif defined(POCO_OS_FAMILY_WINDOWS) && defined(POCO_WIN32_UTF8) -#include "SharedLibrary_WIN32U.cpp" -#elif defined(POCO_OS_FAMILY_WINDOWS) -#include "SharedLibrary_WIN32.cpp" -#elif defined(POCO_OS_FAMILY_VMS) -#include "SharedLibrary_VMS.cpp" -#endif - - -namespace Poco { - - -SharedLibrary::SharedLibrary() -{ -} - - -SharedLibrary::SharedLibrary(const std::string& path) -{ - loadImpl(path); -} - - -SharedLibrary::~SharedLibrary() -{ -} - - -void SharedLibrary::load(const std::string& path) -{ - loadImpl(path); -} - - -void SharedLibrary::unload() -{ - unloadImpl(); -} - - -bool SharedLibrary::isLoaded() const -{ - return isLoadedImpl(); -} - - -bool SharedLibrary::hasSymbol(const std::string& name) -{ - return findSymbolImpl(name) != 0; -} - - -void* SharedLibrary::getSymbol(const std::string& name) -{ - void* result = findSymbolImpl(name); - if (result) - return result; - else - throw NotFoundException(name); -} - - -const std::string& SharedLibrary::getPath() const -{ - return getPathImpl(); -} - - -std::string SharedLibrary::suffix() -{ - return suffixImpl(); -} - - -} // namespace Poco +// +// SharedLibrary.cpp +// +// $Id: //poco/1.2/Foundation/src/SharedLibrary.cpp#1 $ +// +// Library: Foundation +// Package: SharedLibrary +// Module: SharedLibrary +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/SharedLibrary.h" +#include "Poco/Exception.h" + + +#if defined(hpux) || defined(_hpux) +#include "SharedLibrary_HPUX.cpp" +#elif defined(POCO_OS_FAMILY_UNIX) +#include "SharedLibrary_UNIX.cpp" +#elif defined(POCO_OS_FAMILY_WINDOWS) && defined(POCO_WIN32_UTF8) +#include "SharedLibrary_WIN32U.cpp" +#elif defined(POCO_OS_FAMILY_WINDOWS) +#include "SharedLibrary_WIN32.cpp" +#elif defined(POCO_OS_FAMILY_VMS) +#include "SharedLibrary_VMS.cpp" +#endif + + +namespace Poco { + + +SharedLibrary::SharedLibrary() +{ +} + + +SharedLibrary::SharedLibrary(const std::string& path) +{ + loadImpl(path); +} + + +SharedLibrary::~SharedLibrary() +{ +} + + +void SharedLibrary::load(const std::string& path) +{ + loadImpl(path); +} + + +void SharedLibrary::unload() +{ + unloadImpl(); +} + + +bool SharedLibrary::isLoaded() const +{ + return isLoadedImpl(); +} + + +bool SharedLibrary::hasSymbol(const std::string& name) +{ + return findSymbolImpl(name) != 0; +} + + +void* SharedLibrary::getSymbol(const std::string& name) +{ + void* result = findSymbolImpl(name); + if (result) + return result; + else + throw NotFoundException(name); +} + + +const std::string& SharedLibrary::getPath() const +{ + return getPathImpl(); +} + + +std::string SharedLibrary::suffix() +{ + return suffixImpl(); +} + + +} // namespace Poco diff --git a/Foundation/src/SharedLibrary_HPUX.cpp b/Foundation/src/SharedLibrary_HPUX.cpp index 38ab61463..f0eb8e0f5 100644 --- a/Foundation/src/SharedLibrary_HPUX.cpp +++ b/Foundation/src/SharedLibrary_HPUX.cpp @@ -1,116 +1,116 @@ -// -// SharedLibrary_HPUX.cpp -// -// $Id: //poco/1.2/Foundation/src/SharedLibrary_HPUX.cpp#1 $ -// -// Library: Foundation -// Package: SharedLibrary -// Module: SharedLibrary -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/SharedLibrary_HPUX.h" -#include - - -namespace Poco { - - -FastMutex SharedLibraryImpl::_mutex; - - -SharedLibraryImpl::SharedLibraryImpl() -{ - _handle = 0; -} - - -SharedLibraryImpl::~SharedLibraryImpl() -{ -} - - -void SharedLibraryImpl::loadImpl(const std::string& path) -{ - FastMutex::ScopedLock lock(_mutex); - - if (_handle) throw LibraryAlreadyLoadedException(path); - _handle = shl_load(path.c_str(), BIND_DEFERRED, 0); - if (!_handle) throw LibraryLoadException(path); - _path = path; -} - - -void SharedLibraryImpl::unloadImpl() -{ - FastMutex::ScopedLock lock(_mutex); - - if (_handle) - { - shl_unload(_handle); - _handle = 0; - _path.clear(); - } -} - - -bool SharedLibraryImpl::isLoadedImpl() const -{ - return _handle != 0; -} - - -void* SharedLibraryImpl::findSymbolImpl(const std::string& name) -{ - FastMutex::ScopedLock lock(_mutex); - - void* result = 0; - if (_handle && shl_findsym(&_handle, name.c_str(), TYPE_UNDEFINED, &result) != -1) - return result; - else - return 0; -} - - -const std::string& SharedLibraryImpl::getPathImpl() const -{ - return _path; -} - - -std::string SharedLibraryImpl::suffixImpl() -{ -#if defined(_DEBUG) - return "d.sl"; -#else - return ".sl"; -#endif -} - - -} // namespace Poco +// +// SharedLibrary_HPUX.cpp +// +// $Id: //poco/1.2/Foundation/src/SharedLibrary_HPUX.cpp#1 $ +// +// Library: Foundation +// Package: SharedLibrary +// Module: SharedLibrary +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/SharedLibrary_HPUX.h" +#include + + +namespace Poco { + + +FastMutex SharedLibraryImpl::_mutex; + + +SharedLibraryImpl::SharedLibraryImpl() +{ + _handle = 0; +} + + +SharedLibraryImpl::~SharedLibraryImpl() +{ +} + + +void SharedLibraryImpl::loadImpl(const std::string& path) +{ + FastMutex::ScopedLock lock(_mutex); + + if (_handle) throw LibraryAlreadyLoadedException(path); + _handle = shl_load(path.c_str(), BIND_DEFERRED, 0); + if (!_handle) throw LibraryLoadException(path); + _path = path; +} + + +void SharedLibraryImpl::unloadImpl() +{ + FastMutex::ScopedLock lock(_mutex); + + if (_handle) + { + shl_unload(_handle); + _handle = 0; + _path.clear(); + } +} + + +bool SharedLibraryImpl::isLoadedImpl() const +{ + return _handle != 0; +} + + +void* SharedLibraryImpl::findSymbolImpl(const std::string& name) +{ + FastMutex::ScopedLock lock(_mutex); + + void* result = 0; + if (_handle && shl_findsym(&_handle, name.c_str(), TYPE_UNDEFINED, &result) != -1) + return result; + else + return 0; +} + + +const std::string& SharedLibraryImpl::getPathImpl() const +{ + return _path; +} + + +std::string SharedLibraryImpl::suffixImpl() +{ +#if defined(_DEBUG) + return "d.sl"; +#else + return ".sl"; +#endif +} + + +} // namespace Poco diff --git a/Foundation/src/SharedLibrary_UNIX.cpp b/Foundation/src/SharedLibrary_UNIX.cpp index 7c09cc1ec..6d60e13d0 100644 --- a/Foundation/src/SharedLibrary_UNIX.cpp +++ b/Foundation/src/SharedLibrary_UNIX.cpp @@ -1,147 +1,147 @@ -// -// SharedLibrary_UNIX.cpp -// -// $Id: //poco/1.2/Foundation/src/SharedLibrary_UNIX.cpp#1 $ -// -// Library: Foundation -// Package: SharedLibrary -// Module: SharedLibrary -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/SharedLibrary_UNIX.h" -#include "Poco/Exception.h" -#include - - -// Note: cygwin is missing RTLD_LOCAL, set it to 0 -#if defined(__CYGWIN__) && !defined(RTLD_LOCAL) -#define RTLD_LOCAL 0 -#endif - - -namespace Poco { - - -FastMutex SharedLibraryImpl::_mutex; - - -SharedLibraryImpl::SharedLibraryImpl() -{ - _handle = 0; -} - - -SharedLibraryImpl::~SharedLibraryImpl() -{ -} - - -void SharedLibraryImpl::loadImpl(const std::string& path) -{ - FastMutex::ScopedLock lock(_mutex); - - if (_handle) throw LibraryAlreadyLoadedException(path); - _handle = dlopen(path.c_str(), RTLD_LAZY | RTLD_LOCAL); - if (!_handle) - { - const char* err = dlerror(); - throw LibraryLoadException(err ? std::string(err) : path); - } - _path = path; -} - - -void SharedLibraryImpl::unloadImpl() -{ - FastMutex::ScopedLock lock(_mutex); - - if (_handle) - { - dlclose(_handle); - _handle = 0; - } -} - - -bool SharedLibraryImpl::isLoadedImpl() const -{ - return _handle != 0; -} - - -void* SharedLibraryImpl::findSymbolImpl(const std::string& name) -{ - FastMutex::ScopedLock lock(_mutex); - - void* result = 0; - if (_handle) - { - result = dlsym(_handle, name.c_str()); - } - return result; -} - - -const std::string& SharedLibraryImpl::getPathImpl() const -{ - return _path; -} - - -std::string SharedLibraryImpl::suffixImpl() -{ -#if defined(__APPLE__) - #if defined(_DEBUG) - return "d.dylib"; - #else - return ".dylib"; - #endif -#elif defined(hpux) || defined(_hpux) - #if defined(_DEBUG) - return "d.sl"; - #else - return ".sl"; - #endif -#elif defined(__CYGWIN__) - #if defined(_DEBUG) - return "d.dll"; - #else - return ".dll"; - #endif -#else - #if defined(_DEBUG) - return "d.so"; - #else - return ".so"; - #endif -#endif -} - - -} // namespace Poco +// +// SharedLibrary_UNIX.cpp +// +// $Id: //poco/1.2/Foundation/src/SharedLibrary_UNIX.cpp#1 $ +// +// Library: Foundation +// Package: SharedLibrary +// Module: SharedLibrary +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/SharedLibrary_UNIX.h" +#include "Poco/Exception.h" +#include + + +// Note: cygwin is missing RTLD_LOCAL, set it to 0 +#if defined(__CYGWIN__) && !defined(RTLD_LOCAL) +#define RTLD_LOCAL 0 +#endif + + +namespace Poco { + + +FastMutex SharedLibraryImpl::_mutex; + + +SharedLibraryImpl::SharedLibraryImpl() +{ + _handle = 0; +} + + +SharedLibraryImpl::~SharedLibraryImpl() +{ +} + + +void SharedLibraryImpl::loadImpl(const std::string& path) +{ + FastMutex::ScopedLock lock(_mutex); + + if (_handle) throw LibraryAlreadyLoadedException(path); + _handle = dlopen(path.c_str(), RTLD_LAZY | RTLD_LOCAL); + if (!_handle) + { + const char* err = dlerror(); + throw LibraryLoadException(err ? std::string(err) : path); + } + _path = path; +} + + +void SharedLibraryImpl::unloadImpl() +{ + FastMutex::ScopedLock lock(_mutex); + + if (_handle) + { + dlclose(_handle); + _handle = 0; + } +} + + +bool SharedLibraryImpl::isLoadedImpl() const +{ + return _handle != 0; +} + + +void* SharedLibraryImpl::findSymbolImpl(const std::string& name) +{ + FastMutex::ScopedLock lock(_mutex); + + void* result = 0; + if (_handle) + { + result = dlsym(_handle, name.c_str()); + } + return result; +} + + +const std::string& SharedLibraryImpl::getPathImpl() const +{ + return _path; +} + + +std::string SharedLibraryImpl::suffixImpl() +{ +#if defined(__APPLE__) + #if defined(_DEBUG) + return "d.dylib"; + #else + return ".dylib"; + #endif +#elif defined(hpux) || defined(_hpux) + #if defined(_DEBUG) + return "d.sl"; + #else + return ".sl"; + #endif +#elif defined(__CYGWIN__) + #if defined(_DEBUG) + return "d.dll"; + #else + return ".dll"; + #endif +#else + #if defined(_DEBUG) + return "d.so"; + #else + return ".so"; + #endif +#endif +} + + +} // namespace Poco diff --git a/Foundation/src/SharedLibrary_VMS.cpp b/Foundation/src/SharedLibrary_VMS.cpp index 2ac3bcc42..2e001e33c 100644 --- a/Foundation/src/SharedLibrary_VMS.cpp +++ b/Foundation/src/SharedLibrary_VMS.cpp @@ -1,139 +1,139 @@ -// -// SharedLibrary_VMS.cpp -// -// $Id: //poco/1.2/Foundation/src/SharedLibrary_VMS.cpp#1 $ -// -// Library: Foundation -// Package: SharedLibrary -// Module: SharedLibrary -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/SharedLibrary_VMS.h" -#include "Poco/Path.h" -#include -#include -#include -#include -#include - - -namespace Poco { - - -FastMutex SharedLibraryImpl::_mutex; - - -SharedLibraryImpl::SharedLibraryImpl() -{ -} - - -SharedLibraryImpl::~SharedLibraryImpl() -{ -} - - -void SharedLibraryImpl::loadImpl(const std::string& path) -{ - FastMutex::ScopedLock lock(_mutex); - - if (!_path.empty()) throw LibraryAlreadyLoadedException(path); - _path = path; -} - - -void SharedLibraryImpl::unloadImpl() -{ - _path.clear(); -} - - -bool SharedLibraryImpl::isLoadedImpl() const -{ - return !_path.empty(); -} - - -void* SharedLibraryImpl::findSymbolImpl(const std::string& name) -{ - FastMutex::ScopedLock lock(_mutex); - - if (_path.empty()) return NULL; - - Path p(_path); - std::string filename = p.getBaseName(); - std::string ext = p.getExtension(); - std::string imageSpec = p.makeParent().toString(); - if (!imageSpec.empty() && !ext.empty()) - { - imageSpec.append("."); - imageSpec.append(ext); - } - int value = 0; - long flags = LIB$M_FIS_MIXEDCASE; - POCO_DESCRIPTOR_STRING(filenameDsc, filename); - POCO_DESCRIPTOR_STRING(symbolDsc, name); - POCO_DESCRIPTOR_STRING(imageSpecDsc, imageSpec); - - try - { - // lib$find_image_symbol only accepts 32-bit pointers - #pragma pointer_size save - #pragma pointer_size 32 - lib$find_image_symbol(&filenameDsc, &symbolDsc, &value, imageSpec.empty() ? 0 : &imageSpecDsc, flags); - #pragma pointer_size restore - } - catch (struct chf$signal_array& sigarr) - { - unsigned sig = sigarr.chf$is_sig_name; - unsigned act = LIB$_ACTIMAGE; - if (lib$match_cond(&sig, &act)) - throw LibraryLoadException(_path); - } - return (void*) value; -} - - -const std::string& SharedLibraryImpl::getPathImpl() const -{ - return _path; -} - - -std::string SharedLibraryImpl::suffixImpl() -{ -#if defined(_DEBUG) - return "d.exe"; -#else - return ".exe"; -#endif -} - - -} // namespace Poco +// +// SharedLibrary_VMS.cpp +// +// $Id: //poco/1.2/Foundation/src/SharedLibrary_VMS.cpp#1 $ +// +// Library: Foundation +// Package: SharedLibrary +// Module: SharedLibrary +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/SharedLibrary_VMS.h" +#include "Poco/Path.h" +#include +#include +#include +#include +#include + + +namespace Poco { + + +FastMutex SharedLibraryImpl::_mutex; + + +SharedLibraryImpl::SharedLibraryImpl() +{ +} + + +SharedLibraryImpl::~SharedLibraryImpl() +{ +} + + +void SharedLibraryImpl::loadImpl(const std::string& path) +{ + FastMutex::ScopedLock lock(_mutex); + + if (!_path.empty()) throw LibraryAlreadyLoadedException(path); + _path = path; +} + + +void SharedLibraryImpl::unloadImpl() +{ + _path.clear(); +} + + +bool SharedLibraryImpl::isLoadedImpl() const +{ + return !_path.empty(); +} + + +void* SharedLibraryImpl::findSymbolImpl(const std::string& name) +{ + FastMutex::ScopedLock lock(_mutex); + + if (_path.empty()) return NULL; + + Path p(_path); + std::string filename = p.getBaseName(); + std::string ext = p.getExtension(); + std::string imageSpec = p.makeParent().toString(); + if (!imageSpec.empty() && !ext.empty()) + { + imageSpec.append("."); + imageSpec.append(ext); + } + int value = 0; + long flags = LIB$M_FIS_MIXEDCASE; + POCO_DESCRIPTOR_STRING(filenameDsc, filename); + POCO_DESCRIPTOR_STRING(symbolDsc, name); + POCO_DESCRIPTOR_STRING(imageSpecDsc, imageSpec); + + try + { + // lib$find_image_symbol only accepts 32-bit pointers + #pragma pointer_size save + #pragma pointer_size 32 + lib$find_image_symbol(&filenameDsc, &symbolDsc, &value, imageSpec.empty() ? 0 : &imageSpecDsc, flags); + #pragma pointer_size restore + } + catch (struct chf$signal_array& sigarr) + { + unsigned sig = sigarr.chf$is_sig_name; + unsigned act = LIB$_ACTIMAGE; + if (lib$match_cond(&sig, &act)) + throw LibraryLoadException(_path); + } + return (void*) value; +} + + +const std::string& SharedLibraryImpl::getPathImpl() const +{ + return _path; +} + + +std::string SharedLibraryImpl::suffixImpl() +{ +#if defined(_DEBUG) + return "d.exe"; +#else + return ".exe"; +#endif +} + + +} // namespace Poco diff --git a/Foundation/src/SharedLibrary_WIN32.cpp b/Foundation/src/SharedLibrary_WIN32.cpp index 7b9610666..545701f42 100644 --- a/Foundation/src/SharedLibrary_WIN32.cpp +++ b/Foundation/src/SharedLibrary_WIN32.cpp @@ -1,116 +1,116 @@ -// -// SharedLibrary_WIN32.cpp -// -// $Id: //poco/1.2/Foundation/src/SharedLibrary_WIN32.cpp#1 $ -// -// Library: Foundation -// Package: SharedLibrary -// Module: SharedLibrary -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/SharedLibrary_WIN32.h" -#include - - -namespace Poco { - - -FastMutex SharedLibraryImpl::_mutex; - - -SharedLibraryImpl::SharedLibraryImpl() -{ - _handle = 0; -} - - -SharedLibraryImpl::~SharedLibraryImpl() -{ -} - - -void SharedLibraryImpl::loadImpl(const std::string& path) -{ - FastMutex::ScopedLock lock(_mutex); - - if (_handle) throw LibraryAlreadyLoadedException(_path); - _handle = LoadLibrary(path.c_str()); - if (!_handle) throw LibraryLoadException(path); - _path = path; -} - - -void SharedLibraryImpl::unloadImpl() -{ - FastMutex::ScopedLock lock(_mutex); - - if (_handle) - { - FreeLibrary((HMODULE) _handle); - _handle = 0; - } - _path.clear(); -} - - -bool SharedLibraryImpl::isLoadedImpl() const -{ - return _handle != 0; -} - - -void* SharedLibraryImpl::findSymbolImpl(const std::string& name) -{ - FastMutex::ScopedLock lock(_mutex); - - if (_handle) - { - return (void*) GetProcAddress((HMODULE) _handle, name.c_str()); - } - else return 0; -} - - -const std::string& SharedLibraryImpl::getPathImpl() const -{ - return _path; -} - - -std::string SharedLibraryImpl::suffixImpl() -{ -#if defined(_DEBUG) - return "d.dll"; -#else - return ".dll"; -#endif -} - - -} // namespace Poco +// +// SharedLibrary_WIN32.cpp +// +// $Id: //poco/1.2/Foundation/src/SharedLibrary_WIN32.cpp#1 $ +// +// Library: Foundation +// Package: SharedLibrary +// Module: SharedLibrary +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/SharedLibrary_WIN32.h" +#include + + +namespace Poco { + + +FastMutex SharedLibraryImpl::_mutex; + + +SharedLibraryImpl::SharedLibraryImpl() +{ + _handle = 0; +} + + +SharedLibraryImpl::~SharedLibraryImpl() +{ +} + + +void SharedLibraryImpl::loadImpl(const std::string& path) +{ + FastMutex::ScopedLock lock(_mutex); + + if (_handle) throw LibraryAlreadyLoadedException(_path); + _handle = LoadLibrary(path.c_str()); + if (!_handle) throw LibraryLoadException(path); + _path = path; +} + + +void SharedLibraryImpl::unloadImpl() +{ + FastMutex::ScopedLock lock(_mutex); + + if (_handle) + { + FreeLibrary((HMODULE) _handle); + _handle = 0; + } + _path.clear(); +} + + +bool SharedLibraryImpl::isLoadedImpl() const +{ + return _handle != 0; +} + + +void* SharedLibraryImpl::findSymbolImpl(const std::string& name) +{ + FastMutex::ScopedLock lock(_mutex); + + if (_handle) + { + return (void*) GetProcAddress((HMODULE) _handle, name.c_str()); + } + else return 0; +} + + +const std::string& SharedLibraryImpl::getPathImpl() const +{ + return _path; +} + + +std::string SharedLibraryImpl::suffixImpl() +{ +#if defined(_DEBUG) + return "d.dll"; +#else + return ".dll"; +#endif +} + + +} // namespace Poco diff --git a/Foundation/src/SharedLibrary_WIN32U.cpp b/Foundation/src/SharedLibrary_WIN32U.cpp index aae9e8308..6c68edd1a 100644 --- a/Foundation/src/SharedLibrary_WIN32U.cpp +++ b/Foundation/src/SharedLibrary_WIN32U.cpp @@ -1,119 +1,119 @@ -// -// SharedLibrary_WIN32U.cpp -// -// $Id: //poco/1.2/Foundation/src/SharedLibrary_WIN32U.cpp#1 $ -// -// Library: Foundation -// Package: SharedLibrary -// Module: SharedLibrary -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/SharedLibrary_WIN32U.h" -#include "Poco/UnicodeConverter.h" -#include - - -namespace Poco { - - -FastMutex SharedLibraryImpl::_mutex; - - -SharedLibraryImpl::SharedLibraryImpl() -{ - _handle = 0; -} - - -SharedLibraryImpl::~SharedLibraryImpl() -{ -} - - -void SharedLibraryImpl::loadImpl(const std::string& path) -{ - FastMutex::ScopedLock lock(_mutex); - - if (_handle) throw LibraryAlreadyLoadedException(_path); - std::wstring upath; - UnicodeConverter::toUTF16(path, upath); - _handle = LoadLibraryW(upath.c_str()); - if (!_handle) throw LibraryLoadException(path); - _path = path; -} - - -void SharedLibraryImpl::unloadImpl() -{ - FastMutex::ScopedLock lock(_mutex); - - if (_handle) - { - FreeLibrary((HMODULE) _handle); - _handle = 0; - } - _path.clear(); -} - - -bool SharedLibraryImpl::isLoadedImpl() const -{ - return _handle != 0; -} - - -void* SharedLibraryImpl::findSymbolImpl(const std::string& name) -{ - FastMutex::ScopedLock lock(_mutex); - - if (_handle) - { - return (void*) GetProcAddress((HMODULE) _handle, name.c_str()); - } - else return 0; -} - - -const std::string& SharedLibraryImpl::getPathImpl() const -{ - return _path; -} - - -std::string SharedLibraryImpl::suffixImpl() -{ -#if defined(_DEBUG) - return "d.dll"; -#else - return ".dll"; -#endif -} - - -} // namespace Poco +// +// SharedLibrary_WIN32U.cpp +// +// $Id: //poco/1.2/Foundation/src/SharedLibrary_WIN32U.cpp#1 $ +// +// Library: Foundation +// Package: SharedLibrary +// Module: SharedLibrary +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/SharedLibrary_WIN32U.h" +#include "Poco/UnicodeConverter.h" +#include + + +namespace Poco { + + +FastMutex SharedLibraryImpl::_mutex; + + +SharedLibraryImpl::SharedLibraryImpl() +{ + _handle = 0; +} + + +SharedLibraryImpl::~SharedLibraryImpl() +{ +} + + +void SharedLibraryImpl::loadImpl(const std::string& path) +{ + FastMutex::ScopedLock lock(_mutex); + + if (_handle) throw LibraryAlreadyLoadedException(_path); + std::wstring upath; + UnicodeConverter::toUTF16(path, upath); + _handle = LoadLibraryW(upath.c_str()); + if (!_handle) throw LibraryLoadException(path); + _path = path; +} + + +void SharedLibraryImpl::unloadImpl() +{ + FastMutex::ScopedLock lock(_mutex); + + if (_handle) + { + FreeLibrary((HMODULE) _handle); + _handle = 0; + } + _path.clear(); +} + + +bool SharedLibraryImpl::isLoadedImpl() const +{ + return _handle != 0; +} + + +void* SharedLibraryImpl::findSymbolImpl(const std::string& name) +{ + FastMutex::ScopedLock lock(_mutex); + + if (_handle) + { + return (void*) GetProcAddress((HMODULE) _handle, name.c_str()); + } + else return 0; +} + + +const std::string& SharedLibraryImpl::getPathImpl() const +{ + return _path; +} + + +std::string SharedLibraryImpl::suffixImpl() +{ +#if defined(_DEBUG) + return "d.dll"; +#else + return ".dll"; +#endif +} + + +} // namespace Poco diff --git a/Foundation/src/SignalHandler.cpp b/Foundation/src/SignalHandler.cpp index e4a9cdafc..641ad7d18 100644 --- a/Foundation/src/SignalHandler.cpp +++ b/Foundation/src/SignalHandler.cpp @@ -1,127 +1,127 @@ -// -// SignalHandler.cpp -// -// $Id: //poco/1.2/Foundation/src/SignalHandler.cpp#1 $ -// -// Library: Foundation -// Package: Threading -// Module: SignalHandler -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/SignalHandler.h" - - -#if defined(POCO_OS_FAMILY_UNIX) - - -#include "Poco/Thread.h" -#include "Poco/NumberFormatter.h" -#include "Poco/Exception.h" -#include - - -namespace Poco { - - -SignalHandler::JumpBufferVec SignalHandler::_jumpBufferVec; - - -SignalHandler::SignalHandler() -{ - JumpBufferVec& jbv = jumpBufferVec(); - JumpBuffer buf; - jbv.push_back(buf); -} - - -SignalHandler::~SignalHandler() -{ - jumpBufferVec().pop_back(); -} - - -sigjmp_buf& SignalHandler::jumpBuffer() -{ - return jumpBufferVec().back().buf; -} - - -void SignalHandler::throwSignalException(int sig) -{ - switch (sig) - { - case SIGILL: - throw SignalException("Illegal instruction"); - case SIGBUS: - throw SignalException("Bus error"); - case SIGSEGV: - throw SignalException("Segmentation violation"); - case SIGSYS: - throw SignalException("Invalid system call"); - default: - throw SignalException(NumberFormatter::formatHex(sig)); - } -} - - -void SignalHandler::install() -{ - struct sigaction sa; - sa.sa_handler = handleSignal; - sa.sa_flags = 0; - sigemptyset(&sa.sa_mask); - sigaction(SIGILL, &sa, 0); - sigaction(SIGBUS, &sa, 0); - sigaction(SIGSEGV, &sa, 0); - sigaction(SIGSYS, &sa, 0); -} - - -void SignalHandler::handleSignal(int sig) -{ - JumpBufferVec& jb = jumpBufferVec(); - if (!jb.empty()) - siglongjmp(jb.back().buf, sig); -} - - -SignalHandler::JumpBufferVec& SignalHandler::jumpBufferVec() -{ - ThreadImpl* pThread = ThreadImpl::currentImpl(); - if (pThread) - return pThread->_jumpBufferVec; - else - return _jumpBufferVec; -} - - -} // namespace Poco - - -#endif // POCO_OS_FAMILY_UNIX +// +// SignalHandler.cpp +// +// $Id: //poco/1.2/Foundation/src/SignalHandler.cpp#1 $ +// +// Library: Foundation +// Package: Threading +// Module: SignalHandler +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/SignalHandler.h" + + +#if defined(POCO_OS_FAMILY_UNIX) + + +#include "Poco/Thread.h" +#include "Poco/NumberFormatter.h" +#include "Poco/Exception.h" +#include + + +namespace Poco { + + +SignalHandler::JumpBufferVec SignalHandler::_jumpBufferVec; + + +SignalHandler::SignalHandler() +{ + JumpBufferVec& jbv = jumpBufferVec(); + JumpBuffer buf; + jbv.push_back(buf); +} + + +SignalHandler::~SignalHandler() +{ + jumpBufferVec().pop_back(); +} + + +sigjmp_buf& SignalHandler::jumpBuffer() +{ + return jumpBufferVec().back().buf; +} + + +void SignalHandler::throwSignalException(int sig) +{ + switch (sig) + { + case SIGILL: + throw SignalException("Illegal instruction"); + case SIGBUS: + throw SignalException("Bus error"); + case SIGSEGV: + throw SignalException("Segmentation violation"); + case SIGSYS: + throw SignalException("Invalid system call"); + default: + throw SignalException(NumberFormatter::formatHex(sig)); + } +} + + +void SignalHandler::install() +{ + struct sigaction sa; + sa.sa_handler = handleSignal; + sa.sa_flags = 0; + sigemptyset(&sa.sa_mask); + sigaction(SIGILL, &sa, 0); + sigaction(SIGBUS, &sa, 0); + sigaction(SIGSEGV, &sa, 0); + sigaction(SIGSYS, &sa, 0); +} + + +void SignalHandler::handleSignal(int sig) +{ + JumpBufferVec& jb = jumpBufferVec(); + if (!jb.empty()) + siglongjmp(jb.back().buf, sig); +} + + +SignalHandler::JumpBufferVec& SignalHandler::jumpBufferVec() +{ + ThreadImpl* pThread = ThreadImpl::currentImpl(); + if (pThread) + return pThread->_jumpBufferVec; + else + return _jumpBufferVec; +} + + +} // namespace Poco + + +#endif // POCO_OS_FAMILY_UNIX diff --git a/Foundation/src/SimpleFileChannel.cpp b/Foundation/src/SimpleFileChannel.cpp index e26a61f27..e668b98be 100644 --- a/Foundation/src/SimpleFileChannel.cpp +++ b/Foundation/src/SimpleFileChannel.cpp @@ -1,228 +1,228 @@ -// -// SimpleFileChannel.cpp -// -// $Id: //poco/1.2/Foundation/src/SimpleFileChannel.cpp#1 $ -// -// Library: Foundation -// Package: Logging -// Module: SimpleFileChannel -// -// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/SimpleFileChannel.h" -#include "Poco/LogFile.h" -#include "Poco/File.h" -#include "Poco/Message.h" -#include "Poco/Exception.h" -#include - - -namespace Poco { - - -const std::string SimpleFileChannel::PROP_PATH = "path"; -const std::string SimpleFileChannel::PROP_SECONDARYPATH = "secondaryPath"; -const std::string SimpleFileChannel::PROP_ROTATION = "rotation"; - - -SimpleFileChannel::SimpleFileChannel(): - _limit(0), - _pFile(0) -{ -} - - -SimpleFileChannel::SimpleFileChannel(const std::string& path): - _path(path), - _secondaryPath(path + ".0"), - _limit(0), - _pFile(0) -{ -} - - -SimpleFileChannel::~SimpleFileChannel() -{ - close(); -} - - -void SimpleFileChannel::open() -{ - FastMutex::ScopedLock lock(_mutex); - - if (!_pFile) - { - File primary(_path); - File secondary(_secondaryPath); - Timestamp pt = primary.exists() ? primary.getLastModified() : 0; - Timestamp st = secondary.exists() ? secondary.getLastModified() : 0; - std::string path; - if (pt >= st) - path = _path; - else - path = _secondaryPath; - _pFile = new LogFile(path); - } -} - - -void SimpleFileChannel::close() -{ - FastMutex::ScopedLock lock(_mutex); - - delete _pFile; - _pFile = 0; -} - - -void SimpleFileChannel::log(const Message& msg) -{ - open(); - - FastMutex::ScopedLock lock(_mutex); - - if (_limit > 0 && _pFile->size() >= _limit) - { - rotate(); - } - _pFile->write(msg.getText()); -} - - -void SimpleFileChannel::setProperty(const std::string& name, const std::string& value) -{ - FastMutex::ScopedLock lock(_mutex); - - if (name == PROP_PATH) - { - _path = value; - if (_secondaryPath.empty()) - _secondaryPath = _path + ".0"; - } - else if (name == PROP_SECONDARYPATH) - _secondaryPath = value; - else if (name == PROP_ROTATION) - setRotation(value); - else - Channel::setProperty(name, value); -} - - -std::string SimpleFileChannel::getProperty(const std::string& name) const -{ - if (name == PROP_PATH) - return _path; - else if (name == PROP_SECONDARYPATH) - return _secondaryPath; - else if (name == PROP_ROTATION) - return _rotation; - else - return Channel::getProperty(name); -} - - -Timestamp SimpleFileChannel::creationDate() const -{ - if (_pFile) - return _pFile->creationDate(); - else - return 0; -} - - -UInt64 SimpleFileChannel::size() const -{ - if (_pFile) - return _pFile->size(); - else - return 0; -} - - -const std::string& SimpleFileChannel::path() const -{ - return _path; -} - - -const std::string& SimpleFileChannel::secondaryPath() const -{ - return _secondaryPath; -} - - -void SimpleFileChannel::setRotation(const std::string& rotation) -{ - std::string::const_iterator it = rotation.begin(); - std::string::const_iterator end = rotation.end(); - UInt64 n = 0; - while (it != end && isspace(*it)) ++it; - while (it != end && isdigit(*it)) { n *= 10; n += *it++ - '0'; } - while (it != end && isspace(*it)) ++it; - std::string unit; - while (it != end && isalpha(*it)) unit += *it++; - - if (unit == "K") - _limit = n*1024; - else if (unit == "M") - _limit = n*1024*1024; - else if (unit.empty()) - _limit = n; - else if (unit == "never") - _limit = 0; - else - throw InvalidArgumentException("rotation", rotation); - _rotation = rotation; -} - - -void SimpleFileChannel::rotate() -{ - std::string newPath; - if (_pFile->path() == _path) - newPath = _secondaryPath; - else - newPath = _path; - File f(newPath); - if (f.exists()) - { - try - { - f.remove(); - } - catch (...) - { - } - } - delete _pFile; - _pFile = new LogFile(newPath); -} - - -} // namespace Poco +// +// SimpleFileChannel.cpp +// +// $Id: //poco/1.2/Foundation/src/SimpleFileChannel.cpp#1 $ +// +// Library: Foundation +// Package: Logging +// Module: SimpleFileChannel +// +// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/SimpleFileChannel.h" +#include "Poco/LogFile.h" +#include "Poco/File.h" +#include "Poco/Message.h" +#include "Poco/Exception.h" +#include + + +namespace Poco { + + +const std::string SimpleFileChannel::PROP_PATH = "path"; +const std::string SimpleFileChannel::PROP_SECONDARYPATH = "secondaryPath"; +const std::string SimpleFileChannel::PROP_ROTATION = "rotation"; + + +SimpleFileChannel::SimpleFileChannel(): + _limit(0), + _pFile(0) +{ +} + + +SimpleFileChannel::SimpleFileChannel(const std::string& path): + _path(path), + _secondaryPath(path + ".0"), + _limit(0), + _pFile(0) +{ +} + + +SimpleFileChannel::~SimpleFileChannel() +{ + close(); +} + + +void SimpleFileChannel::open() +{ + FastMutex::ScopedLock lock(_mutex); + + if (!_pFile) + { + File primary(_path); + File secondary(_secondaryPath); + Timestamp pt = primary.exists() ? primary.getLastModified() : 0; + Timestamp st = secondary.exists() ? secondary.getLastModified() : 0; + std::string path; + if (pt >= st) + path = _path; + else + path = _secondaryPath; + _pFile = new LogFile(path); + } +} + + +void SimpleFileChannel::close() +{ + FastMutex::ScopedLock lock(_mutex); + + delete _pFile; + _pFile = 0; +} + + +void SimpleFileChannel::log(const Message& msg) +{ + open(); + + FastMutex::ScopedLock lock(_mutex); + + if (_limit > 0 && _pFile->size() >= _limit) + { + rotate(); + } + _pFile->write(msg.getText()); +} + + +void SimpleFileChannel::setProperty(const std::string& name, const std::string& value) +{ + FastMutex::ScopedLock lock(_mutex); + + if (name == PROP_PATH) + { + _path = value; + if (_secondaryPath.empty()) + _secondaryPath = _path + ".0"; + } + else if (name == PROP_SECONDARYPATH) + _secondaryPath = value; + else if (name == PROP_ROTATION) + setRotation(value); + else + Channel::setProperty(name, value); +} + + +std::string SimpleFileChannel::getProperty(const std::string& name) const +{ + if (name == PROP_PATH) + return _path; + else if (name == PROP_SECONDARYPATH) + return _secondaryPath; + else if (name == PROP_ROTATION) + return _rotation; + else + return Channel::getProperty(name); +} + + +Timestamp SimpleFileChannel::creationDate() const +{ + if (_pFile) + return _pFile->creationDate(); + else + return 0; +} + + +UInt64 SimpleFileChannel::size() const +{ + if (_pFile) + return _pFile->size(); + else + return 0; +} + + +const std::string& SimpleFileChannel::path() const +{ + return _path; +} + + +const std::string& SimpleFileChannel::secondaryPath() const +{ + return _secondaryPath; +} + + +void SimpleFileChannel::setRotation(const std::string& rotation) +{ + std::string::const_iterator it = rotation.begin(); + std::string::const_iterator end = rotation.end(); + UInt64 n = 0; + while (it != end && isspace(*it)) ++it; + while (it != end && isdigit(*it)) { n *= 10; n += *it++ - '0'; } + while (it != end && isspace(*it)) ++it; + std::string unit; + while (it != end && isalpha(*it)) unit += *it++; + + if (unit == "K") + _limit = n*1024; + else if (unit == "M") + _limit = n*1024*1024; + else if (unit.empty()) + _limit = n; + else if (unit == "never") + _limit = 0; + else + throw InvalidArgumentException("rotation", rotation); + _rotation = rotation; +} + + +void SimpleFileChannel::rotate() +{ + std::string newPath; + if (_pFile->path() == _path) + newPath = _secondaryPath; + else + newPath = _path; + File f(newPath); + if (f.exists()) + { + try + { + f.remove(); + } + catch (...) + { + } + } + delete _pFile; + _pFile = new LogFile(newPath); +} + + +} // namespace Poco diff --git a/Foundation/src/SplitterChannel.cpp b/Foundation/src/SplitterChannel.cpp index e04804f3e..8d1292c87 100644 --- a/Foundation/src/SplitterChannel.cpp +++ b/Foundation/src/SplitterChannel.cpp @@ -1,128 +1,128 @@ -// -// SplitterChannel.cpp -// -// $Id: //poco/1.2/Foundation/src/SplitterChannel.cpp#2 $ -// -// Library: Foundation -// Package: Logging -// Module: SplitterChannel -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/SplitterChannel.h" -#include "Poco/LoggingRegistry.h" -#include "Poco/StringTokenizer.h" - - -namespace Poco { - - -SplitterChannel::SplitterChannel() -{ -} - - -SplitterChannel::~SplitterChannel() -{ - close(); -} - - -void SplitterChannel::addChannel(Channel* pChannel) -{ - poco_check_ptr (pChannel); - - FastMutex::ScopedLock lock(_mutex); - - pChannel->duplicate(); - _channels.push_back(pChannel); -} - - -void SplitterChannel::removeChannel(Channel* pChannel) -{ - FastMutex::ScopedLock lock(_mutex); - - for (ChannelVec::iterator it = _channels.begin(); it != _channels.end(); ++it) - { - if (*it == pChannel) - { - pChannel->release(); - _channels.erase(it); - break; - } - } -} - - -void SplitterChannel::setProperty(const std::string& name, const std::string& value) -{ - if (name.compare(0, 7, "channel") == 0) - { - StringTokenizer tokenizer(value, ",;", StringTokenizer::TOK_IGNORE_EMPTY | StringTokenizer::TOK_TRIM); - for (StringTokenizer::Iterator it = tokenizer.begin(); it != tokenizer.end(); ++it) - { - addChannel(LoggingRegistry::defaultRegistry().channelForName(*it)); - } - } - else Channel::setProperty(name, value); -} - - -void SplitterChannel::log(const Message& msg) -{ - FastMutex::ScopedLock lock(_mutex); - - for (ChannelVec::iterator it = _channels.begin(); it != _channels.end(); ++it) - { - (*it)->log(msg); - } -} - - -void SplitterChannel::close() -{ - FastMutex::ScopedLock lock(_mutex); - - for (ChannelVec::iterator it = _channels.begin(); it != _channels.end(); ++it) - { - (*it)->release(); - } - _channels.clear(); -} - - -int SplitterChannel::count() const -{ - FastMutex::ScopedLock lock(_mutex); - - return (int) _channels.size(); -} - - -} // namespace Poco +// +// SplitterChannel.cpp +// +// $Id: //poco/1.2/Foundation/src/SplitterChannel.cpp#2 $ +// +// Library: Foundation +// Package: Logging +// Module: SplitterChannel +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/SplitterChannel.h" +#include "Poco/LoggingRegistry.h" +#include "Poco/StringTokenizer.h" + + +namespace Poco { + + +SplitterChannel::SplitterChannel() +{ +} + + +SplitterChannel::~SplitterChannel() +{ + close(); +} + + +void SplitterChannel::addChannel(Channel* pChannel) +{ + poco_check_ptr (pChannel); + + FastMutex::ScopedLock lock(_mutex); + + pChannel->duplicate(); + _channels.push_back(pChannel); +} + + +void SplitterChannel::removeChannel(Channel* pChannel) +{ + FastMutex::ScopedLock lock(_mutex); + + for (ChannelVec::iterator it = _channels.begin(); it != _channels.end(); ++it) + { + if (*it == pChannel) + { + pChannel->release(); + _channels.erase(it); + break; + } + } +} + + +void SplitterChannel::setProperty(const std::string& name, const std::string& value) +{ + if (name.compare(0, 7, "channel") == 0) + { + StringTokenizer tokenizer(value, ",;", StringTokenizer::TOK_IGNORE_EMPTY | StringTokenizer::TOK_TRIM); + for (StringTokenizer::Iterator it = tokenizer.begin(); it != tokenizer.end(); ++it) + { + addChannel(LoggingRegistry::defaultRegistry().channelForName(*it)); + } + } + else Channel::setProperty(name, value); +} + + +void SplitterChannel::log(const Message& msg) +{ + FastMutex::ScopedLock lock(_mutex); + + for (ChannelVec::iterator it = _channels.begin(); it != _channels.end(); ++it) + { + (*it)->log(msg); + } +} + + +void SplitterChannel::close() +{ + FastMutex::ScopedLock lock(_mutex); + + for (ChannelVec::iterator it = _channels.begin(); it != _channels.end(); ++it) + { + (*it)->release(); + } + _channels.clear(); +} + + +int SplitterChannel::count() const +{ + FastMutex::ScopedLock lock(_mutex); + + return (int) _channels.size(); +} + + +} // namespace Poco diff --git a/Foundation/src/Stopwatch.cpp b/Foundation/src/Stopwatch.cpp index b352d555d..35374db4f 100644 --- a/Foundation/src/Stopwatch.cpp +++ b/Foundation/src/Stopwatch.cpp @@ -1,82 +1,82 @@ -// -// Stopwatch.cpp -// -// $Id: //poco/1.2/Foundation/src/Stopwatch.cpp#1 $ -// -// Library: Foundation -// Package: DateTime -// Module: Stopwatch -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/Stopwatch.h" - - -namespace Poco { - - -Stopwatch::Stopwatch(): _elapsed(0), _running(false) -{ -} - - -Stopwatch::~Stopwatch() -{ -} - - -Timestamp::TimeDiff Stopwatch::elapsed() const -{ - if (_running) - { - Timestamp current; - return _elapsed + (current - _start); - } - else - { - return _elapsed; - } -} - - -void Stopwatch::reset() -{ - _elapsed = 0; - _running = false; -} - - -void Stopwatch::restart() -{ - _elapsed = 0; - _start.update(); - _running = true; -} - - -} // namespace Poco +// +// Stopwatch.cpp +// +// $Id: //poco/1.2/Foundation/src/Stopwatch.cpp#1 $ +// +// Library: Foundation +// Package: DateTime +// Module: Stopwatch +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/Stopwatch.h" + + +namespace Poco { + + +Stopwatch::Stopwatch(): _elapsed(0), _running(false) +{ +} + + +Stopwatch::~Stopwatch() +{ +} + + +Timestamp::TimeDiff Stopwatch::elapsed() const +{ + if (_running) + { + Timestamp current; + return _elapsed + (current - _start); + } + else + { + return _elapsed; + } +} + + +void Stopwatch::reset() +{ + _elapsed = 0; + _running = false; +} + + +void Stopwatch::restart() +{ + _elapsed = 0; + _start.update(); + _running = true; +} + + +} // namespace Poco diff --git a/Foundation/src/StreamChannel.cpp b/Foundation/src/StreamChannel.cpp index 3f61e6fe7..678809cff 100644 --- a/Foundation/src/StreamChannel.cpp +++ b/Foundation/src/StreamChannel.cpp @@ -1,62 +1,62 @@ -// -// StreamChannel.cpp -// -// $Id: //poco/1.2/Foundation/src/StreamChannel.cpp#1 $ -// -// Library: Foundation -// Package: Logging -// Module: StreamChannel -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/StreamChannel.h" -#include "Poco/Message.h" - - -namespace Poco { - - -StreamChannel::StreamChannel(std::ostream& str): _str(str) -{ -} - - -StreamChannel::~StreamChannel() -{ -} - - -void StreamChannel::log(const Message& msg) -{ - FastMutex::ScopedLock lock(_mutex); - - _str << msg.getText() << std::endl; -} - - -} // namespace Poco +// +// StreamChannel.cpp +// +// $Id: //poco/1.2/Foundation/src/StreamChannel.cpp#1 $ +// +// Library: Foundation +// Package: Logging +// Module: StreamChannel +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/StreamChannel.h" +#include "Poco/Message.h" + + +namespace Poco { + + +StreamChannel::StreamChannel(std::ostream& str): _str(str) +{ +} + + +StreamChannel::~StreamChannel() +{ +} + + +void StreamChannel::log(const Message& msg) +{ + FastMutex::ScopedLock lock(_mutex); + + _str << msg.getText() << std::endl; +} + + +} // namespace Poco diff --git a/Foundation/src/StreamConverter.cpp b/Foundation/src/StreamConverter.cpp index c35378bde..bbe8f4905 100644 --- a/Foundation/src/StreamConverter.cpp +++ b/Foundation/src/StreamConverter.cpp @@ -1,219 +1,219 @@ -// -// StreamConverter.cpp -// -// $Id: //poco/1.2/Foundation/src/StreamConverter.cpp#1 $ -// -// Library: Foundation -// Package: Text -// Module: StreamConverter -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/StreamConverter.h" -#include "Poco/TextEncoding.h" - - -namespace Poco { - - -StreamConverterBuf::StreamConverterBuf(std::istream& istr, const TextEncoding& inEncoding, const TextEncoding& outEncoding, int defaultChar): - _pIstr(&istr), - _pOstr(0), - _inEncoding(inEncoding), - _outEncoding(outEncoding), - _defaultChar(defaultChar), - _sequenceLength(0), - _pos(0), - _errors(0) -{ -} - - -StreamConverterBuf::StreamConverterBuf(std::ostream& ostr, const TextEncoding& inEncoding, const TextEncoding& outEncoding, int defaultChar): - _pIstr(0), - _pOstr(&ostr), - _inEncoding(inEncoding), - _outEncoding(outEncoding), - _defaultChar(defaultChar), - _sequenceLength(0), - _pos(0), - _errors(0) -{ -} - - -StreamConverterBuf::~StreamConverterBuf() -{ -} - - -int StreamConverterBuf::readFromDevice() -{ - poco_assert_dbg (_pIstr); - - if (_pos < _sequenceLength) return _buffer[_pos++]; - - _pos = 0; - _sequenceLength = 0; - int c = _pIstr->get(); - if (c == -1) return -1; - - poco_assert (c < 256); - int uc; - int n = _inEncoding.characterMap()[c]; - if (n == -1) - { - uc = _defaultChar; - ++_errors; - } - else if (n >= 0) - uc = n; - else - { - poco_assert_dbg(-n <= sizeof(_buffer)); - _buffer[0] = (unsigned char) c; - _pIstr->read((char*) _buffer + 1, -n - 1); - if (_pIstr->gcount() == -n - 1) - { - uc = _inEncoding.convert(_buffer); - if (uc == -1) uc = _defaultChar; - } - else - { - uc = _defaultChar; - ++_errors; - } - } - _sequenceLength = _outEncoding.convert(uc, _buffer, sizeof(_buffer)); - if (_sequenceLength == 0) - _sequenceLength = _outEncoding.convert(_defaultChar, _buffer, sizeof(_buffer)); - if (_sequenceLength == 0) - return -1; - else - return _buffer[_pos++]; -} - - -int StreamConverterBuf::writeToDevice(char c) -{ - poco_assert_dbg (_pOstr); - - if (_sequenceLength == 0) - { - int n = _inEncoding.characterMap()[(unsigned char) c]; - if (n == -1) - { - ++_errors; - return -1; - } - _buffer[0] = (unsigned char) c; - _sequenceLength = n < 0 ? -n : 1; - _pos = 1; - } - else _buffer[_pos++] = (unsigned char) c; - if (_pos == _sequenceLength) - { - int uc = _inEncoding.convert(_buffer); - if (uc == -1) - { - ++_errors; - return -1; - } - int n = _outEncoding.convert(uc, _buffer, sizeof(_buffer)); - if (n == 0) n = _outEncoding.convert(_defaultChar, _buffer, sizeof(_buffer)); - poco_assert_dbg (n <= sizeof(_buffer)); - _pOstr->write((char*) _buffer, n); - _sequenceLength = 0; - _pos = 0; - } - return charToInt(c); -} - - -int StreamConverterBuf::errors() const -{ - return _errors; -} - - -StreamConverterIOS::StreamConverterIOS(std::istream& istr, const TextEncoding& inEncoding, const TextEncoding& outEncoding, int defaultChar): - _buf(istr, inEncoding, outEncoding, defaultChar) -{ - poco_ios_init(&_buf); -} - - -StreamConverterIOS::StreamConverterIOS(std::ostream& ostr, const TextEncoding& inEncoding, const TextEncoding& outEncoding, int defaultChar): - _buf(ostr, inEncoding, outEncoding, defaultChar) -{ - poco_ios_init(&_buf); -} - - -StreamConverterIOS::~StreamConverterIOS() -{ -} - - -StreamConverterBuf* StreamConverterIOS::rdbuf() -{ - return &_buf; -} - - -int StreamConverterIOS::errors() const -{ - return _buf.errors(); -} - - -InputStreamConverter::InputStreamConverter(std::istream& istr, const TextEncoding& inEncoding, const TextEncoding& outEncoding, int defaultChar): - StreamConverterIOS(istr, inEncoding, outEncoding, defaultChar), - std::istream(&_buf) -{ -} - - -InputStreamConverter::~InputStreamConverter() -{ -} - - -OutputStreamConverter::OutputStreamConverter(std::ostream& ostr, const TextEncoding& inEncoding, const TextEncoding& outEncoding, int defaultChar): - StreamConverterIOS(ostr, inEncoding, outEncoding, defaultChar), - std::ostream(&_buf) -{ -} - - -OutputStreamConverter::~OutputStreamConverter() -{ -} - - -} // namespace Poco +// +// StreamConverter.cpp +// +// $Id: //poco/1.2/Foundation/src/StreamConverter.cpp#1 $ +// +// Library: Foundation +// Package: Text +// Module: StreamConverter +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/StreamConverter.h" +#include "Poco/TextEncoding.h" + + +namespace Poco { + + +StreamConverterBuf::StreamConverterBuf(std::istream& istr, const TextEncoding& inEncoding, const TextEncoding& outEncoding, int defaultChar): + _pIstr(&istr), + _pOstr(0), + _inEncoding(inEncoding), + _outEncoding(outEncoding), + _defaultChar(defaultChar), + _sequenceLength(0), + _pos(0), + _errors(0) +{ +} + + +StreamConverterBuf::StreamConverterBuf(std::ostream& ostr, const TextEncoding& inEncoding, const TextEncoding& outEncoding, int defaultChar): + _pIstr(0), + _pOstr(&ostr), + _inEncoding(inEncoding), + _outEncoding(outEncoding), + _defaultChar(defaultChar), + _sequenceLength(0), + _pos(0), + _errors(0) +{ +} + + +StreamConverterBuf::~StreamConverterBuf() +{ +} + + +int StreamConverterBuf::readFromDevice() +{ + poco_assert_dbg (_pIstr); + + if (_pos < _sequenceLength) return _buffer[_pos++]; + + _pos = 0; + _sequenceLength = 0; + int c = _pIstr->get(); + if (c == -1) return -1; + + poco_assert (c < 256); + int uc; + int n = _inEncoding.characterMap()[c]; + if (n == -1) + { + uc = _defaultChar; + ++_errors; + } + else if (n >= 0) + uc = n; + else + { + poco_assert_dbg(-n <= sizeof(_buffer)); + _buffer[0] = (unsigned char) c; + _pIstr->read((char*) _buffer + 1, -n - 1); + if (_pIstr->gcount() == -n - 1) + { + uc = _inEncoding.convert(_buffer); + if (uc == -1) uc = _defaultChar; + } + else + { + uc = _defaultChar; + ++_errors; + } + } + _sequenceLength = _outEncoding.convert(uc, _buffer, sizeof(_buffer)); + if (_sequenceLength == 0) + _sequenceLength = _outEncoding.convert(_defaultChar, _buffer, sizeof(_buffer)); + if (_sequenceLength == 0) + return -1; + else + return _buffer[_pos++]; +} + + +int StreamConverterBuf::writeToDevice(char c) +{ + poco_assert_dbg (_pOstr); + + if (_sequenceLength == 0) + { + int n = _inEncoding.characterMap()[(unsigned char) c]; + if (n == -1) + { + ++_errors; + return -1; + } + _buffer[0] = (unsigned char) c; + _sequenceLength = n < 0 ? -n : 1; + _pos = 1; + } + else _buffer[_pos++] = (unsigned char) c; + if (_pos == _sequenceLength) + { + int uc = _inEncoding.convert(_buffer); + if (uc == -1) + { + ++_errors; + return -1; + } + int n = _outEncoding.convert(uc, _buffer, sizeof(_buffer)); + if (n == 0) n = _outEncoding.convert(_defaultChar, _buffer, sizeof(_buffer)); + poco_assert_dbg (n <= sizeof(_buffer)); + _pOstr->write((char*) _buffer, n); + _sequenceLength = 0; + _pos = 0; + } + return charToInt(c); +} + + +int StreamConverterBuf::errors() const +{ + return _errors; +} + + +StreamConverterIOS::StreamConverterIOS(std::istream& istr, const TextEncoding& inEncoding, const TextEncoding& outEncoding, int defaultChar): + _buf(istr, inEncoding, outEncoding, defaultChar) +{ + poco_ios_init(&_buf); +} + + +StreamConverterIOS::StreamConverterIOS(std::ostream& ostr, const TextEncoding& inEncoding, const TextEncoding& outEncoding, int defaultChar): + _buf(ostr, inEncoding, outEncoding, defaultChar) +{ + poco_ios_init(&_buf); +} + + +StreamConverterIOS::~StreamConverterIOS() +{ +} + + +StreamConverterBuf* StreamConverterIOS::rdbuf() +{ + return &_buf; +} + + +int StreamConverterIOS::errors() const +{ + return _buf.errors(); +} + + +InputStreamConverter::InputStreamConverter(std::istream& istr, const TextEncoding& inEncoding, const TextEncoding& outEncoding, int defaultChar): + StreamConverterIOS(istr, inEncoding, outEncoding, defaultChar), + std::istream(&_buf) +{ +} + + +InputStreamConverter::~InputStreamConverter() +{ +} + + +OutputStreamConverter::OutputStreamConverter(std::ostream& ostr, const TextEncoding& inEncoding, const TextEncoding& outEncoding, int defaultChar): + StreamConverterIOS(ostr, inEncoding, outEncoding, defaultChar), + std::ostream(&_buf) +{ +} + + +OutputStreamConverter::~OutputStreamConverter() +{ +} + + +} // namespace Poco diff --git a/Foundation/src/StreamCopier.cpp b/Foundation/src/StreamCopier.cpp index 37fa877db..f66e096c7 100644 --- a/Foundation/src/StreamCopier.cpp +++ b/Foundation/src/StreamCopier.cpp @@ -1,105 +1,105 @@ -// -// StreamCopier.cpp -// -// $Id: //poco/1.2/Foundation/src/StreamCopier.cpp#1 $ -// -// Library: Foundation -// Package: Streams -// Module: StreamCopier -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/StreamCopier.h" -#include "Poco/Buffer.h" - - -namespace Poco { - - -std::streamsize StreamCopier::copyStream(std::istream& istr, std::ostream& ostr, unsigned bufferSize) -{ - poco_assert (bufferSize > 0); - - Buffer buffer(bufferSize); - std::streamsize len = 0; - istr.read(buffer.begin(), bufferSize); - std::streamsize n = istr.gcount(); - while (n > 0) - { - len += n; - ostr.write(buffer.begin(), n); - if (istr && ostr) - { - istr.read(buffer.begin(), bufferSize); - n = istr.gcount(); - } - else n = 0; - } - return len; -} - - -std::streamsize StreamCopier::copyToString(std::istream& istr, std::string& str, unsigned bufferSize) -{ - poco_assert (bufferSize > 0); - - Buffer buffer(bufferSize); - std::streamsize len = 0; - istr.read(buffer.begin(), bufferSize); - std::streamsize n = istr.gcount(); - while (n > 0) - { - len += n; - str.append(buffer.begin(), n); - if (istr) - { - istr.read(buffer.begin(), bufferSize); - n = istr.gcount(); - } - else n = 0; - } - return len; -} - - -std::streamsize StreamCopier::copyStreamUnbuffered(std::istream& istr, std::ostream& ostr) -{ - char c; - std::streamsize len = 0; - istr.get(c); - while (istr && ostr) - { - ++len; - ostr.put(c); - istr.get(c); - } - return len; -} - - -} // namespace Poco +// +// StreamCopier.cpp +// +// $Id: //poco/1.2/Foundation/src/StreamCopier.cpp#1 $ +// +// Library: Foundation +// Package: Streams +// Module: StreamCopier +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/StreamCopier.h" +#include "Poco/Buffer.h" + + +namespace Poco { + + +std::streamsize StreamCopier::copyStream(std::istream& istr, std::ostream& ostr, unsigned bufferSize) +{ + poco_assert (bufferSize > 0); + + Buffer buffer(bufferSize); + std::streamsize len = 0; + istr.read(buffer.begin(), bufferSize); + std::streamsize n = istr.gcount(); + while (n > 0) + { + len += n; + ostr.write(buffer.begin(), n); + if (istr && ostr) + { + istr.read(buffer.begin(), bufferSize); + n = istr.gcount(); + } + else n = 0; + } + return len; +} + + +std::streamsize StreamCopier::copyToString(std::istream& istr, std::string& str, unsigned bufferSize) +{ + poco_assert (bufferSize > 0); + + Buffer buffer(bufferSize); + std::streamsize len = 0; + istr.read(buffer.begin(), bufferSize); + std::streamsize n = istr.gcount(); + while (n > 0) + { + len += n; + str.append(buffer.begin(), n); + if (istr) + { + istr.read(buffer.begin(), bufferSize); + n = istr.gcount(); + } + else n = 0; + } + return len; +} + + +std::streamsize StreamCopier::copyStreamUnbuffered(std::istream& istr, std::ostream& ostr) +{ + char c; + std::streamsize len = 0; + istr.get(c); + while (istr && ostr) + { + ++len; + ostr.put(c); + istr.get(c); + } + return len; +} + + +} // namespace Poco diff --git a/Foundation/src/StreamTokenizer.cpp b/Foundation/src/StreamTokenizer.cpp index ab1eed58f..926dd8a37 100644 --- a/Foundation/src/StreamTokenizer.cpp +++ b/Foundation/src/StreamTokenizer.cpp @@ -1,127 +1,127 @@ -// -// StreamTokenizer.cpp -// -// $Id: //poco/1.2/Foundation/src/StreamTokenizer.cpp#1 $ -// -// Library: Foundation -// Package: Streams -// Module: StreamTokenizer -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/StreamTokenizer.h" - - -namespace Poco { - - -StreamTokenizer::StreamTokenizer(): - _pIstr(0) -{ -} - - -StreamTokenizer::StreamTokenizer(std::istream& istr): - _pIstr(&istr) -{ -} - - -StreamTokenizer::~StreamTokenizer() -{ - for (TokenVec::iterator it = _tokens.begin(); it != _tokens.end(); ++it) - { - delete it->pToken; - } -} - - -void StreamTokenizer::attachToStream(std::istream& istr) -{ - _pIstr = &istr; -} - - -void StreamTokenizer::addToken(Token* pToken) -{ - poco_check_ptr (pToken); - - TokenInfo ti; - ti.pToken = pToken; - ti.ignore = (pToken->tokenClass() == Token::COMMENT_TOKEN || pToken->tokenClass() == Token::WHITESPACE_TOKEN); - _tokens.push_back(ti); -} - - -void StreamTokenizer::addToken(Token* pToken, bool ignore) -{ - poco_check_ptr (pToken); - - TokenInfo ti; - ti.pToken = pToken; - ti.ignore = ignore; - _tokens.push_back(ti); -} - - -const Token* StreamTokenizer::next() -{ - poco_check_ptr (_pIstr); - - static const int eof = std::char_traits::eof(); - - int first = _pIstr->get(); - TokenVec::const_iterator it = _tokens.begin(); - while (first != eof && it != _tokens.end()) - { - const TokenInfo& ti = *it; - if (ti.pToken->start((char) first, *_pIstr)) - { - ti.pToken->finish(*_pIstr); - if (ti.ignore) - { - first = _pIstr->get(); - it = _tokens.begin(); - } - else return ti.pToken; - } - else ++it; - } - if (first == eof) - { - return &_eofToken; - } - else - { - _invalidToken.start((char) first, *_pIstr); - return &_invalidToken; - } -} - - -} // namespace Poco +// +// StreamTokenizer.cpp +// +// $Id: //poco/1.2/Foundation/src/StreamTokenizer.cpp#1 $ +// +// Library: Foundation +// Package: Streams +// Module: StreamTokenizer +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/StreamTokenizer.h" + + +namespace Poco { + + +StreamTokenizer::StreamTokenizer(): + _pIstr(0) +{ +} + + +StreamTokenizer::StreamTokenizer(std::istream& istr): + _pIstr(&istr) +{ +} + + +StreamTokenizer::~StreamTokenizer() +{ + for (TokenVec::iterator it = _tokens.begin(); it != _tokens.end(); ++it) + { + delete it->pToken; + } +} + + +void StreamTokenizer::attachToStream(std::istream& istr) +{ + _pIstr = &istr; +} + + +void StreamTokenizer::addToken(Token* pToken) +{ + poco_check_ptr (pToken); + + TokenInfo ti; + ti.pToken = pToken; + ti.ignore = (pToken->tokenClass() == Token::COMMENT_TOKEN || pToken->tokenClass() == Token::WHITESPACE_TOKEN); + _tokens.push_back(ti); +} + + +void StreamTokenizer::addToken(Token* pToken, bool ignore) +{ + poco_check_ptr (pToken); + + TokenInfo ti; + ti.pToken = pToken; + ti.ignore = ignore; + _tokens.push_back(ti); +} + + +const Token* StreamTokenizer::next() +{ + poco_check_ptr (_pIstr); + + static const int eof = std::char_traits::eof(); + + int first = _pIstr->get(); + TokenVec::const_iterator it = _tokens.begin(); + while (first != eof && it != _tokens.end()) + { + const TokenInfo& ti = *it; + if (ti.pToken->start((char) first, *_pIstr)) + { + ti.pToken->finish(*_pIstr); + if (ti.ignore) + { + first = _pIstr->get(); + it = _tokens.begin(); + } + else return ti.pToken; + } + else ++it; + } + if (first == eof) + { + return &_eofToken; + } + else + { + _invalidToken.start((char) first, *_pIstr); + return &_invalidToken; + } +} + + +} // namespace Poco diff --git a/Foundation/src/String.cpp b/Foundation/src/String.cpp index 672f84c6b..99bf92d0e 100644 --- a/Foundation/src/String.cpp +++ b/Foundation/src/String.cpp @@ -1,158 +1,158 @@ -// -// String.h -// -// $Id: //poco/1.2/Foundation/src/String.cpp#1 $ -// -// Library: Foundation -// Package: Core -// Module: String -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/String.h" - - -namespace Poco { - - -#if defined(POCO_NO_TEMPLATE_ICOMPARE) - - -int icompare(const std::string& str, std::string::size_type pos, std::string::size_type n, std::string::const_iterator it2, std::string::const_iterator end2) -{ - std::string::size_type sz = str.size(); - if (pos > sz) pos = sz; - if (pos + n > sz) n = sz - pos; - std::string::const_iterator it1 = str.begin() + pos; - std::string::const_iterator end1 = str.begin() + pos + n; - std::locale loc; - while (it1 != end1 && it2 != end2) - { - std::string::value_type c1 = tolower(*it1, loc); - std::string::value_type c2 = tolower(*it2, loc); - if (c1 < c2) - return -1; - else if (c1 > c2) - return 1; - ++it1; ++it2; - } - - if (it1 == end1) - return it2 == end2 ? 0 : -1; - else - return 1; -} - - -int icompare(const std::string& str1, const std::string& str2) -{ - return icompare(str1, 0, str1.size(), str2.begin(), str2.end()); -} - - -int icompare(const std::string& str1, std::string::size_type n1, const std::string& str2, std::string::size_type n2) -{ - if (n2 > str2.size()) n2 = str2.size(); - return icompare(str1, 0, n1, str2.begin(), str2.begin() + n2); -} - - -int icompare(const std::string& str1, std::string::size_type n, const std::string& str2) -{ - if (n > str2.size()) n = str2.size(); - return icompare(str1, 0, n, str2.begin(), str2.begin() + n); -} - - -int icompare(const std::string& str1, std::string::size_type pos, std::string::size_type n, const std::string& str2) -{ - return icompare(str1, pos, n, str2.begin(), str2.end()); -} - - -int icompare(const std::string& str1, std::string::size_type pos1, std::string::size_type n1, const std::string& str2, std::string::size_type pos2, std::string::size_type n2) -{ - std::string::size_type sz2 = str2.size(); - if (pos2 > sz2) pos2 = sz2; - if (pos2 + n2 > sz2) n2 = sz2 - pos2; - return icompare(str1, pos1, n1, str2.begin() + pos2, str2.begin() + pos2 + n2); -} - - -int icompare(const std::string& str1, std::string::size_type pos1, std::string::size_type n, const std::string& str2, std::string::size_type pos2) -{ - std::string::size_type sz2 = str2.size(); - if (pos2 > sz2) pos2 = sz2; - if (pos2 + n > sz2) n = sz2 - pos2; - return icompare(str1, pos1, n, str2.begin() + pos2, str2.begin() + pos2 + n); -} - - -int icompare(const std::string& str, std::string::size_type pos, std::string::size_type n, const std::string::value_type* ptr) -{ - poco_check_ptr (ptr); - std::string::size_type sz = str.size(); - if (pos > sz) pos = sz; - if (pos + n > sz) n = sz - pos; - std::string::const_iterator it = str.begin() + pos; - std::string::const_iterator end = str.begin() + pos + n; - std::locale loc; - while (it != end && *ptr) - { - std::string::value_type c1 = tolower(*it, loc); - std::string::value_type c2 = tolower(*ptr, loc); - if (c1 < c2) - return -1; - else if (c1 > c2) - return 1; - ++it; ++ptr; - } - - if (it == end) - return *ptr == 0 ? 0 : -1; - else - return 1; -} - - -int icompare(const std::string& str, std::string::size_type pos, const std::string::value_type* ptr) -{ - return icompare(str, pos, str.size() - pos, ptr); -} - - -int icompare(const std::string& str, const std::string::value_type* ptr) -{ - return icompare(str, 0, str.size(), ptr); -} - - -#endif - - -} // namespace Poco +// +// String.h +// +// $Id: //poco/1.2/Foundation/src/String.cpp#1 $ +// +// Library: Foundation +// Package: Core +// Module: String +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/String.h" + + +namespace Poco { + + +#if defined(POCO_NO_TEMPLATE_ICOMPARE) + + +int icompare(const std::string& str, std::string::size_type pos, std::string::size_type n, std::string::const_iterator it2, std::string::const_iterator end2) +{ + std::string::size_type sz = str.size(); + if (pos > sz) pos = sz; + if (pos + n > sz) n = sz - pos; + std::string::const_iterator it1 = str.begin() + pos; + std::string::const_iterator end1 = str.begin() + pos + n; + std::locale loc; + while (it1 != end1 && it2 != end2) + { + std::string::value_type c1 = tolower(*it1, loc); + std::string::value_type c2 = tolower(*it2, loc); + if (c1 < c2) + return -1; + else if (c1 > c2) + return 1; + ++it1; ++it2; + } + + if (it1 == end1) + return it2 == end2 ? 0 : -1; + else + return 1; +} + + +int icompare(const std::string& str1, const std::string& str2) +{ + return icompare(str1, 0, str1.size(), str2.begin(), str2.end()); +} + + +int icompare(const std::string& str1, std::string::size_type n1, const std::string& str2, std::string::size_type n2) +{ + if (n2 > str2.size()) n2 = str2.size(); + return icompare(str1, 0, n1, str2.begin(), str2.begin() + n2); +} + + +int icompare(const std::string& str1, std::string::size_type n, const std::string& str2) +{ + if (n > str2.size()) n = str2.size(); + return icompare(str1, 0, n, str2.begin(), str2.begin() + n); +} + + +int icompare(const std::string& str1, std::string::size_type pos, std::string::size_type n, const std::string& str2) +{ + return icompare(str1, pos, n, str2.begin(), str2.end()); +} + + +int icompare(const std::string& str1, std::string::size_type pos1, std::string::size_type n1, const std::string& str2, std::string::size_type pos2, std::string::size_type n2) +{ + std::string::size_type sz2 = str2.size(); + if (pos2 > sz2) pos2 = sz2; + if (pos2 + n2 > sz2) n2 = sz2 - pos2; + return icompare(str1, pos1, n1, str2.begin() + pos2, str2.begin() + pos2 + n2); +} + + +int icompare(const std::string& str1, std::string::size_type pos1, std::string::size_type n, const std::string& str2, std::string::size_type pos2) +{ + std::string::size_type sz2 = str2.size(); + if (pos2 > sz2) pos2 = sz2; + if (pos2 + n > sz2) n = sz2 - pos2; + return icompare(str1, pos1, n, str2.begin() + pos2, str2.begin() + pos2 + n); +} + + +int icompare(const std::string& str, std::string::size_type pos, std::string::size_type n, const std::string::value_type* ptr) +{ + poco_check_ptr (ptr); + std::string::size_type sz = str.size(); + if (pos > sz) pos = sz; + if (pos + n > sz) n = sz - pos; + std::string::const_iterator it = str.begin() + pos; + std::string::const_iterator end = str.begin() + pos + n; + std::locale loc; + while (it != end && *ptr) + { + std::string::value_type c1 = tolower(*it, loc); + std::string::value_type c2 = tolower(*ptr, loc); + if (c1 < c2) + return -1; + else if (c1 > c2) + return 1; + ++it; ++ptr; + } + + if (it == end) + return *ptr == 0 ? 0 : -1; + else + return 1; +} + + +int icompare(const std::string& str, std::string::size_type pos, const std::string::value_type* ptr) +{ + return icompare(str, pos, str.size() - pos, ptr); +} + + +int icompare(const std::string& str, const std::string::value_type* ptr) +{ + return icompare(str, 0, str.size(), ptr); +} + + +#endif + + +} // namespace Poco diff --git a/Foundation/src/StringTokenizer.cpp b/Foundation/src/StringTokenizer.cpp index 33cd3a89e..b1768e16f 100644 --- a/Foundation/src/StringTokenizer.cpp +++ b/Foundation/src/StringTokenizer.cpp @@ -1,87 +1,87 @@ -// -// StringTokenizer.cpp -// -// $Id: //poco/1.2/Foundation/src/StringTokenizer.cpp#1 $ -// -// Library: Foundation -// Package: Core -// Module: StringTokenizer -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/StringTokenizer.h" -#include - - -namespace Poco { - - -StringTokenizer::StringTokenizer(const std::string& str, const std::string& separators, int options) -{ - std::locale loc; - std::string::const_iterator it1 = str.begin(); - std::string::const_iterator it2; - std::string::const_iterator it3; - std::string::const_iterator end = str.end(); - - while (it1 != end) - { - if (options & TOK_TRIM) - { - while (it1 != end && std::isspace(*it1, loc)) ++it1; - } - it2 = it1; - while (it2 != end && separators.find(*it2) == std::string::npos) ++it2; - it3 = it2; - if (it3 != it1 && (options & TOK_TRIM)) - { - --it3; - while (it3 != it1 && std::isspace(*it3, loc)) --it3; - if (!std::isspace(*it3, loc)) ++it3; - } - if (options & TOK_IGNORE_EMPTY) - { - if (it3 != it1) - _tokens.push_back(std::string(it1, it3)); - } - else - { - _tokens.push_back(std::string(it1, it3)); - } - it1 = it2; - if (it1 != end) ++it1; - } -} - - -StringTokenizer::~StringTokenizer() -{ -} - - -} // namespace Poco +// +// StringTokenizer.cpp +// +// $Id: //poco/1.2/Foundation/src/StringTokenizer.cpp#1 $ +// +// Library: Foundation +// Package: Core +// Module: StringTokenizer +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/StringTokenizer.h" +#include + + +namespace Poco { + + +StringTokenizer::StringTokenizer(const std::string& str, const std::string& separators, int options) +{ + std::locale loc; + std::string::const_iterator it1 = str.begin(); + std::string::const_iterator it2; + std::string::const_iterator it3; + std::string::const_iterator end = str.end(); + + while (it1 != end) + { + if (options & TOK_TRIM) + { + while (it1 != end && std::isspace(*it1, loc)) ++it1; + } + it2 = it1; + while (it2 != end && separators.find(*it2) == std::string::npos) ++it2; + it3 = it2; + if (it3 != it1 && (options & TOK_TRIM)) + { + --it3; + while (it3 != it1 && std::isspace(*it3, loc)) --it3; + if (!std::isspace(*it3, loc)) ++it3; + } + if (options & TOK_IGNORE_EMPTY) + { + if (it3 != it1) + _tokens.push_back(std::string(it1, it3)); + } + else + { + _tokens.push_back(std::string(it1, it3)); + } + it1 = it2; + if (it1 != end) ++it1; + } +} + + +StringTokenizer::~StringTokenizer() +{ +} + + +} // namespace Poco diff --git a/Foundation/src/SynchronizedObject.cpp b/Foundation/src/SynchronizedObject.cpp index 24b839b81..93b357195 100644 --- a/Foundation/src/SynchronizedObject.cpp +++ b/Foundation/src/SynchronizedObject.cpp @@ -1,53 +1,53 @@ -// -// SynchronizedObject.cpp -// -// $Id: //poco/1.2/Foundation/src/SynchronizedObject.cpp#1 $ -// -// Library: Foundation -// Package: Threading -// Module: SynchronizedObject -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/SynchronizedObject.h" - - -namespace Poco { - - -SynchronizedObject::SynchronizedObject() -{ -} - - -SynchronizedObject::~SynchronizedObject() -{ -} - - -} // namespace Poco +// +// SynchronizedObject.cpp +// +// $Id: //poco/1.2/Foundation/src/SynchronizedObject.cpp#1 $ +// +// Library: Foundation +// Package: Threading +// Module: SynchronizedObject +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/SynchronizedObject.h" + + +namespace Poco { + + +SynchronizedObject::SynchronizedObject() +{ +} + + +SynchronizedObject::~SynchronizedObject() +{ +} + + +} // namespace Poco diff --git a/Foundation/src/SyslogChannel.cpp b/Foundation/src/SyslogChannel.cpp index f77203800..86142cfae 100644 --- a/Foundation/src/SyslogChannel.cpp +++ b/Foundation/src/SyslogChannel.cpp @@ -1,278 +1,278 @@ -// -// SyslogChannel.cpp -// -// $Id: //poco/1.2/Foundation/src/SyslogChannel.cpp#1 $ -// -// Library: Foundation -// Package: Logging -// Module: SyslogChannel -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/SyslogChannel.h" -#include "Poco/Message.h" -#include "Poco/StringTokenizer.h" -#include - - -namespace Poco { - - -const std::string SyslogChannel::PROP_NAME = "name"; -const std::string SyslogChannel::PROP_FACILITY = "facility"; -const std::string SyslogChannel::PROP_OPTIONS = "options"; - - -SyslogChannel::SyslogChannel(): - _options(SYSLOG_CONS), - _facility(SYSLOG_USER), - _open(false) -{ -} - - -SyslogChannel::SyslogChannel(const std::string& name, int options, int facility): - _name(name), - _options(options), - _facility(facility), - _open(false) -{ -} - - -SyslogChannel::~SyslogChannel() -{ - close(); -} - - -void SyslogChannel::open() -{ - openlog(_name.c_str(), _options, _facility); - _open = true; -} - - -void SyslogChannel::close() -{ - if (_open) - { - closelog(); - _open = false; - } -} - - -void SyslogChannel::log(const Message& msg) -{ - if (!_open) open(); - syslog(getPrio(msg), "%s", msg.getText().c_str()); -} - - -void SyslogChannel::setProperty(const std::string& name, const std::string& value) -{ - if (name == PROP_NAME) - { - _name = value; - } - else if (name == PROP_FACILITY) - { - if (value == "LOG_KERN") - _facility = SYSLOG_KERN; - else if (value == "LOG_USER") - _facility = SYSLOG_USER; - else if (value == "LOG_MAIL") - _facility = SYSLOG_MAIL; - else if (value == "LOG_DAEMON") - _facility = SYSLOG_DAEMON; - else if (value == "LOG_AUTH") - _facility = SYSLOG_AUTH; - else if (value == "LOG_AUTHPRIV") - _facility = SYSLOG_AUTHPRIV; - else if (value == "LOG_SYSLOG") - _facility = SYSLOG_SYSLOG; - else if (value == "LOG_LPR") - _facility = SYSLOG_LPR; - else if (value == "LOG_NEWS") - _facility = SYSLOG_NEWS; - else if (value == "LOG_UUCP") - _facility = SYSLOG_UUCP; - else if (value == "LOG_CRON") - _facility = SYSLOG_CRON; - else if (value == "LOG_FTP") - _facility = SYSLOG_FTP; - else if (value == "LOG_LOCAL0") - _facility = SYSLOG_LOCAL0; - else if (value == "LOG_LOCAL1") - _facility = SYSLOG_LOCAL1; - else if (value == "LOG_LOCAL2") - _facility = SYSLOG_LOCAL2; - else if (value == "LOG_LOCAL3") - _facility = SYSLOG_LOCAL3; - else if (value == "LOG_LOCAL4") - _facility = SYSLOG_LOCAL4; - else if (value == "LOG_LOCAL5") - _facility = SYSLOG_LOCAL5; - else if (value == "LOG_LOCAL6") - _facility = SYSLOG_LOCAL6; - else if (value == "LOG_LOCAL7") - _facility = SYSLOG_LOCAL7; - } - else if (name == PROP_OPTIONS) - { - _options = 0; - StringTokenizer tokenizer(value, "|+:;,", StringTokenizer::TOK_IGNORE_EMPTY | StringTokenizer::TOK_TRIM); - for (StringTokenizer::Iterator it = tokenizer.begin(); it != tokenizer.end(); ++it) - { - if (*it == "LOG_CONS") - _options |= SYSLOG_CONS; - else if (*it == "LOG_NDELAY") - _options |= SYSLOG_NDELAY; - else if (*it == "LOG_PERROR") - _options |= SYSLOG_PERROR; - else if (*it == "LOG_PID") - _options |= SYSLOG_PID; - } - } - else - { - Channel::setProperty(name, value); - } -} - - -std::string SyslogChannel::getProperty(const std::string& name) const -{ - if (name == PROP_NAME) - { - return _name; - } - else if (name == PROP_FACILITY) - { - if (_facility == SYSLOG_KERN) - return "LOG_KERN"; - else if (_facility == SYSLOG_USER) - return "LOG_USER"; - else if (_facility == SYSLOG_MAIL) - return "LOG_MAIL"; - else if (_facility == SYSLOG_DAEMON) - return "LOG_DAEMON"; - else if (_facility == SYSLOG_AUTH) - return "LOG_AUTH"; - else if (_facility == SYSLOG_AUTHPRIV) - return "LOG_AUTHPRIV"; - else if (_facility == SYSLOG_SYSLOG) - return "LOG_SYSLOG"; - else if (_facility == SYSLOG_LPR) - return "LOG_LPR"; - else if (_facility == SYSLOG_NEWS) - return "LOG_NEWS"; - else if (_facility == SYSLOG_UUCP) - return "LOG_UUCP"; - else if (_facility == SYSLOG_CRON) - return "LOG_CRON"; - else if (_facility == SYSLOG_FTP) - return "LOG_FTP"; - else if (_facility == SYSLOG_LOCAL0) - return "LOG_LOCAL0"; - else if (_facility == SYSLOG_LOCAL1) - return "LOG_LOCAL1"; - else if (_facility == SYSLOG_LOCAL2) - return "LOG_LOCAL2"; - else if (_facility == SYSLOG_LOCAL3) - return "LOG_LOCAL3"; - else if (_facility == SYSLOG_LOCAL4) - return "LOG_LOCAL4"; - else if (_facility == SYSLOG_LOCAL5) - return "LOG_LOCAL5"; - else if (_facility == SYSLOG_LOCAL6) - return "LOG_LOCAL6"; - else if (_facility == SYSLOG_LOCAL7) - return "LOG_LOCAL7"; - else - return ""; - } - else if (name == PROP_OPTIONS) - { - std::string result; - if (_options & SYSLOG_CONS) - { - if (!result.empty()) result.append("|"); - result.append("LOG_CONS"); - } - if (_options & SYSLOG_NDELAY) - { - if (!result.empty()) result.append("|"); - result.append("LOG_NDELAY"); - } - if (_options & SYSLOG_PERROR) - { - if (!result.empty()) result.append("|"); - result.append("LOG_PERROR"); - } - if (_options & SYSLOG_PID) - { - if (!result.empty()) result.append("|"); - result.append("LOG_PID"); - } - return result; - } - else - { - return Channel::getProperty(name); - } -} - - -int SyslogChannel::getPrio(const Message& msg) -{ - switch (msg.getPriority()) - { - case Message::PRIO_TRACE: - case Message::PRIO_DEBUG: - return LOG_DEBUG; - case Message::PRIO_INFORMATION: - return LOG_INFO; - case Message::PRIO_NOTICE: - return LOG_NOTICE; - case Message::PRIO_WARNING: - return LOG_WARNING; - case Message::PRIO_ERROR: - return LOG_ERR; - case Message::PRIO_CRITICAL: - return LOG_CRIT; - case Message::PRIO_FATAL: - return LOG_ALERT; - default: - return 0; - } -} - - -} // namespace Poco +// +// SyslogChannel.cpp +// +// $Id: //poco/1.2/Foundation/src/SyslogChannel.cpp#1 $ +// +// Library: Foundation +// Package: Logging +// Module: SyslogChannel +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/SyslogChannel.h" +#include "Poco/Message.h" +#include "Poco/StringTokenizer.h" +#include + + +namespace Poco { + + +const std::string SyslogChannel::PROP_NAME = "name"; +const std::string SyslogChannel::PROP_FACILITY = "facility"; +const std::string SyslogChannel::PROP_OPTIONS = "options"; + + +SyslogChannel::SyslogChannel(): + _options(SYSLOG_CONS), + _facility(SYSLOG_USER), + _open(false) +{ +} + + +SyslogChannel::SyslogChannel(const std::string& name, int options, int facility): + _name(name), + _options(options), + _facility(facility), + _open(false) +{ +} + + +SyslogChannel::~SyslogChannel() +{ + close(); +} + + +void SyslogChannel::open() +{ + openlog(_name.c_str(), _options, _facility); + _open = true; +} + + +void SyslogChannel::close() +{ + if (_open) + { + closelog(); + _open = false; + } +} + + +void SyslogChannel::log(const Message& msg) +{ + if (!_open) open(); + syslog(getPrio(msg), "%s", msg.getText().c_str()); +} + + +void SyslogChannel::setProperty(const std::string& name, const std::string& value) +{ + if (name == PROP_NAME) + { + _name = value; + } + else if (name == PROP_FACILITY) + { + if (value == "LOG_KERN") + _facility = SYSLOG_KERN; + else if (value == "LOG_USER") + _facility = SYSLOG_USER; + else if (value == "LOG_MAIL") + _facility = SYSLOG_MAIL; + else if (value == "LOG_DAEMON") + _facility = SYSLOG_DAEMON; + else if (value == "LOG_AUTH") + _facility = SYSLOG_AUTH; + else if (value == "LOG_AUTHPRIV") + _facility = SYSLOG_AUTHPRIV; + else if (value == "LOG_SYSLOG") + _facility = SYSLOG_SYSLOG; + else if (value == "LOG_LPR") + _facility = SYSLOG_LPR; + else if (value == "LOG_NEWS") + _facility = SYSLOG_NEWS; + else if (value == "LOG_UUCP") + _facility = SYSLOG_UUCP; + else if (value == "LOG_CRON") + _facility = SYSLOG_CRON; + else if (value == "LOG_FTP") + _facility = SYSLOG_FTP; + else if (value == "LOG_LOCAL0") + _facility = SYSLOG_LOCAL0; + else if (value == "LOG_LOCAL1") + _facility = SYSLOG_LOCAL1; + else if (value == "LOG_LOCAL2") + _facility = SYSLOG_LOCAL2; + else if (value == "LOG_LOCAL3") + _facility = SYSLOG_LOCAL3; + else if (value == "LOG_LOCAL4") + _facility = SYSLOG_LOCAL4; + else if (value == "LOG_LOCAL5") + _facility = SYSLOG_LOCAL5; + else if (value == "LOG_LOCAL6") + _facility = SYSLOG_LOCAL6; + else if (value == "LOG_LOCAL7") + _facility = SYSLOG_LOCAL7; + } + else if (name == PROP_OPTIONS) + { + _options = 0; + StringTokenizer tokenizer(value, "|+:;,", StringTokenizer::TOK_IGNORE_EMPTY | StringTokenizer::TOK_TRIM); + for (StringTokenizer::Iterator it = tokenizer.begin(); it != tokenizer.end(); ++it) + { + if (*it == "LOG_CONS") + _options |= SYSLOG_CONS; + else if (*it == "LOG_NDELAY") + _options |= SYSLOG_NDELAY; + else if (*it == "LOG_PERROR") + _options |= SYSLOG_PERROR; + else if (*it == "LOG_PID") + _options |= SYSLOG_PID; + } + } + else + { + Channel::setProperty(name, value); + } +} + + +std::string SyslogChannel::getProperty(const std::string& name) const +{ + if (name == PROP_NAME) + { + return _name; + } + else if (name == PROP_FACILITY) + { + if (_facility == SYSLOG_KERN) + return "LOG_KERN"; + else if (_facility == SYSLOG_USER) + return "LOG_USER"; + else if (_facility == SYSLOG_MAIL) + return "LOG_MAIL"; + else if (_facility == SYSLOG_DAEMON) + return "LOG_DAEMON"; + else if (_facility == SYSLOG_AUTH) + return "LOG_AUTH"; + else if (_facility == SYSLOG_AUTHPRIV) + return "LOG_AUTHPRIV"; + else if (_facility == SYSLOG_SYSLOG) + return "LOG_SYSLOG"; + else if (_facility == SYSLOG_LPR) + return "LOG_LPR"; + else if (_facility == SYSLOG_NEWS) + return "LOG_NEWS"; + else if (_facility == SYSLOG_UUCP) + return "LOG_UUCP"; + else if (_facility == SYSLOG_CRON) + return "LOG_CRON"; + else if (_facility == SYSLOG_FTP) + return "LOG_FTP"; + else if (_facility == SYSLOG_LOCAL0) + return "LOG_LOCAL0"; + else if (_facility == SYSLOG_LOCAL1) + return "LOG_LOCAL1"; + else if (_facility == SYSLOG_LOCAL2) + return "LOG_LOCAL2"; + else if (_facility == SYSLOG_LOCAL3) + return "LOG_LOCAL3"; + else if (_facility == SYSLOG_LOCAL4) + return "LOG_LOCAL4"; + else if (_facility == SYSLOG_LOCAL5) + return "LOG_LOCAL5"; + else if (_facility == SYSLOG_LOCAL6) + return "LOG_LOCAL6"; + else if (_facility == SYSLOG_LOCAL7) + return "LOG_LOCAL7"; + else + return ""; + } + else if (name == PROP_OPTIONS) + { + std::string result; + if (_options & SYSLOG_CONS) + { + if (!result.empty()) result.append("|"); + result.append("LOG_CONS"); + } + if (_options & SYSLOG_NDELAY) + { + if (!result.empty()) result.append("|"); + result.append("LOG_NDELAY"); + } + if (_options & SYSLOG_PERROR) + { + if (!result.empty()) result.append("|"); + result.append("LOG_PERROR"); + } + if (_options & SYSLOG_PID) + { + if (!result.empty()) result.append("|"); + result.append("LOG_PID"); + } + return result; + } + else + { + return Channel::getProperty(name); + } +} + + +int SyslogChannel::getPrio(const Message& msg) +{ + switch (msg.getPriority()) + { + case Message::PRIO_TRACE: + case Message::PRIO_DEBUG: + return LOG_DEBUG; + case Message::PRIO_INFORMATION: + return LOG_INFO; + case Message::PRIO_NOTICE: + return LOG_NOTICE; + case Message::PRIO_WARNING: + return LOG_WARNING; + case Message::PRIO_ERROR: + return LOG_ERR; + case Message::PRIO_CRITICAL: + return LOG_CRIT; + case Message::PRIO_FATAL: + return LOG_ALERT; + default: + return 0; + } +} + + +} // namespace Poco diff --git a/Foundation/src/Task.cpp b/Foundation/src/Task.cpp index 358466fbb..76bd0f081 100644 --- a/Foundation/src/Task.cpp +++ b/Foundation/src/Task.cpp @@ -1,151 +1,151 @@ -// -// Task.cpp -// -// $Id: //poco/1.2/Foundation/src/Task.cpp#1 $ -// -// Library: Foundation -// Package: Tasks -// Module: Tasks -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/Task.h" -#include "Poco/TaskManager.h" -#include "Poco/Exception.h" - - -namespace Poco { - - -Task::Task(const std::string& name): - _name(name), - _pOwner(0), - _progress(0), - _state(TASK_IDLE), - _cancelEvent(false) -{ -} - - -Task::~Task() -{ -} - - -void Task::cancel() -{ - _state = TASK_CANCELLING; - _cancelEvent.set(); - if (_pOwner) - _pOwner->taskCancelled(this); -} - - -void Task::reset() -{ - _progress = 0.0; - _state = TASK_IDLE; - _cancelEvent.reset(); -} - - -void Task::run() -{ - TaskManager* pOwner = getOwner(); - if (pOwner) - pOwner->taskStarted(this); - try - { - _state = TASK_RUNNING; - runTask(); - } - catch (Exception& exc) - { - if (pOwner) - pOwner->taskFailed(this, exc); - } - catch (std::exception& exc) - { - if (pOwner) - pOwner->taskFailed(this, SystemException(exc.what())); - } - catch (...) - { - if (pOwner) - pOwner->taskFailed(this, SystemException("unknown exception")); - } - _state = TASK_FINISHED; - if (pOwner) - pOwner->taskFinished(this); -} - - -bool Task::sleep(long milliseconds) -{ - return _cancelEvent.tryWait(milliseconds); -} - - -void Task::setProgress(float progress) -{ - FastMutex::ScopedLock lock(_mutex); - - _progress = progress; - if (_pOwner) - _pOwner->taskProgress(this, _progress); -} - - -void Task::setOwner(TaskManager* pOwner) -{ - FastMutex::ScopedLock lock(_mutex); - - _pOwner = pOwner; -} - - -void Task::setState(TaskState state) -{ - _state = state; -} - - -void Task::postNotification(Notification* pNf) -{ - poco_check_ptr (pNf); - - FastMutex::ScopedLock lock(_mutex); - - if (_pOwner) - { - _pOwner->postNotification(pNf); - } -} - - -} // namespace Poco +// +// Task.cpp +// +// $Id: //poco/1.2/Foundation/src/Task.cpp#1 $ +// +// Library: Foundation +// Package: Tasks +// Module: Tasks +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/Task.h" +#include "Poco/TaskManager.h" +#include "Poco/Exception.h" + + +namespace Poco { + + +Task::Task(const std::string& name): + _name(name), + _pOwner(0), + _progress(0), + _state(TASK_IDLE), + _cancelEvent(false) +{ +} + + +Task::~Task() +{ +} + + +void Task::cancel() +{ + _state = TASK_CANCELLING; + _cancelEvent.set(); + if (_pOwner) + _pOwner->taskCancelled(this); +} + + +void Task::reset() +{ + _progress = 0.0; + _state = TASK_IDLE; + _cancelEvent.reset(); +} + + +void Task::run() +{ + TaskManager* pOwner = getOwner(); + if (pOwner) + pOwner->taskStarted(this); + try + { + _state = TASK_RUNNING; + runTask(); + } + catch (Exception& exc) + { + if (pOwner) + pOwner->taskFailed(this, exc); + } + catch (std::exception& exc) + { + if (pOwner) + pOwner->taskFailed(this, SystemException(exc.what())); + } + catch (...) + { + if (pOwner) + pOwner->taskFailed(this, SystemException("unknown exception")); + } + _state = TASK_FINISHED; + if (pOwner) + pOwner->taskFinished(this); +} + + +bool Task::sleep(long milliseconds) +{ + return _cancelEvent.tryWait(milliseconds); +} + + +void Task::setProgress(float progress) +{ + FastMutex::ScopedLock lock(_mutex); + + _progress = progress; + if (_pOwner) + _pOwner->taskProgress(this, _progress); +} + + +void Task::setOwner(TaskManager* pOwner) +{ + FastMutex::ScopedLock lock(_mutex); + + _pOwner = pOwner; +} + + +void Task::setState(TaskState state) +{ + _state = state; +} + + +void Task::postNotification(Notification* pNf) +{ + poco_check_ptr (pNf); + + FastMutex::ScopedLock lock(_mutex); + + if (_pOwner) + { + _pOwner->postNotification(pNf); + } +} + + +} // namespace Poco diff --git a/Foundation/src/TaskManager.cpp b/Foundation/src/TaskManager.cpp index 5db04c0f1..a798cb4a3 100644 --- a/Foundation/src/TaskManager.cpp +++ b/Foundation/src/TaskManager.cpp @@ -1,165 +1,165 @@ -// -// TaskManager.cpp -// -// $Id: //poco/1.2/Foundation/src/TaskManager.cpp#1 $ -// -// Library: Foundation -// Package: Tasks -// Module: Tasks -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/TaskManager.h" -#include "Poco/TaskNotification.h" -#include "Poco/ThreadPool.h" - - -namespace Poco { - - -const int TaskManager::MIN_PROGRESS_NOTIFICATION_INTERVAL = 100000; // 100 milliseconds - - -TaskManager::TaskManager(): - _threadPool(ThreadPool::defaultPool()) -{ -} - - -TaskManager::TaskManager(ThreadPool& pool): - _threadPool(pool) -{ -} - - -TaskManager::~TaskManager() -{ -} - - -void TaskManager::start(Task* pTask) -{ - FastMutex::ScopedLock lock(_mutex); - - pTask->setOwner(this); - pTask->setState(Task::TASK_STARTING); - _taskList.push_back(TaskPtr(pTask)); - _threadPool.start(*pTask, pTask->name()); -} - - -void TaskManager::cancelAll() -{ - FastMutex::ScopedLock lock(_mutex); - - for (TaskList::iterator it = _taskList.begin(); it != _taskList.end(); ++it) - { - (*it)->cancel(); - } -} - - -void TaskManager::joinAll() -{ - _threadPool.joinAll(); -} - - -TaskManager::TaskList TaskManager::taskList() const -{ - FastMutex::ScopedLock lock(_mutex); - - return _taskList; -} - - -void TaskManager::addObserver(const AbstractObserver& observer) -{ - _nc.addObserver(observer); -} - - -void TaskManager::removeObserver(const AbstractObserver& observer) -{ - _nc.removeObserver(observer); -} - - -void TaskManager::postNotification(Notification* pNf) -{ - _nc.postNotification(pNf); -} - - -void TaskManager::taskStarted(Task* pTask) -{ - _nc.postNotification(new TaskStartedNotification(pTask)); -} - - -void TaskManager::taskProgress(Task* pTask, float progress) -{ - FastMutex::ScopedLock lock(_mutex); - - if (_lastProgressNotification.isElapsed(MIN_PROGRESS_NOTIFICATION_INTERVAL)) - { - _lastProgressNotification.update(); - _nc.postNotification(new TaskProgressNotification(pTask, progress)); - } -} - - -void TaskManager::taskCancelled(Task* pTask) -{ - _nc.postNotification(new TaskCancelledNotification(pTask)); -} - - -void TaskManager::taskFinished(Task* pTask) -{ - _nc.postNotification(new TaskFinishedNotification(pTask)); - - FastMutex::ScopedLock lock(_mutex); - for (TaskList::iterator it = _taskList.begin(); it != _taskList.end(); ++it) - { - if (*it == pTask) - { - _taskList.erase(it); - break; - } - } -} - - -void TaskManager::taskFailed(Task* pTask, const Exception& exc) -{ - _nc.postNotification(new TaskFailedNotification(pTask, exc)); -} - - -} // namespace Poco +// +// TaskManager.cpp +// +// $Id: //poco/1.2/Foundation/src/TaskManager.cpp#1 $ +// +// Library: Foundation +// Package: Tasks +// Module: Tasks +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/TaskManager.h" +#include "Poco/TaskNotification.h" +#include "Poco/ThreadPool.h" + + +namespace Poco { + + +const int TaskManager::MIN_PROGRESS_NOTIFICATION_INTERVAL = 100000; // 100 milliseconds + + +TaskManager::TaskManager(): + _threadPool(ThreadPool::defaultPool()) +{ +} + + +TaskManager::TaskManager(ThreadPool& pool): + _threadPool(pool) +{ +} + + +TaskManager::~TaskManager() +{ +} + + +void TaskManager::start(Task* pTask) +{ + FastMutex::ScopedLock lock(_mutex); + + pTask->setOwner(this); + pTask->setState(Task::TASK_STARTING); + _taskList.push_back(TaskPtr(pTask)); + _threadPool.start(*pTask, pTask->name()); +} + + +void TaskManager::cancelAll() +{ + FastMutex::ScopedLock lock(_mutex); + + for (TaskList::iterator it = _taskList.begin(); it != _taskList.end(); ++it) + { + (*it)->cancel(); + } +} + + +void TaskManager::joinAll() +{ + _threadPool.joinAll(); +} + + +TaskManager::TaskList TaskManager::taskList() const +{ + FastMutex::ScopedLock lock(_mutex); + + return _taskList; +} + + +void TaskManager::addObserver(const AbstractObserver& observer) +{ + _nc.addObserver(observer); +} + + +void TaskManager::removeObserver(const AbstractObserver& observer) +{ + _nc.removeObserver(observer); +} + + +void TaskManager::postNotification(Notification* pNf) +{ + _nc.postNotification(pNf); +} + + +void TaskManager::taskStarted(Task* pTask) +{ + _nc.postNotification(new TaskStartedNotification(pTask)); +} + + +void TaskManager::taskProgress(Task* pTask, float progress) +{ + FastMutex::ScopedLock lock(_mutex); + + if (_lastProgressNotification.isElapsed(MIN_PROGRESS_NOTIFICATION_INTERVAL)) + { + _lastProgressNotification.update(); + _nc.postNotification(new TaskProgressNotification(pTask, progress)); + } +} + + +void TaskManager::taskCancelled(Task* pTask) +{ + _nc.postNotification(new TaskCancelledNotification(pTask)); +} + + +void TaskManager::taskFinished(Task* pTask) +{ + _nc.postNotification(new TaskFinishedNotification(pTask)); + + FastMutex::ScopedLock lock(_mutex); + for (TaskList::iterator it = _taskList.begin(); it != _taskList.end(); ++it) + { + if (*it == pTask) + { + _taskList.erase(it); + break; + } + } +} + + +void TaskManager::taskFailed(Task* pTask, const Exception& exc) +{ + _nc.postNotification(new TaskFailedNotification(pTask, exc)); +} + + +} // namespace Poco diff --git a/Foundation/src/TaskNotification.cpp b/Foundation/src/TaskNotification.cpp index 2526913be..65e0257a1 100644 --- a/Foundation/src/TaskNotification.cpp +++ b/Foundation/src/TaskNotification.cpp @@ -1,114 +1,114 @@ -// -// TaskNotification.cpp -// -// $Id: //poco/1.2/Foundation/src/TaskNotification.cpp#1 $ -// -// Library: Foundation -// Package: Tasks -// Module: Tasks -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/TaskNotification.h" - - -namespace Poco { - - -TaskNotification::TaskNotification(Task* pTask): - _pTask(pTask) -{ - if (_pTask) _pTask->duplicate(); -} - - -TaskNotification::~TaskNotification() -{ - if (_pTask) _pTask->release(); -} - - -TaskStartedNotification::TaskStartedNotification(Task* pTask): - TaskNotification(pTask) -{ -} - - -TaskStartedNotification::~TaskStartedNotification() -{ -} - - -TaskCancelledNotification::TaskCancelledNotification(Task* pTask): - TaskNotification(pTask) -{ -} - - -TaskCancelledNotification::~TaskCancelledNotification() -{ -} - - -TaskFinishedNotification::TaskFinishedNotification(Task* pTask): - TaskNotification(pTask) -{ -} - - -TaskFinishedNotification::~TaskFinishedNotification() -{ -} - - -TaskFailedNotification::TaskFailedNotification(Task* pTask, const Exception& exc): - TaskNotification(pTask), - _pException(exc.clone()) -{ -} - - -TaskFailedNotification::~TaskFailedNotification() -{ - delete _pException; -} - - -TaskProgressNotification::TaskProgressNotification(Task* pTask, float progress): - TaskNotification(pTask), - _progress(progress) -{ -} - - -TaskProgressNotification::~TaskProgressNotification() -{ -} - - -} // namespace Poco +// +// TaskNotification.cpp +// +// $Id: //poco/1.2/Foundation/src/TaskNotification.cpp#1 $ +// +// Library: Foundation +// Package: Tasks +// Module: Tasks +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/TaskNotification.h" + + +namespace Poco { + + +TaskNotification::TaskNotification(Task* pTask): + _pTask(pTask) +{ + if (_pTask) _pTask->duplicate(); +} + + +TaskNotification::~TaskNotification() +{ + if (_pTask) _pTask->release(); +} + + +TaskStartedNotification::TaskStartedNotification(Task* pTask): + TaskNotification(pTask) +{ +} + + +TaskStartedNotification::~TaskStartedNotification() +{ +} + + +TaskCancelledNotification::TaskCancelledNotification(Task* pTask): + TaskNotification(pTask) +{ +} + + +TaskCancelledNotification::~TaskCancelledNotification() +{ +} + + +TaskFinishedNotification::TaskFinishedNotification(Task* pTask): + TaskNotification(pTask) +{ +} + + +TaskFinishedNotification::~TaskFinishedNotification() +{ +} + + +TaskFailedNotification::TaskFailedNotification(Task* pTask, const Exception& exc): + TaskNotification(pTask), + _pException(exc.clone()) +{ +} + + +TaskFailedNotification::~TaskFailedNotification() +{ + delete _pException; +} + + +TaskProgressNotification::TaskProgressNotification(Task* pTask, float progress): + TaskNotification(pTask), + _progress(progress) +{ +} + + +TaskProgressNotification::~TaskProgressNotification() +{ +} + + +} // namespace Poco diff --git a/Foundation/src/TeeStream.cpp b/Foundation/src/TeeStream.cpp index 352bd091c..824e896c0 100644 --- a/Foundation/src/TeeStream.cpp +++ b/Foundation/src/TeeStream.cpp @@ -1,155 +1,155 @@ -// -// TeeStream.cpp -// -// $Id: //poco/1.2/Foundation/src/TeeStream.cpp#1 $ -// -// Library: Foundation -// Package: Streams -// Module: TeeStream -// -// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/TeeStream.h" - - -namespace Poco { - - -TeeStreamBuf::TeeStreamBuf(): - _pIstr(0) -{ -} - - -TeeStreamBuf::TeeStreamBuf(std::istream& istr): - _pIstr(&istr) -{ -} - - -TeeStreamBuf::TeeStreamBuf(std::ostream& ostr): - _pIstr(0) -{ - _streams.push_back(&ostr); -} - - -TeeStreamBuf::~TeeStreamBuf() -{ -} - - -void TeeStreamBuf::addStream(std::ostream& ostr) -{ - _streams.push_back(&ostr); -} - - -int TeeStreamBuf::readFromDevice() -{ - if (_pIstr) - { - int c = _pIstr->get(); - if (c != -1) writeToDevice((char) c); - return c; - } - return -1; -} - - -int TeeStreamBuf::writeToDevice(char c) -{ - for (StreamVec::iterator it = _streams.begin(); it != _streams.end(); ++it) - { - (*it)->put(c); - } - return charToInt(c); -} - - -TeeIOS::TeeIOS() -{ - poco_ios_init(&_buf); -} - - -TeeIOS::TeeIOS(std::istream& istr): _buf(istr) -{ - poco_ios_init(&_buf); -} - - -TeeIOS::TeeIOS(std::ostream& ostr): _buf(ostr) -{ - poco_ios_init(&_buf); -} - - -TeeIOS::~TeeIOS() -{ -} - - -void TeeIOS::addStream(std::ostream& ostr) -{ - _buf.addStream(ostr); -} - - -TeeStreamBuf* TeeIOS::rdbuf() -{ - return &_buf; -} - - -TeeInputStream::TeeInputStream(std::istream& istr): TeeIOS(istr), std::istream(&_buf) -{ -} - - -TeeInputStream::~TeeInputStream() -{ -} - - -TeeOutputStream::TeeOutputStream(): std::ostream(&_buf) -{ -} - - -TeeOutputStream::TeeOutputStream(std::ostream& ostr): TeeIOS(ostr), std::ostream(&_buf) -{ -} - - -TeeOutputStream::~TeeOutputStream() -{ -} - - -} // namespace Poco +// +// TeeStream.cpp +// +// $Id: //poco/1.2/Foundation/src/TeeStream.cpp#1 $ +// +// Library: Foundation +// Package: Streams +// Module: TeeStream +// +// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/TeeStream.h" + + +namespace Poco { + + +TeeStreamBuf::TeeStreamBuf(): + _pIstr(0) +{ +} + + +TeeStreamBuf::TeeStreamBuf(std::istream& istr): + _pIstr(&istr) +{ +} + + +TeeStreamBuf::TeeStreamBuf(std::ostream& ostr): + _pIstr(0) +{ + _streams.push_back(&ostr); +} + + +TeeStreamBuf::~TeeStreamBuf() +{ +} + + +void TeeStreamBuf::addStream(std::ostream& ostr) +{ + _streams.push_back(&ostr); +} + + +int TeeStreamBuf::readFromDevice() +{ + if (_pIstr) + { + int c = _pIstr->get(); + if (c != -1) writeToDevice((char) c); + return c; + } + return -1; +} + + +int TeeStreamBuf::writeToDevice(char c) +{ + for (StreamVec::iterator it = _streams.begin(); it != _streams.end(); ++it) + { + (*it)->put(c); + } + return charToInt(c); +} + + +TeeIOS::TeeIOS() +{ + poco_ios_init(&_buf); +} + + +TeeIOS::TeeIOS(std::istream& istr): _buf(istr) +{ + poco_ios_init(&_buf); +} + + +TeeIOS::TeeIOS(std::ostream& ostr): _buf(ostr) +{ + poco_ios_init(&_buf); +} + + +TeeIOS::~TeeIOS() +{ +} + + +void TeeIOS::addStream(std::ostream& ostr) +{ + _buf.addStream(ostr); +} + + +TeeStreamBuf* TeeIOS::rdbuf() +{ + return &_buf; +} + + +TeeInputStream::TeeInputStream(std::istream& istr): TeeIOS(istr), std::istream(&_buf) +{ +} + + +TeeInputStream::~TeeInputStream() +{ +} + + +TeeOutputStream::TeeOutputStream(): std::ostream(&_buf) +{ +} + + +TeeOutputStream::TeeOutputStream(std::ostream& ostr): TeeIOS(ostr), std::ostream(&_buf) +{ +} + + +TeeOutputStream::~TeeOutputStream() +{ +} + + +} // namespace Poco diff --git a/Foundation/src/TemporaryFile.cpp b/Foundation/src/TemporaryFile.cpp index 0abf61084..2a2d0d05d 100644 --- a/Foundation/src/TemporaryFile.cpp +++ b/Foundation/src/TemporaryFile.cpp @@ -1,144 +1,144 @@ -// -// TemporaryFile.cpp -// -// $Id: //poco/1.2/Foundation/src/TemporaryFile.cpp#1 $ -// -// Library: Foundation -// Package: Filesystem -// Module: TemporaryFile -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/TemporaryFile.h" -#include "Poco/Path.h" -#include "Poco/Exception.h" -#include "Poco/Process.h" -#include "Poco/Mutex.h" -#include -#include - - -namespace Poco { - - -class TempFileCollector -{ -public: - TempFileCollector() - { - } - - ~TempFileCollector() - { - for (std::set::iterator it = _files.begin(); it != _files.end(); ++it) - { - try - { - File f(*it); - f.remove(true); - } - catch (Exception&) - { - } - } - } - - void registerFile(const std::string& path) - { - FastMutex::ScopedLock lock(_mutex); - - Path p(path); - _files.insert(p.absolute().toString()); - } - -private: - std::set _files; - FastMutex _mutex; -}; - - -TemporaryFile::TemporaryFile(): File(tempName()), _keep(false) -{ -} - - -TemporaryFile::~TemporaryFile() -{ - if (!_keep) - { - try - { - remove(true); - } - catch (Exception&) - { - } - } -} - - -void TemporaryFile::keep() -{ - _keep = true; -} - - -void TemporaryFile::keepUntilExit() -{ - _keep = true; - registerForDeletion(path()); -} - - -void TemporaryFile::registerForDeletion(const std::string& path) -{ - static TempFileCollector fc; - fc.registerFile(path); -} - - -std::string TemporaryFile::tempName() -{ - std::ostringstream name; - static FastMutex mutex; - static unsigned long count = 0; - mutex.lock(); - unsigned long n = count++; - mutex.unlock(); - name << Path::temp(); - name << "tmp" << Process::id(); - for (int i = 0; i < 6; ++i) - { - name << char('a' + (n % 26)); - n /= 26; - } - return name.str(); -} - - -} // namespace Poco +// +// TemporaryFile.cpp +// +// $Id: //poco/1.2/Foundation/src/TemporaryFile.cpp#1 $ +// +// Library: Foundation +// Package: Filesystem +// Module: TemporaryFile +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/TemporaryFile.h" +#include "Poco/Path.h" +#include "Poco/Exception.h" +#include "Poco/Process.h" +#include "Poco/Mutex.h" +#include +#include + + +namespace Poco { + + +class TempFileCollector +{ +public: + TempFileCollector() + { + } + + ~TempFileCollector() + { + for (std::set::iterator it = _files.begin(); it != _files.end(); ++it) + { + try + { + File f(*it); + f.remove(true); + } + catch (Exception&) + { + } + } + } + + void registerFile(const std::string& path) + { + FastMutex::ScopedLock lock(_mutex); + + Path p(path); + _files.insert(p.absolute().toString()); + } + +private: + std::set _files; + FastMutex _mutex; +}; + + +TemporaryFile::TemporaryFile(): File(tempName()), _keep(false) +{ +} + + +TemporaryFile::~TemporaryFile() +{ + if (!_keep) + { + try + { + remove(true); + } + catch (Exception&) + { + } + } +} + + +void TemporaryFile::keep() +{ + _keep = true; +} + + +void TemporaryFile::keepUntilExit() +{ + _keep = true; + registerForDeletion(path()); +} + + +void TemporaryFile::registerForDeletion(const std::string& path) +{ + static TempFileCollector fc; + fc.registerFile(path); +} + + +std::string TemporaryFile::tempName() +{ + std::ostringstream name; + static FastMutex mutex; + static unsigned long count = 0; + mutex.lock(); + unsigned long n = count++; + mutex.unlock(); + name << Path::temp(); + name << "tmp" << Process::id(); + for (int i = 0; i < 6; ++i) + { + name << char('a' + (n % 26)); + n /= 26; + } + return name.str(); +} + + +} // namespace Poco diff --git a/Foundation/src/TextConverter.cpp b/Foundation/src/TextConverter.cpp index 231f5fc49..550df8320 100644 --- a/Foundation/src/TextConverter.cpp +++ b/Foundation/src/TextConverter.cpp @@ -1,127 +1,127 @@ -// -// TextConverter.cpp -// -// $Id: //poco/1.2/Foundation/src/TextConverter.cpp#1 $ -// -// Library: Foundation -// Package: Text -// Module: TextConverter -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/TextConverter.h" -#include "Poco/TextIterator.h" -#include "Poco/TextEncoding.h" - - -namespace Poco { - - -TextConverter::TextConverter(const TextEncoding& inEncoding, const TextEncoding& outEncoding, int defaultChar): - _inEncoding(inEncoding), - _outEncoding(outEncoding), - _defaultChar(defaultChar) -{ -} - - -TextConverter::~TextConverter() -{ -} - - -int TextConverter::convert(const std::string& source, std::string& destination) -{ - int errors = 0; - TextIterator it(source, _inEncoding); - TextIterator end(source); - unsigned char buffer[TextEncoding::MAX_SEQUENCE_LENGTH]; - - while (it != end) - { - int c = *it; - if (c == -1) { ++errors; c = _defaultChar; } - int n = _outEncoding.convert(c, buffer, sizeof(buffer)); - if (n == 0) n = _outEncoding.convert(_defaultChar, buffer, sizeof(buffer)); - poco_assert (n <= sizeof(buffer)); - destination.append((const char*) buffer, n); - ++it; - } - return errors; -} - - -int TextConverter::convert(const void* source, int length, std::string& destination) -{ - poco_check_ptr (source); - - int errors = 0; - const unsigned char* it = (const unsigned char*) source; - const unsigned char* end = (const unsigned char*) source + length; - unsigned char buffer[TextEncoding::MAX_SEQUENCE_LENGTH]; - - while (it < end) - { - unsigned char c = *it; - int n = _inEncoding.characterMap()[c]; - int uc; - if (n == -1) - { - ++errors; - uc = _defaultChar; - ++it; - } - else if (n >= 0) - { - uc = n; - ++it; - } - else - { - if (it - n <= end) - { - uc = _inEncoding.convert(it); - if (uc == -1) uc = _defaultChar; - } - else - { - ++errors; - uc = _defaultChar; - } - it -= n; - } - n = _outEncoding.convert(uc, buffer, sizeof(buffer)); - if (n == 0) n = _outEncoding.convert(_defaultChar, buffer, sizeof(buffer)); - poco_assert (n <= sizeof(buffer)); - destination.append((const char*) buffer, n); - } - return errors; -} - - -} // namespace Poco +// +// TextConverter.cpp +// +// $Id: //poco/1.2/Foundation/src/TextConverter.cpp#1 $ +// +// Library: Foundation +// Package: Text +// Module: TextConverter +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/TextConverter.h" +#include "Poco/TextIterator.h" +#include "Poco/TextEncoding.h" + + +namespace Poco { + + +TextConverter::TextConverter(const TextEncoding& inEncoding, const TextEncoding& outEncoding, int defaultChar): + _inEncoding(inEncoding), + _outEncoding(outEncoding), + _defaultChar(defaultChar) +{ +} + + +TextConverter::~TextConverter() +{ +} + + +int TextConverter::convert(const std::string& source, std::string& destination) +{ + int errors = 0; + TextIterator it(source, _inEncoding); + TextIterator end(source); + unsigned char buffer[TextEncoding::MAX_SEQUENCE_LENGTH]; + + while (it != end) + { + int c = *it; + if (c == -1) { ++errors; c = _defaultChar; } + int n = _outEncoding.convert(c, buffer, sizeof(buffer)); + if (n == 0) n = _outEncoding.convert(_defaultChar, buffer, sizeof(buffer)); + poco_assert (n <= sizeof(buffer)); + destination.append((const char*) buffer, n); + ++it; + } + return errors; +} + + +int TextConverter::convert(const void* source, int length, std::string& destination) +{ + poco_check_ptr (source); + + int errors = 0; + const unsigned char* it = (const unsigned char*) source; + const unsigned char* end = (const unsigned char*) source + length; + unsigned char buffer[TextEncoding::MAX_SEQUENCE_LENGTH]; + + while (it < end) + { + unsigned char c = *it; + int n = _inEncoding.characterMap()[c]; + int uc; + if (n == -1) + { + ++errors; + uc = _defaultChar; + ++it; + } + else if (n >= 0) + { + uc = n; + ++it; + } + else + { + if (it - n <= end) + { + uc = _inEncoding.convert(it); + if (uc == -1) uc = _defaultChar; + } + else + { + ++errors; + uc = _defaultChar; + } + it -= n; + } + n = _outEncoding.convert(uc, buffer, sizeof(buffer)); + if (n == 0) n = _outEncoding.convert(_defaultChar, buffer, sizeof(buffer)); + poco_assert (n <= sizeof(buffer)); + destination.append((const char*) buffer, n); + } + return errors; +} + + +} // namespace Poco diff --git a/Foundation/src/TextEncoding.cpp b/Foundation/src/TextEncoding.cpp index b4deea3a6..83a51a306 100644 --- a/Foundation/src/TextEncoding.cpp +++ b/Foundation/src/TextEncoding.cpp @@ -1,61 +1,61 @@ -// -// TextEncoding.cpp -// -// $Id: //poco/1.2/Foundation/src/TextEncoding.cpp#1 $ -// -// Library: Foundation -// Package: Text -// Module: TextEncoding -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/TextEncoding.h" - - -namespace Poco { - - -TextEncoding::~TextEncoding() -{ -} - - -int TextEncoding::convert(const unsigned char* bytes) const -{ - return (int) *bytes; -} - - -int TextEncoding::convert(int ch, unsigned char* bytes, int length) const -{ - return 0; -} - - -} // namespace Poco - +// +// TextEncoding.cpp +// +// $Id: //poco/1.2/Foundation/src/TextEncoding.cpp#1 $ +// +// Library: Foundation +// Package: Text +// Module: TextEncoding +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/TextEncoding.h" + + +namespace Poco { + + +TextEncoding::~TextEncoding() +{ +} + + +int TextEncoding::convert(const unsigned char* bytes) const +{ + return (int) *bytes; +} + + +int TextEncoding::convert(int ch, unsigned char* bytes, int length) const +{ + return 0; +} + + +} // namespace Poco + diff --git a/Foundation/src/TextIterator.cpp b/Foundation/src/TextIterator.cpp index 89787a250..0315aa2a2 100644 --- a/Foundation/src/TextIterator.cpp +++ b/Foundation/src/TextIterator.cpp @@ -1,163 +1,163 @@ -// -// TextIterator.cpp -// -// $Id: //poco/1.2/Foundation/src/TextIterator.cpp#1 $ -// -// Library: Foundation -// Package: Text -// Module: TextIterator -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/TextIterator.h" -#include "Poco/TextEncoding.h" -#include - - -namespace Poco { - - -TextIterator::TextIterator(): - _pEncoding(0) -{ -} - - -TextIterator::TextIterator(const std::string& str, const TextEncoding& encoding): - _pEncoding(&encoding), - _it(str.begin()), - _end(str.end()) -{ -} - -TextIterator::TextIterator(const std::string::const_iterator& begin, const std::string::const_iterator& end, const TextEncoding& encoding): - _pEncoding(&encoding), - _it(begin), - _end(end) -{ -} - - -TextIterator::TextIterator(const std::string& str): - _pEncoding(0), - _it(str.end()), - _end(str.end()) -{ -} - - -TextIterator::TextIterator(const std::string::const_iterator& end): - _pEncoding(0), - _it(end), - _end(end) -{ -} - - -TextIterator::~TextIterator() -{ -} - - -TextIterator::TextIterator(const TextIterator& it): - _pEncoding(it._pEncoding), - _it(it._it), - _end(it._end) -{ -} - - -TextIterator& TextIterator::operator = (const TextIterator& it) -{ - if (&it != this) - { - _pEncoding = it._pEncoding; - _it = it._it; - _end = it._end; - } - return *this; -} - - -void TextIterator::swap(TextIterator& it) -{ - std::swap(_pEncoding, it._pEncoding); - std::swap(_it, it._it); - std::swap(_end, it._end); -} - - -int TextIterator::operator * () const -{ - poco_check_ptr (_pEncoding); - poco_assert (_it != _end); - - unsigned char c = (unsigned char) *_it; - int n = _pEncoding->characterMap()[c]; - if (n >= -1) - return n; - else - { - poco_assert_dbg (n >= -TextEncoding::MAX_SEQUENCE_LENGTH); - unsigned char buffer[TextEncoding::MAX_SEQUENCE_LENGTH]; - unsigned char* p = buffer; - std::string::const_iterator it = _it; - while (n < 0 && it != _end) { *p++ = *it++; ++n; } - if (n == 0) - return _pEncoding->convert(buffer); - else - return -1; - } -} - - -TextIterator& TextIterator::operator ++ () -{ - poco_check_ptr (_pEncoding); - poco_assert (_it != _end); - - unsigned char c = (unsigned char) *_it; - int n = _pEncoding->characterMap()[c]; - if (n >= -1) - ++_it; - else - while (n < 0 && _it != _end) { ++_it; ++n; } - - return *this; -} - - -TextIterator TextIterator::operator ++ (int) -{ - TextIterator prev(*this); - operator ++ (); - return prev; -} - - -} // namespace Poco +// +// TextIterator.cpp +// +// $Id: //poco/1.2/Foundation/src/TextIterator.cpp#1 $ +// +// Library: Foundation +// Package: Text +// Module: TextIterator +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/TextIterator.h" +#include "Poco/TextEncoding.h" +#include + + +namespace Poco { + + +TextIterator::TextIterator(): + _pEncoding(0) +{ +} + + +TextIterator::TextIterator(const std::string& str, const TextEncoding& encoding): + _pEncoding(&encoding), + _it(str.begin()), + _end(str.end()) +{ +} + +TextIterator::TextIterator(const std::string::const_iterator& begin, const std::string::const_iterator& end, const TextEncoding& encoding): + _pEncoding(&encoding), + _it(begin), + _end(end) +{ +} + + +TextIterator::TextIterator(const std::string& str): + _pEncoding(0), + _it(str.end()), + _end(str.end()) +{ +} + + +TextIterator::TextIterator(const std::string::const_iterator& end): + _pEncoding(0), + _it(end), + _end(end) +{ +} + + +TextIterator::~TextIterator() +{ +} + + +TextIterator::TextIterator(const TextIterator& it): + _pEncoding(it._pEncoding), + _it(it._it), + _end(it._end) +{ +} + + +TextIterator& TextIterator::operator = (const TextIterator& it) +{ + if (&it != this) + { + _pEncoding = it._pEncoding; + _it = it._it; + _end = it._end; + } + return *this; +} + + +void TextIterator::swap(TextIterator& it) +{ + std::swap(_pEncoding, it._pEncoding); + std::swap(_it, it._it); + std::swap(_end, it._end); +} + + +int TextIterator::operator * () const +{ + poco_check_ptr (_pEncoding); + poco_assert (_it != _end); + + unsigned char c = (unsigned char) *_it; + int n = _pEncoding->characterMap()[c]; + if (n >= -1) + return n; + else + { + poco_assert_dbg (n >= -TextEncoding::MAX_SEQUENCE_LENGTH); + unsigned char buffer[TextEncoding::MAX_SEQUENCE_LENGTH]; + unsigned char* p = buffer; + std::string::const_iterator it = _it; + while (n < 0 && it != _end) { *p++ = *it++; ++n; } + if (n == 0) + return _pEncoding->convert(buffer); + else + return -1; + } +} + + +TextIterator& TextIterator::operator ++ () +{ + poco_check_ptr (_pEncoding); + poco_assert (_it != _end); + + unsigned char c = (unsigned char) *_it; + int n = _pEncoding->characterMap()[c]; + if (n >= -1) + ++_it; + else + while (n < 0 && _it != _end) { ++_it; ++n; } + + return *this; +} + + +TextIterator TextIterator::operator ++ (int) +{ + TextIterator prev(*this); + operator ++ (); + return prev; +} + + +} // namespace Poco diff --git a/Foundation/src/Thread.cpp b/Foundation/src/Thread.cpp index a8b3cdb65..9806cb519 100644 --- a/Foundation/src/Thread.cpp +++ b/Foundation/src/Thread.cpp @@ -1,143 +1,143 @@ -// -// Thread.cpp -// -// $Id: //poco/1.2/Foundation/src/Thread.cpp#1 $ -// -// Library: Foundation -// Package: Threading -// Module: Thread -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/Thread.h" -#include "Poco/Mutex.h" -#include "Poco/Exception.h" -#include "Poco/ThreadLocal.h" -#include - - -#if defined(POCO_OS_FAMILY_WINDOWS) -#include "Thread_WIN32.cpp" -#else -#include "Thread_POSIX.cpp" -#endif - - -namespace Poco { - - -Thread::Thread(): - _id(uniqueId()), - _name(makeName()), - _pTLS(0) -{ -} - - -Thread::Thread(const std::string& name): - _id(uniqueId()), - _name(name), - _pTLS(0) -{ -} - - -Thread::~Thread() -{ - delete _pTLS; -} - - -void Thread::setPriority(Priority prio) -{ - setPriorityImpl(prio); -} - - -Thread::Priority Thread::getPriority() const -{ - return Priority(getPriorityImpl()); -} - - -void Thread::start(Runnable& target) -{ - startImpl(target); -} - - -void Thread::join() -{ - joinImpl(); -} - - -ThreadLocalStorage& Thread::tls() -{ - if (!_pTLS) - _pTLS = new ThreadLocalStorage; - return *_pTLS; -} - - -void Thread::clearTLS() -{ - if (_pTLS) - { - delete _pTLS; - _pTLS = 0; - } -} - - -std::string Thread::makeName() -{ - std::ostringstream name; - name << '#' << _id; - return name.str(); -} - - -int Thread::uniqueId() -{ - static FastMutex mtx; - FastMutex::ScopedLock lock(mtx); - - static unsigned count = 0; - ++count; - return count; -} - - -void Thread::setName(const std::string& name) -{ - _name = name; -} - - -} // namespace Poco +// +// Thread.cpp +// +// $Id: //poco/1.2/Foundation/src/Thread.cpp#1 $ +// +// Library: Foundation +// Package: Threading +// Module: Thread +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/Thread.h" +#include "Poco/Mutex.h" +#include "Poco/Exception.h" +#include "Poco/ThreadLocal.h" +#include + + +#if defined(POCO_OS_FAMILY_WINDOWS) +#include "Thread_WIN32.cpp" +#else +#include "Thread_POSIX.cpp" +#endif + + +namespace Poco { + + +Thread::Thread(): + _id(uniqueId()), + _name(makeName()), + _pTLS(0) +{ +} + + +Thread::Thread(const std::string& name): + _id(uniqueId()), + _name(name), + _pTLS(0) +{ +} + + +Thread::~Thread() +{ + delete _pTLS; +} + + +void Thread::setPriority(Priority prio) +{ + setPriorityImpl(prio); +} + + +Thread::Priority Thread::getPriority() const +{ + return Priority(getPriorityImpl()); +} + + +void Thread::start(Runnable& target) +{ + startImpl(target); +} + + +void Thread::join() +{ + joinImpl(); +} + + +ThreadLocalStorage& Thread::tls() +{ + if (!_pTLS) + _pTLS = new ThreadLocalStorage; + return *_pTLS; +} + + +void Thread::clearTLS() +{ + if (_pTLS) + { + delete _pTLS; + _pTLS = 0; + } +} + + +std::string Thread::makeName() +{ + std::ostringstream name; + name << '#' << _id; + return name.str(); +} + + +int Thread::uniqueId() +{ + static FastMutex mtx; + FastMutex::ScopedLock lock(mtx); + + static unsigned count = 0; + ++count; + return count; +} + + +void Thread::setName(const std::string& name) +{ + _name = name; +} + + +} // namespace Poco diff --git a/Foundation/src/ThreadLocal.cpp b/Foundation/src/ThreadLocal.cpp index 7ff4da7da..995697d94 100644 --- a/Foundation/src/ThreadLocal.cpp +++ b/Foundation/src/ThreadLocal.cpp @@ -1,102 +1,102 @@ -// -// ThreadLocal.cpp -// -// $Id: //poco/1.2/Foundation/src/ThreadLocal.cpp#1 $ -// -// Library: Foundation -// Package: Threading -// Module: Thread -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/ThreadLocal.h" -#include "Poco/SingletonHolder.h" -#include "Poco/Thread.h" - - -namespace Poco { - - -TLSAbstractSlot::TLSAbstractSlot() -{ -} - - -TLSAbstractSlot::~TLSAbstractSlot() -{ -} - - -ThreadLocalStorage::ThreadLocalStorage() -{ -} - - -ThreadLocalStorage::~ThreadLocalStorage() -{ - for (TLSMap::iterator it = _map.begin(); it != _map.end(); ++it) - { - delete it->second; - } -} - - -TLSAbstractSlot*& ThreadLocalStorage::get(const void* key) -{ - TLSMap::iterator it = _map.find(key); - if (it == _map.end()) - return _map.insert(TLSMap::value_type(key, 0)).first->second; - else - return it->second; -} - - -ThreadLocalStorage& ThreadLocalStorage::current() -{ - Thread* pThread = Thread::current(); - if (pThread) - { - return pThread->tls(); - } - else - { - static SingletonHolder sh; - return *sh.get(); - } -} - - -void ThreadLocalStorage::clear() -{ - Thread* pThread = Thread::current(); - if (pThread) - pThread->clearTLS(); -} - - -} // namespace Poco +// +// ThreadLocal.cpp +// +// $Id: //poco/1.2/Foundation/src/ThreadLocal.cpp#1 $ +// +// Library: Foundation +// Package: Threading +// Module: Thread +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/ThreadLocal.h" +#include "Poco/SingletonHolder.h" +#include "Poco/Thread.h" + + +namespace Poco { + + +TLSAbstractSlot::TLSAbstractSlot() +{ +} + + +TLSAbstractSlot::~TLSAbstractSlot() +{ +} + + +ThreadLocalStorage::ThreadLocalStorage() +{ +} + + +ThreadLocalStorage::~ThreadLocalStorage() +{ + for (TLSMap::iterator it = _map.begin(); it != _map.end(); ++it) + { + delete it->second; + } +} + + +TLSAbstractSlot*& ThreadLocalStorage::get(const void* key) +{ + TLSMap::iterator it = _map.find(key); + if (it == _map.end()) + return _map.insert(TLSMap::value_type(key, 0)).first->second; + else + return it->second; +} + + +ThreadLocalStorage& ThreadLocalStorage::current() +{ + Thread* pThread = Thread::current(); + if (pThread) + { + return pThread->tls(); + } + else + { + static SingletonHolder sh; + return *sh.get(); + } +} + + +void ThreadLocalStorage::clear() +{ + Thread* pThread = Thread::current(); + if (pThread) + pThread->clearTLS(); +} + + +} // namespace Poco diff --git a/Foundation/src/ThreadPool.cpp b/Foundation/src/ThreadPool.cpp index aa9526866..519cf28f8 100644 --- a/Foundation/src/ThreadPool.cpp +++ b/Foundation/src/ThreadPool.cpp @@ -1,493 +1,493 @@ -// -// ThreadPool.cpp -// -// $Id: //poco/1.2/Foundation/src/ThreadPool.cpp#3 $ -// -// Library: Foundation -// Package: Threading -// Module: ThreadPool -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/ThreadPool.h" -#include "Poco/Runnable.h" -#include "Poco/Thread.h" -#include "Poco/Event.h" -#include "Poco/ThreadLocal.h" -#include "Poco/ErrorHandler.h" -#include -#include - - -namespace Poco { - - -class PooledThread: public Runnable -{ -public: - PooledThread(const std::string& name); - ~PooledThread(); - - void start(); - void start(Thread::Priority priority, Runnable& target); - void start(Thread::Priority priority, Runnable& target, const std::string& name); - bool idle(); - int idleTime(); - void join(); - void activate(); - void release(); - void run(); - -private: - volatile bool _idle; - volatile time_t _idleTime; - Runnable* _pTarget; - std::string _name; - Thread _thread; - Event _targetReady; - Event _targetCompleted; - Event _started; - FastMutex _mutex; -}; - - -PooledThread::PooledThread(const std::string& name): - _idle(true), - _idleTime(0), - _pTarget(0), - _name(name), - _thread(name) -{ - _idleTime = time(NULL); -} - - -PooledThread::~PooledThread() -{ -} - - -void PooledThread::start() -{ - _thread.start(*this); - _started.wait(); -} - - -void PooledThread::start(Thread::Priority priority, Runnable& target) -{ - FastMutex::ScopedLock lock(_mutex); - - poco_assert (_pTarget == 0); - - _pTarget = ⌖ - _thread.setPriority(priority); - _targetReady.set(); -} - - -void PooledThread::start(Thread::Priority priority, Runnable& target, const std::string& name) -{ - FastMutex::ScopedLock lock(_mutex); - - std::string fullName(name); - if (name.empty()) - { - fullName = _name; - } - else - { - fullName.append(" ("); - fullName.append(_name); - fullName.append(")"); - } - _thread.setName(fullName); - _thread.setPriority(priority); - - poco_assert (_pTarget == 0); - - _pTarget = ⌖ - _targetReady.set(); -} - - -inline bool PooledThread::idle() -{ - return _idle; -} - - -int PooledThread::idleTime() -{ - FastMutex::ScopedLock lock(_mutex); - - return (int) (time(NULL) - _idleTime); -} - - -void PooledThread::join() -{ - _mutex.lock(); - Runnable* pTarget = _pTarget; - _mutex.unlock(); - if (pTarget) - _targetCompleted.wait(); -} - - -void PooledThread::activate() -{ - FastMutex::ScopedLock lock(_mutex); - - poco_assert (_idle); - _idle = false; - _targetCompleted.reset(); -} - - -void PooledThread::release() -{ - _mutex.lock(); - _pTarget = 0; - _mutex.unlock(); - // In case of a statically allocated thread pool (such - // as the default thread pool), Windows may have already - // terminated the thread before we got here. - if (_thread.isRunning()) - _targetReady.set(); - else - delete this; -} - - -void PooledThread::run() -{ - _started.set(); - for (;;) - { - _targetReady.wait(); - _mutex.lock(); - if (_pTarget) // a NULL target means kill yourself - { - _mutex.unlock(); - try - { - _pTarget->run(); - } - catch (Exception& exc) - { - ErrorHandler::handle(exc); - } - catch (std::exception& exc) - { - ErrorHandler::handle(exc); - } - catch (...) - { - ErrorHandler::handle(); - } - FastMutex::ScopedLock lock(_mutex); - _pTarget = 0; - _idleTime = time(NULL); - _idle = true; - _targetCompleted.set(); - ThreadLocalStorage::clear(); - _thread.setName(_name); - _thread.setPriority(Thread::PRIO_NORMAL); - } - else - { - _mutex.unlock(); - break; - } - } - delete this; -} - - -ThreadPool::ThreadPool(int minCapacity, int maxCapacity, int idleTime): - _minCapacity(minCapacity), - _maxCapacity(maxCapacity), - _idleTime(idleTime), - _serial(0), - _age(0) -{ - poco_assert (minCapacity >= 1 && maxCapacity >= minCapacity && idleTime > 0); - - for (int i = 0; i < _minCapacity; i++) - { - PooledThread* pThread = createThread(); - _threads.push_back(pThread); - pThread->start(); - } -} - - -ThreadPool::ThreadPool(const std::string& name, int minCapacity, int maxCapacity, int idleTime): - _name(name), - _minCapacity(minCapacity), - _maxCapacity(maxCapacity), - _idleTime(idleTime), - _serial(0), - _age(0) -{ - poco_assert (minCapacity >= 1 && maxCapacity >= minCapacity && idleTime > 0); - - for (int i = 0; i < _minCapacity; i++) - { - PooledThread* pThread = createThread(); - _threads.push_back(pThread); - pThread->start(); - } -} - - -ThreadPool::~ThreadPool() -{ - stopAll(); -} - - -void ThreadPool::addCapacity(int n) -{ - FastMutex::ScopedLock lock(_mutex); - - poco_assert (_maxCapacity + n >= _minCapacity); - _maxCapacity += n; - housekeep(); -} - - -int ThreadPool::capacity() const -{ - FastMutex::ScopedLock lock(_mutex); - return _maxCapacity; -} - - -int ThreadPool::available() const -{ - FastMutex::ScopedLock lock(_mutex); - - int count = 0; - for (ThreadVec::const_iterator it = _threads.begin(); it != _threads.end(); ++it) - { - if ((*it)->idle()) ++count; - } - return (int) (count + _maxCapacity - _threads.size()); -} - - -int ThreadPool::used() const -{ - FastMutex::ScopedLock lock(_mutex); - - int count = 0; - for (ThreadVec::const_iterator it = _threads.begin(); it != _threads.end(); ++it) - { - if (!(*it)->idle()) ++count; - } - return count; -} - - -int ThreadPool::allocated() const -{ - FastMutex::ScopedLock lock(_mutex); - - return int(_threads.size()); -} - - -void ThreadPool::start(Runnable& target) -{ - getThread()->start(Thread::PRIO_NORMAL, target); -} - - -void ThreadPool::start(Runnable& target, const std::string& name) -{ - getThread()->start(Thread::PRIO_NORMAL, target, name); -} - - -void ThreadPool::startWithPriority(Thread::Priority priority, Runnable& target) -{ - getThread()->start(priority, target); -} - - -void ThreadPool::startWithPriority(Thread::Priority priority, Runnable& target, const std::string& name) -{ - getThread()->start(priority, target, name); -} - - -void ThreadPool::stopAll() -{ - FastMutex::ScopedLock lock(_mutex); - - for (ThreadVec::iterator it = _threads.begin(); it != _threads.end(); ++it) - { - (*it)->release(); - } - _threads.clear(); -} - - -void ThreadPool::joinAll() -{ - FastMutex::ScopedLock lock(_mutex); - - for (ThreadVec::iterator it = _threads.begin(); it != _threads.end(); ++it) - { - (*it)->join(); - } - housekeep(); -} - - -void ThreadPool::collect() -{ - FastMutex::ScopedLock lock(_mutex); - housekeep(); -} - - -void ThreadPool::housekeep() -{ - _age = 0; - if (_threads.size() <= _minCapacity) - return; - - ThreadVec idleThreads; - ThreadVec expiredThreads; - ThreadVec activeThreads; - idleThreads.reserve(_threads.size()); - activeThreads.reserve(_threads.size()); - - for (ThreadVec::iterator it = _threads.begin(); it != _threads.end(); ++it) - { - if ((*it)->idle()) - { - if ((*it)->idleTime() < _idleTime) - idleThreads.push_back(*it); - else - expiredThreads.push_back(*it); - } - else activeThreads.push_back(*it); - } - int n = (int) activeThreads.size(); - int limit = (int) idleThreads.size() + n; - if (limit < _minCapacity) limit = _minCapacity; - idleThreads.insert(idleThreads.end(), expiredThreads.begin(), expiredThreads.end()); - _threads.clear(); - for (ThreadVec::iterator it = idleThreads.begin(); it != idleThreads.end(); ++it) - { - if (n < limit) - { - _threads.push_back(*it); - ++n; - } - else (*it)->release(); - } - _threads.insert(_threads.end(), activeThreads.begin(), activeThreads.end()); -} - - -PooledThread* ThreadPool::getThread() -{ - FastMutex::ScopedLock lock(_mutex); - - if (++_age == 32) - housekeep(); - - PooledThread* pThread = 0; - for (ThreadVec::iterator it = _threads.begin(); !pThread && it != _threads.end(); ++it) - { - if ((*it)->idle()) pThread = *it; - } - if (!pThread) - { - if (_threads.size() < _maxCapacity) - { - pThread = createThread(); - _threads.push_back(pThread); - pThread->start(); - } - else throw NoThreadAvailableException(); - } - pThread->activate(); - return pThread; -} - - -PooledThread* ThreadPool::createThread() -{ - std::ostringstream name; - name << _name << "[#" << ++_serial << "]"; - return new PooledThread(name.str()); -} - - -class ThreadPoolSingletonHolder -{ -public: - ThreadPoolSingletonHolder() - { - _pPool = 0; - } - ~ThreadPoolSingletonHolder() - { - delete _pPool; - } - ThreadPool* pool() - { - FastMutex::ScopedLock lock(_mutex); - - if (!_pPool) - { - _pPool = new ThreadPool("default"); - } - return _pPool; - } - -private: - ThreadPool* _pPool; - FastMutex _mutex; -}; - - -ThreadPool& ThreadPool::defaultPool() -{ - static ThreadPoolSingletonHolder sh; - return *sh.pool(); -} - - -} // namespace Poco +// +// ThreadPool.cpp +// +// $Id: //poco/1.2/Foundation/src/ThreadPool.cpp#3 $ +// +// Library: Foundation +// Package: Threading +// Module: ThreadPool +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/ThreadPool.h" +#include "Poco/Runnable.h" +#include "Poco/Thread.h" +#include "Poco/Event.h" +#include "Poco/ThreadLocal.h" +#include "Poco/ErrorHandler.h" +#include +#include + + +namespace Poco { + + +class PooledThread: public Runnable +{ +public: + PooledThread(const std::string& name); + ~PooledThread(); + + void start(); + void start(Thread::Priority priority, Runnable& target); + void start(Thread::Priority priority, Runnable& target, const std::string& name); + bool idle(); + int idleTime(); + void join(); + void activate(); + void release(); + void run(); + +private: + volatile bool _idle; + volatile time_t _idleTime; + Runnable* _pTarget; + std::string _name; + Thread _thread; + Event _targetReady; + Event _targetCompleted; + Event _started; + FastMutex _mutex; +}; + + +PooledThread::PooledThread(const std::string& name): + _idle(true), + _idleTime(0), + _pTarget(0), + _name(name), + _thread(name) +{ + _idleTime = time(NULL); +} + + +PooledThread::~PooledThread() +{ +} + + +void PooledThread::start() +{ + _thread.start(*this); + _started.wait(); +} + + +void PooledThread::start(Thread::Priority priority, Runnable& target) +{ + FastMutex::ScopedLock lock(_mutex); + + poco_assert (_pTarget == 0); + + _pTarget = ⌖ + _thread.setPriority(priority); + _targetReady.set(); +} + + +void PooledThread::start(Thread::Priority priority, Runnable& target, const std::string& name) +{ + FastMutex::ScopedLock lock(_mutex); + + std::string fullName(name); + if (name.empty()) + { + fullName = _name; + } + else + { + fullName.append(" ("); + fullName.append(_name); + fullName.append(")"); + } + _thread.setName(fullName); + _thread.setPriority(priority); + + poco_assert (_pTarget == 0); + + _pTarget = ⌖ + _targetReady.set(); +} + + +inline bool PooledThread::idle() +{ + return _idle; +} + + +int PooledThread::idleTime() +{ + FastMutex::ScopedLock lock(_mutex); + + return (int) (time(NULL) - _idleTime); +} + + +void PooledThread::join() +{ + _mutex.lock(); + Runnable* pTarget = _pTarget; + _mutex.unlock(); + if (pTarget) + _targetCompleted.wait(); +} + + +void PooledThread::activate() +{ + FastMutex::ScopedLock lock(_mutex); + + poco_assert (_idle); + _idle = false; + _targetCompleted.reset(); +} + + +void PooledThread::release() +{ + _mutex.lock(); + _pTarget = 0; + _mutex.unlock(); + // In case of a statically allocated thread pool (such + // as the default thread pool), Windows may have already + // terminated the thread before we got here. + if (_thread.isRunning()) + _targetReady.set(); + else + delete this; +} + + +void PooledThread::run() +{ + _started.set(); + for (;;) + { + _targetReady.wait(); + _mutex.lock(); + if (_pTarget) // a NULL target means kill yourself + { + _mutex.unlock(); + try + { + _pTarget->run(); + } + catch (Exception& exc) + { + ErrorHandler::handle(exc); + } + catch (std::exception& exc) + { + ErrorHandler::handle(exc); + } + catch (...) + { + ErrorHandler::handle(); + } + FastMutex::ScopedLock lock(_mutex); + _pTarget = 0; + _idleTime = time(NULL); + _idle = true; + _targetCompleted.set(); + ThreadLocalStorage::clear(); + _thread.setName(_name); + _thread.setPriority(Thread::PRIO_NORMAL); + } + else + { + _mutex.unlock(); + break; + } + } + delete this; +} + + +ThreadPool::ThreadPool(int minCapacity, int maxCapacity, int idleTime): + _minCapacity(minCapacity), + _maxCapacity(maxCapacity), + _idleTime(idleTime), + _serial(0), + _age(0) +{ + poco_assert (minCapacity >= 1 && maxCapacity >= minCapacity && idleTime > 0); + + for (int i = 0; i < _minCapacity; i++) + { + PooledThread* pThread = createThread(); + _threads.push_back(pThread); + pThread->start(); + } +} + + +ThreadPool::ThreadPool(const std::string& name, int minCapacity, int maxCapacity, int idleTime): + _name(name), + _minCapacity(minCapacity), + _maxCapacity(maxCapacity), + _idleTime(idleTime), + _serial(0), + _age(0) +{ + poco_assert (minCapacity >= 1 && maxCapacity >= minCapacity && idleTime > 0); + + for (int i = 0; i < _minCapacity; i++) + { + PooledThread* pThread = createThread(); + _threads.push_back(pThread); + pThread->start(); + } +} + + +ThreadPool::~ThreadPool() +{ + stopAll(); +} + + +void ThreadPool::addCapacity(int n) +{ + FastMutex::ScopedLock lock(_mutex); + + poco_assert (_maxCapacity + n >= _minCapacity); + _maxCapacity += n; + housekeep(); +} + + +int ThreadPool::capacity() const +{ + FastMutex::ScopedLock lock(_mutex); + return _maxCapacity; +} + + +int ThreadPool::available() const +{ + FastMutex::ScopedLock lock(_mutex); + + int count = 0; + for (ThreadVec::const_iterator it = _threads.begin(); it != _threads.end(); ++it) + { + if ((*it)->idle()) ++count; + } + return (int) (count + _maxCapacity - _threads.size()); +} + + +int ThreadPool::used() const +{ + FastMutex::ScopedLock lock(_mutex); + + int count = 0; + for (ThreadVec::const_iterator it = _threads.begin(); it != _threads.end(); ++it) + { + if (!(*it)->idle()) ++count; + } + return count; +} + + +int ThreadPool::allocated() const +{ + FastMutex::ScopedLock lock(_mutex); + + return int(_threads.size()); +} + + +void ThreadPool::start(Runnable& target) +{ + getThread()->start(Thread::PRIO_NORMAL, target); +} + + +void ThreadPool::start(Runnable& target, const std::string& name) +{ + getThread()->start(Thread::PRIO_NORMAL, target, name); +} + + +void ThreadPool::startWithPriority(Thread::Priority priority, Runnable& target) +{ + getThread()->start(priority, target); +} + + +void ThreadPool::startWithPriority(Thread::Priority priority, Runnable& target, const std::string& name) +{ + getThread()->start(priority, target, name); +} + + +void ThreadPool::stopAll() +{ + FastMutex::ScopedLock lock(_mutex); + + for (ThreadVec::iterator it = _threads.begin(); it != _threads.end(); ++it) + { + (*it)->release(); + } + _threads.clear(); +} + + +void ThreadPool::joinAll() +{ + FastMutex::ScopedLock lock(_mutex); + + for (ThreadVec::iterator it = _threads.begin(); it != _threads.end(); ++it) + { + (*it)->join(); + } + housekeep(); +} + + +void ThreadPool::collect() +{ + FastMutex::ScopedLock lock(_mutex); + housekeep(); +} + + +void ThreadPool::housekeep() +{ + _age = 0; + if (_threads.size() <= _minCapacity) + return; + + ThreadVec idleThreads; + ThreadVec expiredThreads; + ThreadVec activeThreads; + idleThreads.reserve(_threads.size()); + activeThreads.reserve(_threads.size()); + + for (ThreadVec::iterator it = _threads.begin(); it != _threads.end(); ++it) + { + if ((*it)->idle()) + { + if ((*it)->idleTime() < _idleTime) + idleThreads.push_back(*it); + else + expiredThreads.push_back(*it); + } + else activeThreads.push_back(*it); + } + int n = (int) activeThreads.size(); + int limit = (int) idleThreads.size() + n; + if (limit < _minCapacity) limit = _minCapacity; + idleThreads.insert(idleThreads.end(), expiredThreads.begin(), expiredThreads.end()); + _threads.clear(); + for (ThreadVec::iterator it = idleThreads.begin(); it != idleThreads.end(); ++it) + { + if (n < limit) + { + _threads.push_back(*it); + ++n; + } + else (*it)->release(); + } + _threads.insert(_threads.end(), activeThreads.begin(), activeThreads.end()); +} + + +PooledThread* ThreadPool::getThread() +{ + FastMutex::ScopedLock lock(_mutex); + + if (++_age == 32) + housekeep(); + + PooledThread* pThread = 0; + for (ThreadVec::iterator it = _threads.begin(); !pThread && it != _threads.end(); ++it) + { + if ((*it)->idle()) pThread = *it; + } + if (!pThread) + { + if (_threads.size() < _maxCapacity) + { + pThread = createThread(); + _threads.push_back(pThread); + pThread->start(); + } + else throw NoThreadAvailableException(); + } + pThread->activate(); + return pThread; +} + + +PooledThread* ThreadPool::createThread() +{ + std::ostringstream name; + name << _name << "[#" << ++_serial << "]"; + return new PooledThread(name.str()); +} + + +class ThreadPoolSingletonHolder +{ +public: + ThreadPoolSingletonHolder() + { + _pPool = 0; + } + ~ThreadPoolSingletonHolder() + { + delete _pPool; + } + ThreadPool* pool() + { + FastMutex::ScopedLock lock(_mutex); + + if (!_pPool) + { + _pPool = new ThreadPool("default"); + } + return _pPool; + } + +private: + ThreadPool* _pPool; + FastMutex _mutex; +}; + + +ThreadPool& ThreadPool::defaultPool() +{ + static ThreadPoolSingletonHolder sh; + return *sh.pool(); +} + + +} // namespace Poco diff --git a/Foundation/src/Thread_POSIX.cpp b/Foundation/src/Thread_POSIX.cpp index d96cc3ffb..bcafac14d 100644 --- a/Foundation/src/Thread_POSIX.cpp +++ b/Foundation/src/Thread_POSIX.cpp @@ -1,221 +1,221 @@ -// -// Thread_POSIX.cpp -// -// $Id: //poco/1.2/Foundation/src/Thread_POSIX.cpp#1 $ -// -// Library: Foundation -// Package: Threading -// Module: Thread -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/Thread_POSIX.h" -#include "Poco/Exception.h" -#include "Poco/ErrorHandler.h" -#include - - -// -// Block SIGPIPE in main thread. -// -#if defined(POCO_OS_FAMILY_UNIX) -namespace -{ - class SignalBlocker - { - public: - SignalBlocker() - { - sigset_t sset; - sigemptyset(&sset); - sigaddset(&sset, SIGPIPE); - pthread_sigmask(SIG_BLOCK, &sset, 0); - } - ~SignalBlocker() - { - } - }; - - static SignalBlocker signalBlocker; -} -#endif - - -namespace Poco { - - -pthread_key_t ThreadImpl::_currentKey; -bool ThreadImpl::_haveCurrentKey = false; - - -ThreadImpl::ThreadImpl(): - _pTarget(0), - _thread(0), - _prio(PRIO_NORMAL_IMPL) -{ - if (!_haveCurrentKey) - { - if (pthread_key_create(&_currentKey, NULL)) - throw SystemException("cannot allocate thread context key"); - _haveCurrentKey = true; - } -} - - -ThreadImpl::~ThreadImpl() -{ - if (_pTarget) - pthread_detach(_thread); -} - - -void ThreadImpl::setPriorityImpl(int prio) -{ - if (prio != _prio) - { - _prio = prio; - if (_pTarget) - { - struct sched_param par; - par.sched_priority = mapPrio(_prio); - if (pthread_setschedparam(_thread, SCHED_OTHER, &par)) - throw SystemException("cannot set thread priority"); - } - } -} - - -void ThreadImpl::startImpl(Runnable& target) -{ - if (_pTarget) throw SystemException("thread already running"); - - _pTarget = ⌖ - if (pthread_create(&_thread, NULL, entry, this)) - { - _pTarget = 0; - throw SystemException("cannot start thread"); - } - - if (_prio != PRIO_NORMAL_IMPL) - { - struct sched_param par; - par.sched_priority = mapPrio(_prio); - if (pthread_setschedparam(_thread, SCHED_OTHER, &par)) - throw SystemException("cannot set thread priority"); - } -} - - -void ThreadImpl::joinImpl() -{ - if (!_pTarget) return; - void* result; - if (pthread_join(_thread, &result)) - throw SystemException("cannot join thread"); - _pTarget = 0; -} - - -bool ThreadImpl::isRunningImpl() const -{ - return _pTarget != 0; -} - - -ThreadImpl* ThreadImpl::currentImpl() -{ - if (_haveCurrentKey) - return (ThreadImpl*) pthread_getspecific(_currentKey); - else - return 0; -} - - -void* ThreadImpl::entry(void* pThread) -{ - pthread_setspecific(_currentKey, pThread); - -#if defined(POCO_OS_FAMILY_UNIX) - sigset_t sset; - sigemptyset(&sset); - sigaddset(&sset, SIGQUIT); - sigaddset(&sset, SIGTERM); - sigaddset(&sset, SIGPIPE); - pthread_sigmask(SIG_BLOCK, &sset, 0); -#endif - - try - { - reinterpret_cast(pThread)->_pTarget->run(); - } - catch (Exception& exc) - { - ErrorHandler::handle(exc); - } - catch (std::exception& exc) - { - ErrorHandler::handle(exc); - } - catch (...) - { - ErrorHandler::handle(); - } - return 0; -} - - -int ThreadImpl::mapPrio(int prio) -{ -#if defined(__VMS) || defined(__digital__) - static const int pmin = PRI_OTHER_MIN; - static const int pmax = PRI_OTHER_MAX; -#else - static const int pmin = sched_get_priority_min(SCHED_OTHER); - static const int pmax = sched_get_priority_max(SCHED_OTHER); -#endif - - switch (prio) - { - case PRIO_LOWEST_IMPL: - return pmin; - case PRIO_LOW_IMPL: - return pmin + (pmax - pmin)/4; - case PRIO_NORMAL_IMPL: - return pmin + (pmax - pmin)/2; - case PRIO_HIGH_IMPL: - return pmin + 3*(pmax - pmin)/4; - case PRIO_HIGHEST_IMPL: - return pmax; - default: - poco_bugcheck_msg("invalid thread priority"); - } - return -1; // just to satisfy compiler - we'll never get here anyway -} - - -} // namespace Poco +// +// Thread_POSIX.cpp +// +// $Id: //poco/1.2/Foundation/src/Thread_POSIX.cpp#1 $ +// +// Library: Foundation +// Package: Threading +// Module: Thread +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/Thread_POSIX.h" +#include "Poco/Exception.h" +#include "Poco/ErrorHandler.h" +#include + + +// +// Block SIGPIPE in main thread. +// +#if defined(POCO_OS_FAMILY_UNIX) +namespace +{ + class SignalBlocker + { + public: + SignalBlocker() + { + sigset_t sset; + sigemptyset(&sset); + sigaddset(&sset, SIGPIPE); + pthread_sigmask(SIG_BLOCK, &sset, 0); + } + ~SignalBlocker() + { + } + }; + + static SignalBlocker signalBlocker; +} +#endif + + +namespace Poco { + + +pthread_key_t ThreadImpl::_currentKey; +bool ThreadImpl::_haveCurrentKey = false; + + +ThreadImpl::ThreadImpl(): + _pTarget(0), + _thread(0), + _prio(PRIO_NORMAL_IMPL) +{ + if (!_haveCurrentKey) + { + if (pthread_key_create(&_currentKey, NULL)) + throw SystemException("cannot allocate thread context key"); + _haveCurrentKey = true; + } +} + + +ThreadImpl::~ThreadImpl() +{ + if (_pTarget) + pthread_detach(_thread); +} + + +void ThreadImpl::setPriorityImpl(int prio) +{ + if (prio != _prio) + { + _prio = prio; + if (_pTarget) + { + struct sched_param par; + par.sched_priority = mapPrio(_prio); + if (pthread_setschedparam(_thread, SCHED_OTHER, &par)) + throw SystemException("cannot set thread priority"); + } + } +} + + +void ThreadImpl::startImpl(Runnable& target) +{ + if (_pTarget) throw SystemException("thread already running"); + + _pTarget = ⌖ + if (pthread_create(&_thread, NULL, entry, this)) + { + _pTarget = 0; + throw SystemException("cannot start thread"); + } + + if (_prio != PRIO_NORMAL_IMPL) + { + struct sched_param par; + par.sched_priority = mapPrio(_prio); + if (pthread_setschedparam(_thread, SCHED_OTHER, &par)) + throw SystemException("cannot set thread priority"); + } +} + + +void ThreadImpl::joinImpl() +{ + if (!_pTarget) return; + void* result; + if (pthread_join(_thread, &result)) + throw SystemException("cannot join thread"); + _pTarget = 0; +} + + +bool ThreadImpl::isRunningImpl() const +{ + return _pTarget != 0; +} + + +ThreadImpl* ThreadImpl::currentImpl() +{ + if (_haveCurrentKey) + return (ThreadImpl*) pthread_getspecific(_currentKey); + else + return 0; +} + + +void* ThreadImpl::entry(void* pThread) +{ + pthread_setspecific(_currentKey, pThread); + +#if defined(POCO_OS_FAMILY_UNIX) + sigset_t sset; + sigemptyset(&sset); + sigaddset(&sset, SIGQUIT); + sigaddset(&sset, SIGTERM); + sigaddset(&sset, SIGPIPE); + pthread_sigmask(SIG_BLOCK, &sset, 0); +#endif + + try + { + reinterpret_cast(pThread)->_pTarget->run(); + } + catch (Exception& exc) + { + ErrorHandler::handle(exc); + } + catch (std::exception& exc) + { + ErrorHandler::handle(exc); + } + catch (...) + { + ErrorHandler::handle(); + } + return 0; +} + + +int ThreadImpl::mapPrio(int prio) +{ +#if defined(__VMS) || defined(__digital__) + static const int pmin = PRI_OTHER_MIN; + static const int pmax = PRI_OTHER_MAX; +#else + static const int pmin = sched_get_priority_min(SCHED_OTHER); + static const int pmax = sched_get_priority_max(SCHED_OTHER); +#endif + + switch (prio) + { + case PRIO_LOWEST_IMPL: + return pmin; + case PRIO_LOW_IMPL: + return pmin + (pmax - pmin)/4; + case PRIO_NORMAL_IMPL: + return pmin + (pmax - pmin)/2; + case PRIO_HIGH_IMPL: + return pmin + 3*(pmax - pmin)/4; + case PRIO_HIGHEST_IMPL: + return pmax; + default: + poco_bugcheck_msg("invalid thread priority"); + } + return -1; // just to satisfy compiler - we'll never get here anyway +} + + +} // namespace Poco diff --git a/Foundation/src/Thread_WIN32.cpp b/Foundation/src/Thread_WIN32.cpp index 23fb3095a..c171c9418 100644 --- a/Foundation/src/Thread_WIN32.cpp +++ b/Foundation/src/Thread_WIN32.cpp @@ -1,160 +1,160 @@ -// -// Thread_WIN32.h -// -// $Id: //poco/1.2/Foundation/src/Thread_WIN32.cpp#1 $ -// -// Library: Foundation -// Package: Threading -// Module: Thread -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/Thread_WIN32.h" -#include "Poco/Exception.h" -#include "Poco/ErrorHandler.h" -#include - - -namespace Poco { - - -DWORD ThreadImpl::_currentKey = TLS_OUT_OF_INDEXES; - - -ThreadImpl::ThreadImpl(): _pTarget(0), _thread(0), _prio(PRIO_NORMAL_IMPL) -{ - if (_currentKey == TLS_OUT_OF_INDEXES) - { - _currentKey = TlsAlloc(); - if (_currentKey == TLS_OUT_OF_INDEXES) - throw SystemException("cannot allocate thread context key"); - } -} - - -ThreadImpl::~ThreadImpl() -{ - if (_thread) CloseHandle(_thread); -} - - -void ThreadImpl::setPriorityImpl(int prio) -{ - if (prio != _prio) - { - _prio = prio; - if (_thread) - { - if (SetThreadPriority(_thread, _prio) == 0) - throw SystemException("cannot set thread priority"); - } - } -} - - -void ThreadImpl::startImpl(Runnable& target) -{ - if (_thread) throw SystemException("thread already running"); - - _pTarget = ⌖ -#if defined(_DLL) - DWORD threadId; - _thread = CreateThread(NULL, 0, entry, this, 0, &threadId); -#else - unsigned threadId; - _thread = (HANDLE) _beginthreadex(NULL, 0, entry, this, 0, &threadId); -#endif - if (!_thread) - throw SystemException("cannot create thread"); - if (_prio != PRIO_NORMAL_IMPL && !SetThreadPriority(_thread, _prio)) - throw SystemException("cannot set thread priority"); -} - - -void ThreadImpl::joinImpl() -{ - if (!_thread) return; - - switch (WaitForSingleObject(_thread, INFINITE)) - { - case WAIT_OBJECT_0: - return; - default: - throw SystemException("cannot join thread"); - } -} - - -bool ThreadImpl::isRunningImpl() const -{ - if (_thread) - { - DWORD ec = 0; - return GetExitCodeThread(_thread, &ec) && ec == STILL_ACTIVE; - } - return false; -} - - -ThreadImpl* ThreadImpl::currentImpl() -{ - if (_currentKey == TLS_OUT_OF_INDEXES) - return 0; - else - return (ThreadImpl*) TlsGetValue(_currentKey); -} - - -#if defined(_DLL) -DWORD WINAPI ThreadImpl::entry(LPVOID pThread) -#else -unsigned __stdcall ThreadImpl::entry(void* pThread) -#endif -{ - TlsSetValue(_currentKey, pThread); - try - { - reinterpret_cast(pThread)->_pTarget->run(); - } - catch (Exception& exc) - { - ErrorHandler::handle(exc); - } - catch (std::exception& exc) - { - ErrorHandler::handle(exc); - } - catch (...) - { - ErrorHandler::handle(); - } - return 0; -} - - -} // namespace Poco +// +// Thread_WIN32.h +// +// $Id: //poco/1.2/Foundation/src/Thread_WIN32.cpp#1 $ +// +// Library: Foundation +// Package: Threading +// Module: Thread +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/Thread_WIN32.h" +#include "Poco/Exception.h" +#include "Poco/ErrorHandler.h" +#include + + +namespace Poco { + + +DWORD ThreadImpl::_currentKey = TLS_OUT_OF_INDEXES; + + +ThreadImpl::ThreadImpl(): _pTarget(0), _thread(0), _prio(PRIO_NORMAL_IMPL) +{ + if (_currentKey == TLS_OUT_OF_INDEXES) + { + _currentKey = TlsAlloc(); + if (_currentKey == TLS_OUT_OF_INDEXES) + throw SystemException("cannot allocate thread context key"); + } +} + + +ThreadImpl::~ThreadImpl() +{ + if (_thread) CloseHandle(_thread); +} + + +void ThreadImpl::setPriorityImpl(int prio) +{ + if (prio != _prio) + { + _prio = prio; + if (_thread) + { + if (SetThreadPriority(_thread, _prio) == 0) + throw SystemException("cannot set thread priority"); + } + } +} + + +void ThreadImpl::startImpl(Runnable& target) +{ + if (_thread) throw SystemException("thread already running"); + + _pTarget = ⌖ +#if defined(_DLL) + DWORD threadId; + _thread = CreateThread(NULL, 0, entry, this, 0, &threadId); +#else + unsigned threadId; + _thread = (HANDLE) _beginthreadex(NULL, 0, entry, this, 0, &threadId); +#endif + if (!_thread) + throw SystemException("cannot create thread"); + if (_prio != PRIO_NORMAL_IMPL && !SetThreadPriority(_thread, _prio)) + throw SystemException("cannot set thread priority"); +} + + +void ThreadImpl::joinImpl() +{ + if (!_thread) return; + + switch (WaitForSingleObject(_thread, INFINITE)) + { + case WAIT_OBJECT_0: + return; + default: + throw SystemException("cannot join thread"); + } +} + + +bool ThreadImpl::isRunningImpl() const +{ + if (_thread) + { + DWORD ec = 0; + return GetExitCodeThread(_thread, &ec) && ec == STILL_ACTIVE; + } + return false; +} + + +ThreadImpl* ThreadImpl::currentImpl() +{ + if (_currentKey == TLS_OUT_OF_INDEXES) + return 0; + else + return (ThreadImpl*) TlsGetValue(_currentKey); +} + + +#if defined(_DLL) +DWORD WINAPI ThreadImpl::entry(LPVOID pThread) +#else +unsigned __stdcall ThreadImpl::entry(void* pThread) +#endif +{ + TlsSetValue(_currentKey, pThread); + try + { + reinterpret_cast(pThread)->_pTarget->run(); + } + catch (Exception& exc) + { + ErrorHandler::handle(exc); + } + catch (std::exception& exc) + { + ErrorHandler::handle(exc); + } + catch (...) + { + ErrorHandler::handle(); + } + return 0; +} + + +} // namespace Poco diff --git a/Foundation/src/Timer.cpp b/Foundation/src/Timer.cpp index 106979142..d17b85213 100644 --- a/Foundation/src/Timer.cpp +++ b/Foundation/src/Timer.cpp @@ -1,210 +1,210 @@ -// -// Timer.cpp -// -// $Id: //poco/1.2/Foundation/src/Timer.cpp#1 $ -// -// Library: Foundation -// Package: Threading -// Module: Timer -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/Timer.h" -#include "Poco/ThreadPool.h" -#include "Poco/Exception.h" -#include "Poco/ErrorHandler.h" - - -namespace Poco { - - -Timer::Timer(long startInterval, long periodicInterval): - _startInterval(startInterval), - _periodicInterval(periodicInterval), - _pCallback(0) -{ - poco_assert (startInterval >= 0 && periodicInterval >= 0); -} - - -Timer::~Timer() -{ - stop(); -} - - -void Timer::start(const AbstractTimerCallback& method) -{ - start(method, ThreadPool::defaultPool()); -} - - -void Timer::start(const AbstractTimerCallback& method, ThreadPool& threadPool) -{ - poco_assert (!_pCallback); - - FastMutex::ScopedLock lock(_mutex); - _pCallback = method.clone(); - _wakeUp.reset(); - threadPool.start(*this); -} - - -void Timer::stop() -{ - FastMutex::ScopedLock lock(_mutex); - if (_pCallback) - { - _periodicInterval = 0; - _mutex.unlock(); - _wakeUp.set(); - _done.wait(); // warning: deadlock if called from timer callback - _mutex.lock(); - delete _pCallback; - _pCallback = 0; - } -} - - -void Timer::restart() -{ - FastMutex::ScopedLock lock(_mutex); - if (_pCallback) - { - _wakeUp.set(); - } -} - - -void Timer::restart(long milliseconds) -{ - poco_assert (milliseconds >= 0); - FastMutex::ScopedLock lock(_mutex); - if (_pCallback) - { - _periodicInterval = milliseconds; - _wakeUp.set(); - } -} - - -long Timer::getStartInterval() const -{ - FastMutex::ScopedLock lock(_mutex); - return _startInterval; -} - - -void Timer::setStartInterval(long milliseconds) -{ - poco_assert (milliseconds >= 0); - FastMutex::ScopedLock lock(_mutex); - _startInterval = milliseconds; -} - - -long Timer::getPeriodicInterval() const -{ - FastMutex::ScopedLock lock(_mutex); - return _periodicInterval; -} - - -void Timer::setPeriodicInterval(long milliseconds) -{ - poco_assert (milliseconds >= 0); - FastMutex::ScopedLock lock(_mutex); - _periodicInterval = milliseconds; -} - - -void Timer::run() -{ - long interval; - { - FastMutex::ScopedLock lock(_mutex); - interval = _startInterval; - } - do - { - if (_wakeUp.tryWait(interval)) - { - FastMutex::ScopedLock lock(_mutex); - interval = _periodicInterval; - } - else - { - try - { - _pCallback->invoke(*this); - } - catch (Exception& exc) - { - ErrorHandler::handle(exc); - } - catch (std::exception& exc) - { - ErrorHandler::handle(exc); - } - catch (...) - { - ErrorHandler::handle(); - } - { - FastMutex::ScopedLock lock(_mutex); - interval = _periodicInterval; - } - } - } - while (interval > 0); - _done.set(); -} - - -AbstractTimerCallback::AbstractTimerCallback() -{ -} - - -AbstractTimerCallback::AbstractTimerCallback(const AbstractTimerCallback& callback) -{ -} - - -AbstractTimerCallback::~AbstractTimerCallback() -{ -} - - -AbstractTimerCallback& AbstractTimerCallback::operator = (const AbstractTimerCallback& callback) -{ - return *this; -} - - -} // namespace Poco +// +// Timer.cpp +// +// $Id: //poco/1.2/Foundation/src/Timer.cpp#1 $ +// +// Library: Foundation +// Package: Threading +// Module: Timer +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/Timer.h" +#include "Poco/ThreadPool.h" +#include "Poco/Exception.h" +#include "Poco/ErrorHandler.h" + + +namespace Poco { + + +Timer::Timer(long startInterval, long periodicInterval): + _startInterval(startInterval), + _periodicInterval(periodicInterval), + _pCallback(0) +{ + poco_assert (startInterval >= 0 && periodicInterval >= 0); +} + + +Timer::~Timer() +{ + stop(); +} + + +void Timer::start(const AbstractTimerCallback& method) +{ + start(method, ThreadPool::defaultPool()); +} + + +void Timer::start(const AbstractTimerCallback& method, ThreadPool& threadPool) +{ + poco_assert (!_pCallback); + + FastMutex::ScopedLock lock(_mutex); + _pCallback = method.clone(); + _wakeUp.reset(); + threadPool.start(*this); +} + + +void Timer::stop() +{ + FastMutex::ScopedLock lock(_mutex); + if (_pCallback) + { + _periodicInterval = 0; + _mutex.unlock(); + _wakeUp.set(); + _done.wait(); // warning: deadlock if called from timer callback + _mutex.lock(); + delete _pCallback; + _pCallback = 0; + } +} + + +void Timer::restart() +{ + FastMutex::ScopedLock lock(_mutex); + if (_pCallback) + { + _wakeUp.set(); + } +} + + +void Timer::restart(long milliseconds) +{ + poco_assert (milliseconds >= 0); + FastMutex::ScopedLock lock(_mutex); + if (_pCallback) + { + _periodicInterval = milliseconds; + _wakeUp.set(); + } +} + + +long Timer::getStartInterval() const +{ + FastMutex::ScopedLock lock(_mutex); + return _startInterval; +} + + +void Timer::setStartInterval(long milliseconds) +{ + poco_assert (milliseconds >= 0); + FastMutex::ScopedLock lock(_mutex); + _startInterval = milliseconds; +} + + +long Timer::getPeriodicInterval() const +{ + FastMutex::ScopedLock lock(_mutex); + return _periodicInterval; +} + + +void Timer::setPeriodicInterval(long milliseconds) +{ + poco_assert (milliseconds >= 0); + FastMutex::ScopedLock lock(_mutex); + _periodicInterval = milliseconds; +} + + +void Timer::run() +{ + long interval; + { + FastMutex::ScopedLock lock(_mutex); + interval = _startInterval; + } + do + { + if (_wakeUp.tryWait(interval)) + { + FastMutex::ScopedLock lock(_mutex); + interval = _periodicInterval; + } + else + { + try + { + _pCallback->invoke(*this); + } + catch (Exception& exc) + { + ErrorHandler::handle(exc); + } + catch (std::exception& exc) + { + ErrorHandler::handle(exc); + } + catch (...) + { + ErrorHandler::handle(); + } + { + FastMutex::ScopedLock lock(_mutex); + interval = _periodicInterval; + } + } + } + while (interval > 0); + _done.set(); +} + + +AbstractTimerCallback::AbstractTimerCallback() +{ +} + + +AbstractTimerCallback::AbstractTimerCallback(const AbstractTimerCallback& callback) +{ +} + + +AbstractTimerCallback::~AbstractTimerCallback() +{ +} + + +AbstractTimerCallback& AbstractTimerCallback::operator = (const AbstractTimerCallback& callback) +{ + return *this; +} + + +} // namespace Poco diff --git a/Foundation/src/Timespan.cpp b/Foundation/src/Timespan.cpp index 652972e8b..573e3b9ab 100644 --- a/Foundation/src/Timespan.cpp +++ b/Foundation/src/Timespan.cpp @@ -1,172 +1,172 @@ -// -// Timespan.cpp -// -// $Id: //poco/1.2/Foundation/src/Timespan.cpp#1 $ -// -// Library: Foundation -// Package: DateTime -// Module: Timespan -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/Timespan.h" -#include - - -namespace Poco { - - -const Timespan::TimeDiff Timespan::MILLISECONDS = 1000; -const Timespan::TimeDiff Timespan::SECONDS = 1000*Timespan::MILLISECONDS; -const Timespan::TimeDiff Timespan::MINUTES = 60*Timespan::SECONDS; -const Timespan::TimeDiff Timespan::HOURS = 60*Timespan::MINUTES; -const Timespan::TimeDiff Timespan::DAYS = 24*Timespan::HOURS; - - -Timespan::Timespan(): - _span(0) -{ -} - - -Timespan::Timespan(TimeDiff microseconds): - _span(microseconds) -{ -} - - -Timespan::Timespan(long seconds, long microseconds): - _span(TimeDiff(seconds)*SECONDS + microseconds) -{ -} - - -Timespan::Timespan(int days, int hours, int minutes, int seconds, int microseconds): - _span(TimeDiff(microseconds) + TimeDiff(seconds)*SECONDS + TimeDiff(minutes)*MINUTES + TimeDiff(hours)*HOURS + TimeDiff(days)*DAYS) -{ -} - - -Timespan::Timespan(const Timespan& timespan): - _span(timespan._span) -{ -} - - -Timespan::~Timespan() -{ -} - - -Timespan& Timespan::operator = (const Timespan& timespan) -{ - _span = timespan._span; - return *this; -} - - -Timespan& Timespan::operator = (TimeDiff microseconds) -{ - _span = microseconds; - return *this; -} - - -Timespan& Timespan::assign(int days, int hours, int minutes, int seconds, int microseconds) -{ - _span = TimeDiff(microseconds) + TimeDiff(seconds)*SECONDS + TimeDiff(minutes)*MINUTES + TimeDiff(hours)*HOURS + TimeDiff(days)*DAYS; - return *this; -} - - -Timespan& Timespan::assign(long seconds, long microseconds) -{ - _span = TimeDiff(seconds)*SECONDS + TimeDiff(microseconds); - return *this; -} - - -void Timespan::swap(Timespan& timespan) -{ - std::swap(_span, timespan._span); -} - - -Timespan Timespan::operator + (const Timespan& d) const -{ - return Timespan(_span + d._span); -} - - -Timespan Timespan::operator - (const Timespan& d) const -{ - return Timespan(_span - d._span); -} - - -Timespan& Timespan::operator += (const Timespan& d) -{ - _span += d._span; - return *this; -} - - -Timespan& Timespan::operator -= (const Timespan& d) -{ - _span -= d._span; - return *this; -} - - -Timespan Timespan::operator + (TimeDiff microseconds) const -{ - return Timespan(_span + microseconds); -} - - -Timespan Timespan::operator - (TimeDiff microseconds) const -{ - return Timespan(_span - microseconds); -} - - -Timespan& Timespan::operator += (TimeDiff microseconds) -{ - _span += microseconds; - return *this; -} - - -Timespan& Timespan::operator -= (TimeDiff microseconds) -{ - _span -= microseconds; - return *this; -} - - -} // namespace Poco +// +// Timespan.cpp +// +// $Id: //poco/1.2/Foundation/src/Timespan.cpp#1 $ +// +// Library: Foundation +// Package: DateTime +// Module: Timespan +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/Timespan.h" +#include + + +namespace Poco { + + +const Timespan::TimeDiff Timespan::MILLISECONDS = 1000; +const Timespan::TimeDiff Timespan::SECONDS = 1000*Timespan::MILLISECONDS; +const Timespan::TimeDiff Timespan::MINUTES = 60*Timespan::SECONDS; +const Timespan::TimeDiff Timespan::HOURS = 60*Timespan::MINUTES; +const Timespan::TimeDiff Timespan::DAYS = 24*Timespan::HOURS; + + +Timespan::Timespan(): + _span(0) +{ +} + + +Timespan::Timespan(TimeDiff microseconds): + _span(microseconds) +{ +} + + +Timespan::Timespan(long seconds, long microseconds): + _span(TimeDiff(seconds)*SECONDS + microseconds) +{ +} + + +Timespan::Timespan(int days, int hours, int minutes, int seconds, int microseconds): + _span(TimeDiff(microseconds) + TimeDiff(seconds)*SECONDS + TimeDiff(minutes)*MINUTES + TimeDiff(hours)*HOURS + TimeDiff(days)*DAYS) +{ +} + + +Timespan::Timespan(const Timespan& timespan): + _span(timespan._span) +{ +} + + +Timespan::~Timespan() +{ +} + + +Timespan& Timespan::operator = (const Timespan& timespan) +{ + _span = timespan._span; + return *this; +} + + +Timespan& Timespan::operator = (TimeDiff microseconds) +{ + _span = microseconds; + return *this; +} + + +Timespan& Timespan::assign(int days, int hours, int minutes, int seconds, int microseconds) +{ + _span = TimeDiff(microseconds) + TimeDiff(seconds)*SECONDS + TimeDiff(minutes)*MINUTES + TimeDiff(hours)*HOURS + TimeDiff(days)*DAYS; + return *this; +} + + +Timespan& Timespan::assign(long seconds, long microseconds) +{ + _span = TimeDiff(seconds)*SECONDS + TimeDiff(microseconds); + return *this; +} + + +void Timespan::swap(Timespan& timespan) +{ + std::swap(_span, timespan._span); +} + + +Timespan Timespan::operator + (const Timespan& d) const +{ + return Timespan(_span + d._span); +} + + +Timespan Timespan::operator - (const Timespan& d) const +{ + return Timespan(_span - d._span); +} + + +Timespan& Timespan::operator += (const Timespan& d) +{ + _span += d._span; + return *this; +} + + +Timespan& Timespan::operator -= (const Timespan& d) +{ + _span -= d._span; + return *this; +} + + +Timespan Timespan::operator + (TimeDiff microseconds) const +{ + return Timespan(_span + microseconds); +} + + +Timespan Timespan::operator - (TimeDiff microseconds) const +{ + return Timespan(_span - microseconds); +} + + +Timespan& Timespan::operator += (TimeDiff microseconds) +{ + _span += microseconds; + return *this; +} + + +Timespan& Timespan::operator -= (TimeDiff microseconds) +{ + _span -= microseconds; + return *this; +} + + +} // namespace Poco diff --git a/Foundation/src/Timestamp.cpp b/Foundation/src/Timestamp.cpp index 3d05f65a9..b8cb977c4 100644 --- a/Foundation/src/Timestamp.cpp +++ b/Foundation/src/Timestamp.cpp @@ -1,172 +1,172 @@ -// -// Timestamp.cpp -// -// $Id: //poco/1.2/Foundation/src/Timestamp.cpp#1 $ -// -// Library: Foundation -// Package: DateTime -// Module: Timestamp -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/Timestamp.h" -#include "Poco/Exception.h" -#include -#if defined(POCO_OS_FAMILY_UNIX) -#include -#include -#include -#elif defined(POCO_OS_FAMILY_WINDOWS) -#include -#endif - - -namespace Poco { - - -Timestamp::Timestamp() -{ - update(); -} - - -Timestamp::Timestamp(TimeVal tv) -{ - _ts = tv; -} - - -Timestamp::Timestamp(const Timestamp& other) -{ - _ts = other._ts; -} - - -Timestamp::~Timestamp() -{ -} - - -Timestamp& Timestamp::operator = (const Timestamp& other) -{ - _ts = other._ts; - return *this; -} - - -Timestamp& Timestamp::operator = (TimeVal tv) -{ - _ts = tv; - return *this; -} - - -void Timestamp::swap(Timestamp& timestamp) -{ - std::swap(_ts, timestamp._ts); -} - - -Timestamp Timestamp::fromEpochTime(time_t t) -{ - return Timestamp(TimeVal(t)*resolution()); -} - - -Timestamp Timestamp::fromUtcTime(UtcTimeVal val) -{ - val -= (TimeDiff(0x01b21dd2) << 32) + 0x13814000; - val /= 10; - return Timestamp(val); -} - - -void Timestamp::update() -{ -#if defined(POCO_OS_FAMILY_WINDOWS) - - FILETIME ft; - GetSystemTimeAsFileTime(&ft); - ULARGE_INTEGER epoch; // UNIX epoch (1970-01-01 00:00:00) expressed in Windows NT FILETIME - epoch.LowPart = 0xD53E8000; - epoch.HighPart = 0x019DB1DE; - - ULARGE_INTEGER ts; - ts.LowPart = ft.dwLowDateTime; - ts.HighPart = ft.dwHighDateTime; - ts.QuadPart -= epoch.QuadPart; - _ts = ts.QuadPart/10; - -#else - - struct timeval tv; - if (gettimeofday(&tv, NULL)) - throw SystemException("cannot get time of day"); - _ts = TimeVal(tv.tv_sec)*resolution() + tv.tv_usec; - -#endif -} - - -#if defined(_WIN32) - - -Timestamp Timestamp::fromFileTimeNP(UInt32 fileTimeLow, UInt32 fileTimeHigh) -{ - ULARGE_INTEGER epoch; // UNIX epoch (1970-01-01 00:00:00) expressed in Windows NT FILETIME - epoch.LowPart = 0xD53E8000; - epoch.HighPart = 0x019DB1DE; - - ULARGE_INTEGER ts; - ts.LowPart = fileTimeLow; - ts.HighPart = fileTimeHigh; - ts.QuadPart -= epoch.QuadPart; - - return Timestamp(ts.QuadPart/10); -} - - -void Timestamp::toFileTimeNP(UInt32& fileTimeLow, UInt32& fileTimeHigh) const -{ - ULARGE_INTEGER epoch; // UNIX epoch (1970-01-01 00:00:00) expressed in Windows NT FILETIME - epoch.LowPart = 0xD53E8000; - epoch.HighPart = 0x019DB1DE; - - ULARGE_INTEGER ts; - ts.QuadPart = _ts*10; - ts.QuadPart += epoch.QuadPart; - fileTimeLow = ts.LowPart; - fileTimeHigh = ts.HighPart; -} - - -#endif - - - -} // namespace Poco +// +// Timestamp.cpp +// +// $Id: //poco/1.2/Foundation/src/Timestamp.cpp#1 $ +// +// Library: Foundation +// Package: DateTime +// Module: Timestamp +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/Timestamp.h" +#include "Poco/Exception.h" +#include +#if defined(POCO_OS_FAMILY_UNIX) +#include +#include +#include +#elif defined(POCO_OS_FAMILY_WINDOWS) +#include +#endif + + +namespace Poco { + + +Timestamp::Timestamp() +{ + update(); +} + + +Timestamp::Timestamp(TimeVal tv) +{ + _ts = tv; +} + + +Timestamp::Timestamp(const Timestamp& other) +{ + _ts = other._ts; +} + + +Timestamp::~Timestamp() +{ +} + + +Timestamp& Timestamp::operator = (const Timestamp& other) +{ + _ts = other._ts; + return *this; +} + + +Timestamp& Timestamp::operator = (TimeVal tv) +{ + _ts = tv; + return *this; +} + + +void Timestamp::swap(Timestamp& timestamp) +{ + std::swap(_ts, timestamp._ts); +} + + +Timestamp Timestamp::fromEpochTime(time_t t) +{ + return Timestamp(TimeVal(t)*resolution()); +} + + +Timestamp Timestamp::fromUtcTime(UtcTimeVal val) +{ + val -= (TimeDiff(0x01b21dd2) << 32) + 0x13814000; + val /= 10; + return Timestamp(val); +} + + +void Timestamp::update() +{ +#if defined(POCO_OS_FAMILY_WINDOWS) + + FILETIME ft; + GetSystemTimeAsFileTime(&ft); + ULARGE_INTEGER epoch; // UNIX epoch (1970-01-01 00:00:00) expressed in Windows NT FILETIME + epoch.LowPart = 0xD53E8000; + epoch.HighPart = 0x019DB1DE; + + ULARGE_INTEGER ts; + ts.LowPart = ft.dwLowDateTime; + ts.HighPart = ft.dwHighDateTime; + ts.QuadPart -= epoch.QuadPart; + _ts = ts.QuadPart/10; + +#else + + struct timeval tv; + if (gettimeofday(&tv, NULL)) + throw SystemException("cannot get time of day"); + _ts = TimeVal(tv.tv_sec)*resolution() + tv.tv_usec; + +#endif +} + + +#if defined(_WIN32) + + +Timestamp Timestamp::fromFileTimeNP(UInt32 fileTimeLow, UInt32 fileTimeHigh) +{ + ULARGE_INTEGER epoch; // UNIX epoch (1970-01-01 00:00:00) expressed in Windows NT FILETIME + epoch.LowPart = 0xD53E8000; + epoch.HighPart = 0x019DB1DE; + + ULARGE_INTEGER ts; + ts.LowPart = fileTimeLow; + ts.HighPart = fileTimeHigh; + ts.QuadPart -= epoch.QuadPart; + + return Timestamp(ts.QuadPart/10); +} + + +void Timestamp::toFileTimeNP(UInt32& fileTimeLow, UInt32& fileTimeHigh) const +{ + ULARGE_INTEGER epoch; // UNIX epoch (1970-01-01 00:00:00) expressed in Windows NT FILETIME + epoch.LowPart = 0xD53E8000; + epoch.HighPart = 0x019DB1DE; + + ULARGE_INTEGER ts; + ts.QuadPart = _ts*10; + ts.QuadPart += epoch.QuadPart; + fileTimeLow = ts.LowPart; + fileTimeHigh = ts.HighPart; +} + + +#endif + + + +} // namespace Poco diff --git a/Foundation/src/Timezone.cpp b/Foundation/src/Timezone.cpp index 3a3fa6308..5d4cac866 100644 --- a/Foundation/src/Timezone.cpp +++ b/Foundation/src/Timezone.cpp @@ -1,57 +1,57 @@ -// -// Timezone.cpp -// -// $Id: //poco/1.2/Foundation/src/Timezone.cpp#1 $ -// -// Library: Foundation -// Package: DateTime -// Module: Timezone -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/Timezone.h" -#include - - -#if defined(POCO_OS_FAMILY_WINDOWS) -#include "Timezone_WIN32.cpp" -#else -#include "Timezone_UNIX.cpp" -#endif - - -namespace Poco { - - -int Timezone::tzd() -{ - return utcOffset() + dst(); -} - - -} // namespace Poco +// +// Timezone.cpp +// +// $Id: //poco/1.2/Foundation/src/Timezone.cpp#1 $ +// +// Library: Foundation +// Package: DateTime +// Module: Timezone +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/Timezone.h" +#include + + +#if defined(POCO_OS_FAMILY_WINDOWS) +#include "Timezone_WIN32.cpp" +#else +#include "Timezone_UNIX.cpp" +#endif + + +namespace Poco { + + +int Timezone::tzd() +{ + return utcOffset() + dst(); +} + + +} // namespace Poco diff --git a/Foundation/src/Timezone_UNIX.cpp b/Foundation/src/Timezone_UNIX.cpp index fdecaea77..54f23ceb2 100644 --- a/Foundation/src/Timezone_UNIX.cpp +++ b/Foundation/src/Timezone_UNIX.cpp @@ -1,118 +1,118 @@ -// -// Timezone_UNIX.cpp -// -// $Id: //poco/1.2/Foundation/src/Timezone_UNIX.cpp#1 $ -// -// Library: Foundation -// Package: DateTime -// Module: Timezone -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/Timezone.h" -#include - - -namespace Poco { - - -class TZInfo -{ -public: - TZInfo() - { - tzset(); - } - - int timeZone() - { - #if defined(__APPLE__) || defined(__FreeBSD__) // no timezone global var - time_t now = time(NULL); - struct tm t; - gmtime_r(&now, &t); - time_t utc = mktime(&t); - return now - utc; - #elif defined(__CYGWIN__) - return -_timezone; - #else - return -timezone; - #endif - } - - const char* name(bool dst) - { - return tzname[dst ? 1 : 0]; - } -}; - - -static TZInfo tzInfo; - - -int Timezone::utcOffset() -{ - return tzInfo.timeZone(); -} - - -int Timezone::dst() -{ - time_t now = time(NULL); - struct tm t; - localtime_r(&now, &t); - return t.tm_isdst == 1 ? 3600 : 0; -} - - -bool Timezone::isDst(const Timestamp& timestamp) -{ - time_t time = timestamp.epochTime(); - struct tm* tms = localtime(&time); - return tms->tm_isdst > 0; -} - - -std::string Timezone::name() -{ - return std::string(tzInfo.name(dst() != 0)); -} - - -std::string Timezone::standardName() -{ - return std::string(tzInfo.name(false)); -} - - -std::string Timezone::dstName() -{ - return std::string(tzInfo.name(true)); -} - - -} // namespace Poco +// +// Timezone_UNIX.cpp +// +// $Id: //poco/1.2/Foundation/src/Timezone_UNIX.cpp#1 $ +// +// Library: Foundation +// Package: DateTime +// Module: Timezone +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/Timezone.h" +#include + + +namespace Poco { + + +class TZInfo +{ +public: + TZInfo() + { + tzset(); + } + + int timeZone() + { + #if defined(__APPLE__) || defined(__FreeBSD__) // no timezone global var + time_t now = time(NULL); + struct tm t; + gmtime_r(&now, &t); + time_t utc = mktime(&t); + return now - utc; + #elif defined(__CYGWIN__) + return -_timezone; + #else + return -timezone; + #endif + } + + const char* name(bool dst) + { + return tzname[dst ? 1 : 0]; + } +}; + + +static TZInfo tzInfo; + + +int Timezone::utcOffset() +{ + return tzInfo.timeZone(); +} + + +int Timezone::dst() +{ + time_t now = time(NULL); + struct tm t; + localtime_r(&now, &t); + return t.tm_isdst == 1 ? 3600 : 0; +} + + +bool Timezone::isDst(const Timestamp& timestamp) +{ + time_t time = timestamp.epochTime(); + struct tm* tms = localtime(&time); + return tms->tm_isdst > 0; +} + + +std::string Timezone::name() +{ + return std::string(tzInfo.name(dst() != 0)); +} + + +std::string Timezone::standardName() +{ + return std::string(tzInfo.name(false)); +} + + +std::string Timezone::dstName() +{ + return std::string(tzInfo.name(true)); +} + + +} // namespace Poco diff --git a/Foundation/src/Timezone_WIN32.cpp b/Foundation/src/Timezone_WIN32.cpp index 27bbfd35f..f45e5f413 100644 --- a/Foundation/src/Timezone_WIN32.cpp +++ b/Foundation/src/Timezone_WIN32.cpp @@ -1,102 +1,102 @@ -// -// Timezone_WIN32.cpp -// -// $Id: //poco/1.2/Foundation/src/Timezone_WIN32.cpp#1 $ -// -// Library: Foundation -// Package: DateTime -// Module: Timezone -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/Timezone.h" -#include -#include - - -namespace Poco { - - -int Timezone::utcOffset() -{ - TIME_ZONE_INFORMATION tzInfo; - DWORD dstFlag = GetTimeZoneInformation(&tzInfo); - return -tzInfo.Bias*60; -} - - -int Timezone::dst() -{ - TIME_ZONE_INFORMATION tzInfo; - DWORD dstFlag = GetTimeZoneInformation(&tzInfo); - return dstFlag == TIME_ZONE_ID_DAYLIGHT ? -tzInfo.DaylightBias*60 : 0; -} - - -bool Timezone::isDst(const Timestamp& timestamp) -{ - time_t time = timestamp.epochTime(); - struct tm* tms = localtime(&time); - return tms->tm_isdst > 0; -} - - -std::string Timezone::name() -{ - TIME_ZONE_INFORMATION tzInfo; - DWORD dstFlag = GetTimeZoneInformation(&tzInfo); - WCHAR* ptr = dstFlag == TIME_ZONE_ID_DAYLIGHT ? tzInfo.DaylightName : tzInfo.StandardName; - std::string result; - while (*ptr) result += (char) *ptr++; - return result; -} - - -std::string Timezone::standardName() -{ - TIME_ZONE_INFORMATION tzInfo; - DWORD dstFlag = GetTimeZoneInformation(&tzInfo); - WCHAR* ptr = tzInfo.StandardName; - std::string result; - while (*ptr) result += (char) *ptr++; - return result; -} - - -std::string Timezone::dstName() -{ - TIME_ZONE_INFORMATION tzInfo; - DWORD dstFlag = GetTimeZoneInformation(&tzInfo); - WCHAR* ptr = tzInfo.DaylightName; - std::string result; - while (*ptr) result += (char) *ptr++; - return result; -} - - -} // namespace Poco +// +// Timezone_WIN32.cpp +// +// $Id: //poco/1.2/Foundation/src/Timezone_WIN32.cpp#1 $ +// +// Library: Foundation +// Package: DateTime +// Module: Timezone +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/Timezone.h" +#include +#include + + +namespace Poco { + + +int Timezone::utcOffset() +{ + TIME_ZONE_INFORMATION tzInfo; + DWORD dstFlag = GetTimeZoneInformation(&tzInfo); + return -tzInfo.Bias*60; +} + + +int Timezone::dst() +{ + TIME_ZONE_INFORMATION tzInfo; + DWORD dstFlag = GetTimeZoneInformation(&tzInfo); + return dstFlag == TIME_ZONE_ID_DAYLIGHT ? -tzInfo.DaylightBias*60 : 0; +} + + +bool Timezone::isDst(const Timestamp& timestamp) +{ + time_t time = timestamp.epochTime(); + struct tm* tms = localtime(&time); + return tms->tm_isdst > 0; +} + + +std::string Timezone::name() +{ + TIME_ZONE_INFORMATION tzInfo; + DWORD dstFlag = GetTimeZoneInformation(&tzInfo); + WCHAR* ptr = dstFlag == TIME_ZONE_ID_DAYLIGHT ? tzInfo.DaylightName : tzInfo.StandardName; + std::string result; + while (*ptr) result += (char) *ptr++; + return result; +} + + +std::string Timezone::standardName() +{ + TIME_ZONE_INFORMATION tzInfo; + DWORD dstFlag = GetTimeZoneInformation(&tzInfo); + WCHAR* ptr = tzInfo.StandardName; + std::string result; + while (*ptr) result += (char) *ptr++; + return result; +} + + +std::string Timezone::dstName() +{ + TIME_ZONE_INFORMATION tzInfo; + DWORD dstFlag = GetTimeZoneInformation(&tzInfo); + WCHAR* ptr = tzInfo.DaylightName; + std::string result; + while (*ptr) result += (char) *ptr++; + return result; +} + + +} // namespace Poco diff --git a/Foundation/src/Token.cpp b/Foundation/src/Token.cpp index ca63488c6..4c77a0448 100644 --- a/Foundation/src/Token.cpp +++ b/Foundation/src/Token.cpp @@ -1,168 +1,168 @@ -// -// Token.cpp -// -// $Id: //poco/1.2/Foundation/src/Token.cpp#1 $ -// -// Library: Foundation -// Package: Streams -// Module: StringTokenizer -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/Token.h" -#include "Poco/NumberParser.h" -#include - - -namespace Poco { - - -Token::Token() -{ -} - - -Token::~Token() -{ -} - - -bool Token::start(char c, std::istream& istr) -{ - _value = c; - return false; -} - - -void Token::finish(std::istream& istr) -{ -} - - -Token::Class Token::tokenClass() const -{ - return INVALID_TOKEN; -} - - -std::string Token::asString() const -{ - return _value; -} - - -int Token::asInteger() const -{ - return NumberParser::parse(_value); -} - - -double Token::asFloat() const -{ - return NumberParser::parseFloat(_value); -} - - -char Token::asChar() const -{ - return _value.empty() ? 0 : _value[0]; -} - - -InvalidToken::InvalidToken() -{ -} - - -InvalidToken::~InvalidToken() -{ -} - - -Token::Class InvalidToken::tokenClass() const -{ - return INVALID_TOKEN; -} - - -EOFToken::EOFToken() -{ -} - - -EOFToken::~EOFToken() -{ -} - - -Token::Class EOFToken::tokenClass() const -{ - return EOF_TOKEN; -} - - -WhitespaceToken::WhitespaceToken() -{ -} - - -WhitespaceToken::~WhitespaceToken() -{ -} - - -Token::Class WhitespaceToken::tokenClass() const -{ - return WHITESPACE_TOKEN; -} - - -bool WhitespaceToken::start(char c, std::istream& istr) -{ - if (isspace(c)) - { - _value = c; - return true; - } - return false; -} - - -void WhitespaceToken::finish(std::istream& istr) -{ - int c = istr.peek(); - while (isspace(c)) - { - istr.get(); - _value += (char) c; - c = istr.peek(); - } -} - - -} // namespace Poco +// +// Token.cpp +// +// $Id: //poco/1.2/Foundation/src/Token.cpp#1 $ +// +// Library: Foundation +// Package: Streams +// Module: StringTokenizer +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/Token.h" +#include "Poco/NumberParser.h" +#include + + +namespace Poco { + + +Token::Token() +{ +} + + +Token::~Token() +{ +} + + +bool Token::start(char c, std::istream& istr) +{ + _value = c; + return false; +} + + +void Token::finish(std::istream& istr) +{ +} + + +Token::Class Token::tokenClass() const +{ + return INVALID_TOKEN; +} + + +std::string Token::asString() const +{ + return _value; +} + + +int Token::asInteger() const +{ + return NumberParser::parse(_value); +} + + +double Token::asFloat() const +{ + return NumberParser::parseFloat(_value); +} + + +char Token::asChar() const +{ + return _value.empty() ? 0 : _value[0]; +} + + +InvalidToken::InvalidToken() +{ +} + + +InvalidToken::~InvalidToken() +{ +} + + +Token::Class InvalidToken::tokenClass() const +{ + return INVALID_TOKEN; +} + + +EOFToken::EOFToken() +{ +} + + +EOFToken::~EOFToken() +{ +} + + +Token::Class EOFToken::tokenClass() const +{ + return EOF_TOKEN; +} + + +WhitespaceToken::WhitespaceToken() +{ +} + + +WhitespaceToken::~WhitespaceToken() +{ +} + + +Token::Class WhitespaceToken::tokenClass() const +{ + return WHITESPACE_TOKEN; +} + + +bool WhitespaceToken::start(char c, std::istream& istr) +{ + if (isspace(c)) + { + _value = c; + return true; + } + return false; +} + + +void WhitespaceToken::finish(std::istream& istr) +{ + int c = istr.peek(); + while (isspace(c)) + { + istr.get(); + _value += (char) c; + c = istr.peek(); + } +} + + +} // namespace Poco diff --git a/Foundation/src/URI.cpp b/Foundation/src/URI.cpp index 8bdf49388..d4f6752da 100644 --- a/Foundation/src/URI.cpp +++ b/Foundation/src/URI.cpp @@ -1,841 +1,841 @@ -// -// URI.cpp -// -// $Id: //poco/1.2/Foundation/src/URI.cpp#1 $ -// -// Library: Foundation -// Package: URI -// Module: URI -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/URI.h" -#include "Poco/NumberFormatter.h" -#include "Poco/Exception.h" -#include "Poco/String.h" -#include "Poco/NumberParser.h" - - -namespace Poco { - - -const std::string URI::RESERVED_PATH = "?#"; -const std::string URI::RESERVED_QUERY = "#"; -const std::string URI::RESERVED_FRAGMENT = ""; -const std::string URI::ILLEGAL = "%<>{}|\\\"^`"; - - -URI::URI(): - _port(0) -{ -} - - -URI::URI(const std::string& uri): - _port(0) -{ - parse(uri); -} - - -URI::URI(const char* uri): - _port(0) -{ - parse(std::string(uri)); -} - - -URI::URI(const std::string& scheme, const std::string& pathEtc): - _scheme(scheme), - _port(0) -{ - toLowerInPlace(_scheme); - _port = getWellKnownPort(); - std::string::const_iterator beg = pathEtc.begin(); - std::string::const_iterator end = pathEtc.end(); - parsePathEtc(beg, end); -} - - -URI::URI(const std::string& scheme, const std::string& authority, const std::string& pathEtc): - _scheme(scheme) -{ - toLowerInPlace(_scheme); - std::string::const_iterator beg = authority.begin(); - std::string::const_iterator end = authority.end(); - parseAuthority(beg, end); - beg = pathEtc.begin(); - end = pathEtc.end(); - parsePathEtc(beg, end); -} - - -URI::URI(const std::string& scheme, const std::string& authority, const std::string& path, const std::string& query): - _scheme(scheme), - _path(path), - _query(query) -{ - toLowerInPlace(_scheme); - std::string::const_iterator beg = authority.begin(); - std::string::const_iterator end = authority.end(); - parseAuthority(beg, end); -} - - -URI::URI(const std::string& scheme, const std::string& authority, const std::string& path, const std::string& query, const std::string& fragment): - _scheme(scheme), - _path(path), - _query(query), - _fragment(fragment) -{ - toLowerInPlace(_scheme); - std::string::const_iterator beg = authority.begin(); - std::string::const_iterator end = authority.end(); - parseAuthority(beg, end); -} - - -URI::URI(const URI& uri): - _scheme(uri._scheme), - _userInfo(uri._userInfo), - _host(uri._host), - _port(uri._port), - _path(uri._path), - _query(uri._query), - _fragment(uri._fragment) -{ -} - - -URI::URI(const URI& baseURI, const std::string& relativeURI): - _scheme(baseURI._scheme), - _userInfo(baseURI._userInfo), - _host(baseURI._host), - _port(baseURI._port), - _path(baseURI._path), - _query(baseURI._query), - _fragment(baseURI._fragment) -{ - resolve(relativeURI); -} - - -URI::~URI() -{ -} - - -URI& URI::operator = (const URI& uri) -{ - if (&uri != this) - { - _scheme = uri._scheme; - _userInfo = uri._userInfo; - _host = uri._host; - _port = uri._port; - _path = uri._path; - _query = uri._query; - _fragment = uri._fragment; - } - return *this; -} - - -URI& URI::operator = (const std::string& uri) -{ - clear(); - parse(uri); - return *this; -} - - -URI& URI::operator = (const char* uri) -{ - clear(); - parse(std::string(uri)); - return *this; -} - - -void URI::swap(URI& uri) -{ - std::swap(_scheme, uri._scheme); - std::swap(_userInfo, uri._userInfo); - std::swap(_host, uri._host); - std::swap(_port, uri._port); - std::swap(_path, uri._path); - std::swap(_query, uri._query); - std::swap(_fragment, uri._fragment); -} - - -void URI::clear() -{ - _scheme.clear(); - _userInfo.clear(); - _host.clear(); - _port = 0; - _path.clear(); - _query.clear(); - _fragment.clear(); -} - - -std::string URI::toString() const -{ - std::string uri; - if (isRelative()) - { - encode(_path, RESERVED_PATH, uri); - } - else - { - uri = _scheme; - uri += ':'; - std::string auth = getAuthority(); - if (!auth.empty() || _scheme == "file") - { - uri.append("//"); - uri.append(auth); - } - if (!_path.empty()) - { - if (!auth.empty() && _path[0] != '/') - uri += '/'; - encode(_path, RESERVED_PATH, uri); - } - } - if (!_query.empty()) - { - uri += '?'; - uri.append(_query); - } - if (!_fragment.empty()) - { - uri += '#'; - encode(_fragment, RESERVED_FRAGMENT, uri); - } - return uri; -} - - -void URI::setScheme(const std::string& scheme) -{ - _scheme = scheme; - toLowerInPlace(_scheme); - if (_port == 0) - _port = getWellKnownPort(); -} - - -void URI::setUserInfo(const std::string& userInfo) -{ - _userInfo.clear(); - decode(userInfo, _userInfo); -} - - -void URI::setHost(const std::string& host) -{ - _host = host; -} - - -unsigned short URI::getPort() const -{ - if (_port == 0) - return getWellKnownPort(); - else - return _port; -} - - -void URI::setPort(unsigned short port) -{ - _port = port; -} - - -std::string URI::getAuthority() const -{ - std::string auth; - if (!_userInfo.empty()) - { - auth.append(_userInfo); - auth += '@'; - } - auth.append(_host); - if (_port && !isWellKnownPort()) - { - auth += ':'; - auth.append(NumberFormatter::format(_port)); - } - return auth; -} - - -void URI::setAuthority(const std::string& authority) -{ - _userInfo.clear(); - _host.clear(); - _port = 0; - std::string::const_iterator beg = authority.begin(); - std::string::const_iterator end = authority.end(); - parseAuthority(beg, end); -} - - -void URI::setPath(const std::string& path) -{ - _path.clear(); - decode(path, _path); -} - - -void URI::setRawQuery(const std::string& query) -{ - _query = query; -} - - -void URI::setQuery(const std::string& query) -{ - _query.clear(); - encode(query, RESERVED_QUERY, _query); -} - - -std::string URI::getQuery() const -{ - std::string query; - decode(_query, query); - return query; -} - - -void URI::setFragment(const std::string& fragment) -{ - _fragment.clear(); - decode(fragment, _fragment); -} - - -void URI::setPathEtc(const std::string& pathEtc) -{ - _path.clear(); - _query.clear(); - _fragment.clear(); - std::string::const_iterator beg = pathEtc.begin(); - std::string::const_iterator end = pathEtc.end(); - parsePathEtc(beg, end); -} - - -std::string URI::getPathEtc() const -{ - std::string pathEtc; - encode(_path, RESERVED_PATH, pathEtc); - if (!_query.empty()) - { - pathEtc += '?'; - encode(_query, RESERVED_QUERY, pathEtc); - } - if (!_fragment.empty()) - { - pathEtc += '#'; - encode(_fragment, RESERVED_FRAGMENT, pathEtc); - } - return pathEtc; -} - - -std::string URI::getPathAndQuery() const -{ - std::string pathAndQuery; - encode(_path, RESERVED_PATH, pathAndQuery); - if (!_query.empty()) - { - pathAndQuery += '?'; - encode(_query, RESERVED_QUERY, pathAndQuery); - } - return pathAndQuery; -} - - -void URI::resolve(const std::string& relativeURI) -{ - URI parsedURI(relativeURI); - resolve(parsedURI); -} - - -void URI::resolve(const URI& relativeURI) -{ - if (!relativeURI._scheme.empty()) - { - _scheme = relativeURI._scheme; - _userInfo = relativeURI._userInfo; - _host = relativeURI._host; - _port = relativeURI._port; - _path = relativeURI._path; - _query = relativeURI._query; - removeDotSegments(); - } - else - { - if (!relativeURI._host.empty()) - { - _userInfo = relativeURI._userInfo; - _host = relativeURI._host; - _port = relativeURI._port; - _path = relativeURI._path; - _query = relativeURI._query; - removeDotSegments(); - } - else - { - if (relativeURI._path.empty()) - { - if (!relativeURI._query.empty()) - _query = relativeURI._query; - } - else - { - if (relativeURI._path[0] == '/') - { - _path = relativeURI._path; - removeDotSegments(); - } - else - { - mergePath(relativeURI._path); - } - _query = relativeURI._query; - } - } - } - _fragment = relativeURI._fragment; -} - - -bool URI::isRelative() const -{ - return _scheme.empty(); -} - - -bool URI::empty() const -{ - return _scheme.empty() && _host.empty() && _path.empty() && _query.empty() && _fragment.empty(); -} - - -bool URI::operator == (const URI& uri) const -{ - return equals(uri); -} - - -bool URI::operator == (const std::string& uri) const -{ - URI parsedURI(uri); - return equals(parsedURI); -} - - -bool URI::operator != (const URI& uri) const -{ - return !equals(uri); -} - - -bool URI::operator != (const std::string& uri) const -{ - URI parsedURI(uri); - return !equals(parsedURI); -} - - -bool URI::equals(const URI& uri) const -{ - return _scheme == uri._scheme - && _userInfo == uri._userInfo - && _host == uri._host - && getPort() == uri.getPort() - && _path == uri._path - && _query == uri._query - && _fragment == uri._fragment; -} - - -void URI::normalize() -{ - removeDotSegments(!isRelative()); -} - - -void URI::removeDotSegments(bool removeLeading) -{ - if (_path.empty()) return; - - bool leadingSlash = *(_path.begin()) == '/'; - bool trailingSlash = *(_path.rbegin()) == '/'; - std::vector segments; - std::vector normalizedSegments; - getPathSegments(segments); - for (std::vector::const_iterator it = segments.begin(); it != segments.end(); ++it) - { - if (*it == "..") - { - if (!normalizedSegments.empty()) - { - if (normalizedSegments.back() == "..") - normalizedSegments.push_back(*it); - else - normalizedSegments.pop_back(); - } - else if (!removeLeading) - { - normalizedSegments.push_back(*it); - } - } - else if (*it != ".") - { - normalizedSegments.push_back(*it); - } - } - buildPath(normalizedSegments, leadingSlash, trailingSlash); -} - - -void URI::getPathSegments(std::vector& segments) -{ - getPathSegments(_path, segments); -} - - -void URI::getPathSegments(const std::string& path, std::vector& segments) -{ - std::string::const_iterator it = path.begin(); - std::string::const_iterator end = path.end(); - std::string seg; - while (it != end) - { - if (*it == '/') - { - if (!seg.empty()) - { - segments.push_back(seg); - seg.clear(); - } - } - else seg += *it; - ++it; - } - if (!seg.empty()) - segments.push_back(seg); -} - - -void URI::encode(const std::string& str, const std::string& reserved, std::string& encodedStr) -{ - for (std::string::const_iterator it = str.begin(); it != str.end(); ++it) - { - char c = *it; - if (c >= 'a' && c <= 'z' || - c >= 'A' && c <= 'Z' || - c >= '0' && c <= '9' || - c == '-' || c == '_' || - c == '.' || c == '~') - { - encodedStr += c; - } - else if (c <= 0x20 || c >= 0x7F || ILLEGAL.find(c) != std::string::npos || reserved.find(c) != std::string::npos) - { - encodedStr += '%'; - encodedStr += NumberFormatter::formatHex((unsigned) (unsigned char) c, 2); - } - else encodedStr += c; - } -} - - -void URI::decode(const std::string& str, std::string& decodedStr) -{ - std::string::const_iterator it = str.begin(); - std::string::const_iterator end = str.end(); - while (it != end) - { - char c = *it++; - if (c == '%') - { - if (it == end) throw SyntaxException("URI encoding: no hex digit following percent sign", str); - char hi = *it++; - if (it == end) throw SyntaxException("URI encoding: two hex digits must follow percent sign", str); - char lo = *it++; - if (hi >= '0' && hi <= '9') - c = hi - '0'; - else if (hi >= 'A' && hi <= 'F') - c = hi - 'A' + 10; - else if (hi >= 'a' && hi <= 'f') - c = hi - 'a' + 10; - else throw SyntaxException("URI encoding: not a hex digit"); - c *= 16; - if (lo >= '0' && lo <= '9') - c += lo - '0'; - else if (lo >= 'A' && lo <= 'F') - c += lo - 'A' + 10; - else if (lo >= 'a' && lo <= 'f') - c += lo - 'a' + 10; - else throw SyntaxException("URI encoding: not a hex digit"); - } - decodedStr += c; - } -} - - -bool URI::isWellKnownPort() const -{ - return _port == getWellKnownPort(); -} - - -unsigned short URI::getWellKnownPort() const -{ - if (_scheme == "ftp") - return 21; - else if (_scheme == "ssh") - return 22; - else if (_scheme == "telnet") - return 23; - else if (_scheme == "http") - return 80; - else if (_scheme == "nntp") - return 119; - else if (_scheme == "ldap") - return 389; - else if (_scheme == "https") - return 443; - else - return 0; -} - - -void URI::parse(const std::string& uri) -{ - std::string::const_iterator it = uri.begin(); - std::string::const_iterator end = uri.end(); - if (it == end) return; - if (*it != '/' && *it != '.' && *it != '?' && *it != '#') - { - std::string scheme; - while (it != end && *it != ':' && *it != '?' && *it != '#' && *it != '/') scheme += *it++; - if (it != end && *it == ':') - { - ++it; - if (it == end) throw SyntaxException("URI scheme must be followed by authority or path", uri); - setScheme(scheme); - if (*it == '/') - { - ++it; - if (it != end && *it == '/') - { - ++it; - parseAuthority(it, end); - } - else --it; - } - parsePathEtc(it, end); - } - else - { - it = uri.begin(); - parsePathEtc(it, end); - } - } - else parsePathEtc(it, end); -} - - -void URI::parseAuthority(std::string::const_iterator& it, const std::string::const_iterator& end) -{ - std::string userInfo; - std::string part; - while (it != end && *it != '/' && *it != '?' && *it != '#') - { - if (*it == '@') - { - userInfo = part; - part.clear(); - } - else part += *it; - ++it; - } - std::string::const_iterator pbeg = part.begin(); - std::string::const_iterator pend = part.end(); - parseHostAndPort(pbeg, pend); - _userInfo = userInfo; -} - - -void URI::parseHostAndPort(std::string::const_iterator& it, const std::string::const_iterator& end) -{ - if (it == end) return; - std::string host; - if (*it == '[') - { - // IPv6 address - while (it != end && *it != ']') host += *it++; - if (it == end) throw SyntaxException("unterminated IPv6 address"); - host += *it++; - } - else - { - while (it != end && *it != ':') host += *it++; - } - if (it != end && *it == ':') - { - ++it; - std::string port; - while (it != end) port += *it++; - if (!port.empty()) - { - int nport = 0; - if (NumberParser::tryParse(port, nport) && nport > 0 && nport < 65536) - _port = (unsigned short) nport; - else - throw SyntaxException("bad or invalid port number", port); - } - else _port = getWellKnownPort(); - } - else _port = getWellKnownPort(); - _host = host; - toLowerInPlace(_host); -} - - -void URI::parsePath(std::string::const_iterator& it, const std::string::const_iterator& end) -{ - std::string path; - while (it != end && *it != '?' && *it != '#') path += *it++; - decode(path, _path); -} - - -void URI::parsePathEtc(std::string::const_iterator& it, const std::string::const_iterator& end) -{ - if (it == end) return; - if (*it != '?' && *it != '#') - parsePath(it, end); - if (it != end && *it == '?') - { - ++it; - parseQuery(it, end); - } - if (it != end && *it == '#') - { - ++it; - parseFragment(it, end); - } -} - - -void URI::parseQuery(std::string::const_iterator& it, const std::string::const_iterator& end) -{ - _query.clear(); - while (it != end && *it != '#') _query += *it++; -} - - -void URI::parseFragment(std::string::const_iterator& it, const std::string::const_iterator& end) -{ - std::string fragment; - while (it != end) fragment += *it++; - decode(fragment, _fragment); -} - - -void URI::mergePath(const std::string& path) -{ - std::vector segments; - std::vector normalizedSegments; - bool addLeadingSlash = false; - if (!_path.empty()) - { - getPathSegments(segments); - bool endsWithSlash = *(_path.rbegin()) == '/'; - if (!endsWithSlash && !segments.empty()) - segments.pop_back(); - addLeadingSlash = _path[0] == '/'; - } - getPathSegments(path, segments); - addLeadingSlash = addLeadingSlash || !path.empty() && path[0] == '/'; - bool hasTrailingSlash = !path.empty() && *(path.rbegin()) == '/'; - bool addTrailingSlash = false; - for (std::vector::const_iterator it = segments.begin(); it != segments.end(); ++it) - { - if (*it == "..") - { - addTrailingSlash = true; - if (!normalizedSegments.empty()) - normalizedSegments.pop_back(); - } - else if (*it != ".") - { - addTrailingSlash = false; - normalizedSegments.push_back(*it); - } - else addTrailingSlash = true; - } - buildPath(normalizedSegments, addLeadingSlash, hasTrailingSlash || addTrailingSlash); -} - - -void URI::buildPath(const std::vector& segments, bool leadingSlash, bool trailingSlash) -{ - _path.clear(); - bool first = true; - for (std::vector::const_iterator it = segments.begin(); it != segments.end(); ++it) - { - if (first) - { - first = false; - if (leadingSlash) - _path += '/'; - else if (_scheme.empty() && (*it).find(':') != std::string::npos) - _path.append("./"); - } - else _path += '/'; - _path.append(*it); - } - if (trailingSlash) - _path += '/'; -} - - -} // namespace Poco +// +// URI.cpp +// +// $Id: //poco/1.2/Foundation/src/URI.cpp#1 $ +// +// Library: Foundation +// Package: URI +// Module: URI +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/URI.h" +#include "Poco/NumberFormatter.h" +#include "Poco/Exception.h" +#include "Poco/String.h" +#include "Poco/NumberParser.h" + + +namespace Poco { + + +const std::string URI::RESERVED_PATH = "?#"; +const std::string URI::RESERVED_QUERY = "#"; +const std::string URI::RESERVED_FRAGMENT = ""; +const std::string URI::ILLEGAL = "%<>{}|\\\"^`"; + + +URI::URI(): + _port(0) +{ +} + + +URI::URI(const std::string& uri): + _port(0) +{ + parse(uri); +} + + +URI::URI(const char* uri): + _port(0) +{ + parse(std::string(uri)); +} + + +URI::URI(const std::string& scheme, const std::string& pathEtc): + _scheme(scheme), + _port(0) +{ + toLowerInPlace(_scheme); + _port = getWellKnownPort(); + std::string::const_iterator beg = pathEtc.begin(); + std::string::const_iterator end = pathEtc.end(); + parsePathEtc(beg, end); +} + + +URI::URI(const std::string& scheme, const std::string& authority, const std::string& pathEtc): + _scheme(scheme) +{ + toLowerInPlace(_scheme); + std::string::const_iterator beg = authority.begin(); + std::string::const_iterator end = authority.end(); + parseAuthority(beg, end); + beg = pathEtc.begin(); + end = pathEtc.end(); + parsePathEtc(beg, end); +} + + +URI::URI(const std::string& scheme, const std::string& authority, const std::string& path, const std::string& query): + _scheme(scheme), + _path(path), + _query(query) +{ + toLowerInPlace(_scheme); + std::string::const_iterator beg = authority.begin(); + std::string::const_iterator end = authority.end(); + parseAuthority(beg, end); +} + + +URI::URI(const std::string& scheme, const std::string& authority, const std::string& path, const std::string& query, const std::string& fragment): + _scheme(scheme), + _path(path), + _query(query), + _fragment(fragment) +{ + toLowerInPlace(_scheme); + std::string::const_iterator beg = authority.begin(); + std::string::const_iterator end = authority.end(); + parseAuthority(beg, end); +} + + +URI::URI(const URI& uri): + _scheme(uri._scheme), + _userInfo(uri._userInfo), + _host(uri._host), + _port(uri._port), + _path(uri._path), + _query(uri._query), + _fragment(uri._fragment) +{ +} + + +URI::URI(const URI& baseURI, const std::string& relativeURI): + _scheme(baseURI._scheme), + _userInfo(baseURI._userInfo), + _host(baseURI._host), + _port(baseURI._port), + _path(baseURI._path), + _query(baseURI._query), + _fragment(baseURI._fragment) +{ + resolve(relativeURI); +} + + +URI::~URI() +{ +} + + +URI& URI::operator = (const URI& uri) +{ + if (&uri != this) + { + _scheme = uri._scheme; + _userInfo = uri._userInfo; + _host = uri._host; + _port = uri._port; + _path = uri._path; + _query = uri._query; + _fragment = uri._fragment; + } + return *this; +} + + +URI& URI::operator = (const std::string& uri) +{ + clear(); + parse(uri); + return *this; +} + + +URI& URI::operator = (const char* uri) +{ + clear(); + parse(std::string(uri)); + return *this; +} + + +void URI::swap(URI& uri) +{ + std::swap(_scheme, uri._scheme); + std::swap(_userInfo, uri._userInfo); + std::swap(_host, uri._host); + std::swap(_port, uri._port); + std::swap(_path, uri._path); + std::swap(_query, uri._query); + std::swap(_fragment, uri._fragment); +} + + +void URI::clear() +{ + _scheme.clear(); + _userInfo.clear(); + _host.clear(); + _port = 0; + _path.clear(); + _query.clear(); + _fragment.clear(); +} + + +std::string URI::toString() const +{ + std::string uri; + if (isRelative()) + { + encode(_path, RESERVED_PATH, uri); + } + else + { + uri = _scheme; + uri += ':'; + std::string auth = getAuthority(); + if (!auth.empty() || _scheme == "file") + { + uri.append("//"); + uri.append(auth); + } + if (!_path.empty()) + { + if (!auth.empty() && _path[0] != '/') + uri += '/'; + encode(_path, RESERVED_PATH, uri); + } + } + if (!_query.empty()) + { + uri += '?'; + uri.append(_query); + } + if (!_fragment.empty()) + { + uri += '#'; + encode(_fragment, RESERVED_FRAGMENT, uri); + } + return uri; +} + + +void URI::setScheme(const std::string& scheme) +{ + _scheme = scheme; + toLowerInPlace(_scheme); + if (_port == 0) + _port = getWellKnownPort(); +} + + +void URI::setUserInfo(const std::string& userInfo) +{ + _userInfo.clear(); + decode(userInfo, _userInfo); +} + + +void URI::setHost(const std::string& host) +{ + _host = host; +} + + +unsigned short URI::getPort() const +{ + if (_port == 0) + return getWellKnownPort(); + else + return _port; +} + + +void URI::setPort(unsigned short port) +{ + _port = port; +} + + +std::string URI::getAuthority() const +{ + std::string auth; + if (!_userInfo.empty()) + { + auth.append(_userInfo); + auth += '@'; + } + auth.append(_host); + if (_port && !isWellKnownPort()) + { + auth += ':'; + auth.append(NumberFormatter::format(_port)); + } + return auth; +} + + +void URI::setAuthority(const std::string& authority) +{ + _userInfo.clear(); + _host.clear(); + _port = 0; + std::string::const_iterator beg = authority.begin(); + std::string::const_iterator end = authority.end(); + parseAuthority(beg, end); +} + + +void URI::setPath(const std::string& path) +{ + _path.clear(); + decode(path, _path); +} + + +void URI::setRawQuery(const std::string& query) +{ + _query = query; +} + + +void URI::setQuery(const std::string& query) +{ + _query.clear(); + encode(query, RESERVED_QUERY, _query); +} + + +std::string URI::getQuery() const +{ + std::string query; + decode(_query, query); + return query; +} + + +void URI::setFragment(const std::string& fragment) +{ + _fragment.clear(); + decode(fragment, _fragment); +} + + +void URI::setPathEtc(const std::string& pathEtc) +{ + _path.clear(); + _query.clear(); + _fragment.clear(); + std::string::const_iterator beg = pathEtc.begin(); + std::string::const_iterator end = pathEtc.end(); + parsePathEtc(beg, end); +} + + +std::string URI::getPathEtc() const +{ + std::string pathEtc; + encode(_path, RESERVED_PATH, pathEtc); + if (!_query.empty()) + { + pathEtc += '?'; + encode(_query, RESERVED_QUERY, pathEtc); + } + if (!_fragment.empty()) + { + pathEtc += '#'; + encode(_fragment, RESERVED_FRAGMENT, pathEtc); + } + return pathEtc; +} + + +std::string URI::getPathAndQuery() const +{ + std::string pathAndQuery; + encode(_path, RESERVED_PATH, pathAndQuery); + if (!_query.empty()) + { + pathAndQuery += '?'; + encode(_query, RESERVED_QUERY, pathAndQuery); + } + return pathAndQuery; +} + + +void URI::resolve(const std::string& relativeURI) +{ + URI parsedURI(relativeURI); + resolve(parsedURI); +} + + +void URI::resolve(const URI& relativeURI) +{ + if (!relativeURI._scheme.empty()) + { + _scheme = relativeURI._scheme; + _userInfo = relativeURI._userInfo; + _host = relativeURI._host; + _port = relativeURI._port; + _path = relativeURI._path; + _query = relativeURI._query; + removeDotSegments(); + } + else + { + if (!relativeURI._host.empty()) + { + _userInfo = relativeURI._userInfo; + _host = relativeURI._host; + _port = relativeURI._port; + _path = relativeURI._path; + _query = relativeURI._query; + removeDotSegments(); + } + else + { + if (relativeURI._path.empty()) + { + if (!relativeURI._query.empty()) + _query = relativeURI._query; + } + else + { + if (relativeURI._path[0] == '/') + { + _path = relativeURI._path; + removeDotSegments(); + } + else + { + mergePath(relativeURI._path); + } + _query = relativeURI._query; + } + } + } + _fragment = relativeURI._fragment; +} + + +bool URI::isRelative() const +{ + return _scheme.empty(); +} + + +bool URI::empty() const +{ + return _scheme.empty() && _host.empty() && _path.empty() && _query.empty() && _fragment.empty(); +} + + +bool URI::operator == (const URI& uri) const +{ + return equals(uri); +} + + +bool URI::operator == (const std::string& uri) const +{ + URI parsedURI(uri); + return equals(parsedURI); +} + + +bool URI::operator != (const URI& uri) const +{ + return !equals(uri); +} + + +bool URI::operator != (const std::string& uri) const +{ + URI parsedURI(uri); + return !equals(parsedURI); +} + + +bool URI::equals(const URI& uri) const +{ + return _scheme == uri._scheme + && _userInfo == uri._userInfo + && _host == uri._host + && getPort() == uri.getPort() + && _path == uri._path + && _query == uri._query + && _fragment == uri._fragment; +} + + +void URI::normalize() +{ + removeDotSegments(!isRelative()); +} + + +void URI::removeDotSegments(bool removeLeading) +{ + if (_path.empty()) return; + + bool leadingSlash = *(_path.begin()) == '/'; + bool trailingSlash = *(_path.rbegin()) == '/'; + std::vector segments; + std::vector normalizedSegments; + getPathSegments(segments); + for (std::vector::const_iterator it = segments.begin(); it != segments.end(); ++it) + { + if (*it == "..") + { + if (!normalizedSegments.empty()) + { + if (normalizedSegments.back() == "..") + normalizedSegments.push_back(*it); + else + normalizedSegments.pop_back(); + } + else if (!removeLeading) + { + normalizedSegments.push_back(*it); + } + } + else if (*it != ".") + { + normalizedSegments.push_back(*it); + } + } + buildPath(normalizedSegments, leadingSlash, trailingSlash); +} + + +void URI::getPathSegments(std::vector& segments) +{ + getPathSegments(_path, segments); +} + + +void URI::getPathSegments(const std::string& path, std::vector& segments) +{ + std::string::const_iterator it = path.begin(); + std::string::const_iterator end = path.end(); + std::string seg; + while (it != end) + { + if (*it == '/') + { + if (!seg.empty()) + { + segments.push_back(seg); + seg.clear(); + } + } + else seg += *it; + ++it; + } + if (!seg.empty()) + segments.push_back(seg); +} + + +void URI::encode(const std::string& str, const std::string& reserved, std::string& encodedStr) +{ + for (std::string::const_iterator it = str.begin(); it != str.end(); ++it) + { + char c = *it; + if (c >= 'a' && c <= 'z' || + c >= 'A' && c <= 'Z' || + c >= '0' && c <= '9' || + c == '-' || c == '_' || + c == '.' || c == '~') + { + encodedStr += c; + } + else if (c <= 0x20 || c >= 0x7F || ILLEGAL.find(c) != std::string::npos || reserved.find(c) != std::string::npos) + { + encodedStr += '%'; + encodedStr += NumberFormatter::formatHex((unsigned) (unsigned char) c, 2); + } + else encodedStr += c; + } +} + + +void URI::decode(const std::string& str, std::string& decodedStr) +{ + std::string::const_iterator it = str.begin(); + std::string::const_iterator end = str.end(); + while (it != end) + { + char c = *it++; + if (c == '%') + { + if (it == end) throw SyntaxException("URI encoding: no hex digit following percent sign", str); + char hi = *it++; + if (it == end) throw SyntaxException("URI encoding: two hex digits must follow percent sign", str); + char lo = *it++; + if (hi >= '0' && hi <= '9') + c = hi - '0'; + else if (hi >= 'A' && hi <= 'F') + c = hi - 'A' + 10; + else if (hi >= 'a' && hi <= 'f') + c = hi - 'a' + 10; + else throw SyntaxException("URI encoding: not a hex digit"); + c *= 16; + if (lo >= '0' && lo <= '9') + c += lo - '0'; + else if (lo >= 'A' && lo <= 'F') + c += lo - 'A' + 10; + else if (lo >= 'a' && lo <= 'f') + c += lo - 'a' + 10; + else throw SyntaxException("URI encoding: not a hex digit"); + } + decodedStr += c; + } +} + + +bool URI::isWellKnownPort() const +{ + return _port == getWellKnownPort(); +} + + +unsigned short URI::getWellKnownPort() const +{ + if (_scheme == "ftp") + return 21; + else if (_scheme == "ssh") + return 22; + else if (_scheme == "telnet") + return 23; + else if (_scheme == "http") + return 80; + else if (_scheme == "nntp") + return 119; + else if (_scheme == "ldap") + return 389; + else if (_scheme == "https") + return 443; + else + return 0; +} + + +void URI::parse(const std::string& uri) +{ + std::string::const_iterator it = uri.begin(); + std::string::const_iterator end = uri.end(); + if (it == end) return; + if (*it != '/' && *it != '.' && *it != '?' && *it != '#') + { + std::string scheme; + while (it != end && *it != ':' && *it != '?' && *it != '#' && *it != '/') scheme += *it++; + if (it != end && *it == ':') + { + ++it; + if (it == end) throw SyntaxException("URI scheme must be followed by authority or path", uri); + setScheme(scheme); + if (*it == '/') + { + ++it; + if (it != end && *it == '/') + { + ++it; + parseAuthority(it, end); + } + else --it; + } + parsePathEtc(it, end); + } + else + { + it = uri.begin(); + parsePathEtc(it, end); + } + } + else parsePathEtc(it, end); +} + + +void URI::parseAuthority(std::string::const_iterator& it, const std::string::const_iterator& end) +{ + std::string userInfo; + std::string part; + while (it != end && *it != '/' && *it != '?' && *it != '#') + { + if (*it == '@') + { + userInfo = part; + part.clear(); + } + else part += *it; + ++it; + } + std::string::const_iterator pbeg = part.begin(); + std::string::const_iterator pend = part.end(); + parseHostAndPort(pbeg, pend); + _userInfo = userInfo; +} + + +void URI::parseHostAndPort(std::string::const_iterator& it, const std::string::const_iterator& end) +{ + if (it == end) return; + std::string host; + if (*it == '[') + { + // IPv6 address + while (it != end && *it != ']') host += *it++; + if (it == end) throw SyntaxException("unterminated IPv6 address"); + host += *it++; + } + else + { + while (it != end && *it != ':') host += *it++; + } + if (it != end && *it == ':') + { + ++it; + std::string port; + while (it != end) port += *it++; + if (!port.empty()) + { + int nport = 0; + if (NumberParser::tryParse(port, nport) && nport > 0 && nport < 65536) + _port = (unsigned short) nport; + else + throw SyntaxException("bad or invalid port number", port); + } + else _port = getWellKnownPort(); + } + else _port = getWellKnownPort(); + _host = host; + toLowerInPlace(_host); +} + + +void URI::parsePath(std::string::const_iterator& it, const std::string::const_iterator& end) +{ + std::string path; + while (it != end && *it != '?' && *it != '#') path += *it++; + decode(path, _path); +} + + +void URI::parsePathEtc(std::string::const_iterator& it, const std::string::const_iterator& end) +{ + if (it == end) return; + if (*it != '?' && *it != '#') + parsePath(it, end); + if (it != end && *it == '?') + { + ++it; + parseQuery(it, end); + } + if (it != end && *it == '#') + { + ++it; + parseFragment(it, end); + } +} + + +void URI::parseQuery(std::string::const_iterator& it, const std::string::const_iterator& end) +{ + _query.clear(); + while (it != end && *it != '#') _query += *it++; +} + + +void URI::parseFragment(std::string::const_iterator& it, const std::string::const_iterator& end) +{ + std::string fragment; + while (it != end) fragment += *it++; + decode(fragment, _fragment); +} + + +void URI::mergePath(const std::string& path) +{ + std::vector segments; + std::vector normalizedSegments; + bool addLeadingSlash = false; + if (!_path.empty()) + { + getPathSegments(segments); + bool endsWithSlash = *(_path.rbegin()) == '/'; + if (!endsWithSlash && !segments.empty()) + segments.pop_back(); + addLeadingSlash = _path[0] == '/'; + } + getPathSegments(path, segments); + addLeadingSlash = addLeadingSlash || !path.empty() && path[0] == '/'; + bool hasTrailingSlash = !path.empty() && *(path.rbegin()) == '/'; + bool addTrailingSlash = false; + for (std::vector::const_iterator it = segments.begin(); it != segments.end(); ++it) + { + if (*it == "..") + { + addTrailingSlash = true; + if (!normalizedSegments.empty()) + normalizedSegments.pop_back(); + } + else if (*it != ".") + { + addTrailingSlash = false; + normalizedSegments.push_back(*it); + } + else addTrailingSlash = true; + } + buildPath(normalizedSegments, addLeadingSlash, hasTrailingSlash || addTrailingSlash); +} + + +void URI::buildPath(const std::vector& segments, bool leadingSlash, bool trailingSlash) +{ + _path.clear(); + bool first = true; + for (std::vector::const_iterator it = segments.begin(); it != segments.end(); ++it) + { + if (first) + { + first = false; + if (leadingSlash) + _path += '/'; + else if (_scheme.empty() && (*it).find(':') != std::string::npos) + _path.append("./"); + } + else _path += '/'; + _path.append(*it); + } + if (trailingSlash) + _path += '/'; +} + + +} // namespace Poco diff --git a/Foundation/src/URIStreamFactory.cpp b/Foundation/src/URIStreamFactory.cpp index c3b0a0cb7..1c5e645ea 100644 --- a/Foundation/src/URIStreamFactory.cpp +++ b/Foundation/src/URIStreamFactory.cpp @@ -1,53 +1,53 @@ -// -// URIStreamFactory.cpp -// -// $Id: //poco/1.2/Foundation/src/URIStreamFactory.cpp#1 $ -// -// Library: Foundation -// Package: URI -// Module: URIStreamFactory -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/URIStreamFactory.h" - - -namespace Poco { - - -URIStreamFactory::URIStreamFactory() -{ -} - - -URIStreamFactory::~URIStreamFactory() -{ -} - - -} // namespace Poco +// +// URIStreamFactory.cpp +// +// $Id: //poco/1.2/Foundation/src/URIStreamFactory.cpp#1 $ +// +// Library: Foundation +// Package: URI +// Module: URIStreamFactory +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/URIStreamFactory.h" + + +namespace Poco { + + +URIStreamFactory::URIStreamFactory() +{ +} + + +URIStreamFactory::~URIStreamFactory() +{ +} + + +} // namespace Poco diff --git a/Foundation/src/URIStreamOpener.cpp b/Foundation/src/URIStreamOpener.cpp index d589b6656..ec3eaed54 100644 --- a/Foundation/src/URIStreamOpener.cpp +++ b/Foundation/src/URIStreamOpener.cpp @@ -1,174 +1,174 @@ -// -// URIStreamOpener.cpp -// -// $Id: //poco/1.2/Foundation/src/URIStreamOpener.cpp#1 $ -// -// Library: Foundation -// Package: URI -// Module: URIStreamOpener -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/URIStreamOpener.h" -#include "Poco/URIStreamFactory.h" -#include "Poco/FileStreamFactory.h" -#include "Poco/URI.h" -#include "Poco/Path.h" -#include "Poco/SingletonHolder.h" -#include "Poco/Exception.h" - - -namespace Poco { - - -URIStreamOpener::URIStreamOpener() -{ - registerStreamFactory("file", new FileStreamFactory); -} - - -URIStreamOpener::~URIStreamOpener() -{ - for (FactoryMap::iterator it = _map.begin(); it != _map.end(); ++it) - delete it->second; -} - - -std::istream* URIStreamOpener::open(const URI& uri) const -{ - FastMutex::ScopedLock lock(_mutex); - - std::string scheme; - if (uri.isRelative()) - scheme = "file"; - else - scheme = uri.getScheme(); - FactoryMap::const_iterator it = _map.find(scheme); - if (it != _map.end()) - return it->second->open(uri); - else - throw UnknownURISchemeException(scheme); -} - - -std::istream* URIStreamOpener::open(const std::string& pathOrURI) const -{ - FastMutex::ScopedLock lock(_mutex); - - try - { - URI uri(pathOrURI); - std::string scheme(uri.getScheme()); - FactoryMap::const_iterator it = _map.find(scheme); - if (it != _map.end()) - return it->second->open(uri); - } - catch (Exception&) - { - } - Path path(pathOrURI, Path::PATH_GUESS); - return openFile(path); -} - - -std::istream* URIStreamOpener::open(const std::string& basePathOrURI, const std::string& pathOrURI) const -{ - FastMutex::ScopedLock lock(_mutex); - - try - { - URI uri(basePathOrURI); - std::string scheme(uri.getScheme()); - FactoryMap::const_iterator it = _map.find(scheme); - if (it != _map.end()) - { - uri.resolve(pathOrURI); - return it->second->open(uri); - } - } - catch (Exception&) - { - } - Path base(basePathOrURI, Path::PATH_GUESS); - Path path(pathOrURI, Path::PATH_GUESS); - base.resolve(path); - return openFile(base); -} - - -void URIStreamOpener::registerStreamFactory(const std::string& scheme, URIStreamFactory* pFactory) -{ - poco_check_ptr (pFactory); - - FastMutex::ScopedLock lock(_mutex); - if (_map.find(scheme) == _map.end()) - { - _map[scheme] = pFactory; - } - else throw ExistsException("An URIStreamFactory for the given scheme has already been registered", scheme); -} - - -void URIStreamOpener::unregisterStreamFactory(const std::string& scheme) -{ - FastMutex::ScopedLock lock(_mutex); - - FactoryMap::iterator it = _map.find(scheme); - if (it != _map.end()) - { - URIStreamFactory* pFactory = it->second; - _map.erase(it); - delete pFactory; - } - else throw NotFoundException("No URIStreamFactory has been registered for the given scheme", scheme); -} - - -bool URIStreamOpener::supportsScheme(const std::string& scheme) -{ - FastMutex::ScopedLock lock(_mutex); - return _map.find(scheme) != _map.end(); -} - - -URIStreamOpener& URIStreamOpener::defaultOpener() -{ - static SingletonHolder sh; - return *sh.get(); -} - - -std::istream* URIStreamOpener::openFile(const Path& path) const -{ - FileStreamFactory factory; - return factory.open(path); -} - - - -} // namespace Poco +// +// URIStreamOpener.cpp +// +// $Id: //poco/1.2/Foundation/src/URIStreamOpener.cpp#1 $ +// +// Library: Foundation +// Package: URI +// Module: URIStreamOpener +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/URIStreamOpener.h" +#include "Poco/URIStreamFactory.h" +#include "Poco/FileStreamFactory.h" +#include "Poco/URI.h" +#include "Poco/Path.h" +#include "Poco/SingletonHolder.h" +#include "Poco/Exception.h" + + +namespace Poco { + + +URIStreamOpener::URIStreamOpener() +{ + registerStreamFactory("file", new FileStreamFactory); +} + + +URIStreamOpener::~URIStreamOpener() +{ + for (FactoryMap::iterator it = _map.begin(); it != _map.end(); ++it) + delete it->second; +} + + +std::istream* URIStreamOpener::open(const URI& uri) const +{ + FastMutex::ScopedLock lock(_mutex); + + std::string scheme; + if (uri.isRelative()) + scheme = "file"; + else + scheme = uri.getScheme(); + FactoryMap::const_iterator it = _map.find(scheme); + if (it != _map.end()) + return it->second->open(uri); + else + throw UnknownURISchemeException(scheme); +} + + +std::istream* URIStreamOpener::open(const std::string& pathOrURI) const +{ + FastMutex::ScopedLock lock(_mutex); + + try + { + URI uri(pathOrURI); + std::string scheme(uri.getScheme()); + FactoryMap::const_iterator it = _map.find(scheme); + if (it != _map.end()) + return it->second->open(uri); + } + catch (Exception&) + { + } + Path path(pathOrURI, Path::PATH_GUESS); + return openFile(path); +} + + +std::istream* URIStreamOpener::open(const std::string& basePathOrURI, const std::string& pathOrURI) const +{ + FastMutex::ScopedLock lock(_mutex); + + try + { + URI uri(basePathOrURI); + std::string scheme(uri.getScheme()); + FactoryMap::const_iterator it = _map.find(scheme); + if (it != _map.end()) + { + uri.resolve(pathOrURI); + return it->second->open(uri); + } + } + catch (Exception&) + { + } + Path base(basePathOrURI, Path::PATH_GUESS); + Path path(pathOrURI, Path::PATH_GUESS); + base.resolve(path); + return openFile(base); +} + + +void URIStreamOpener::registerStreamFactory(const std::string& scheme, URIStreamFactory* pFactory) +{ + poco_check_ptr (pFactory); + + FastMutex::ScopedLock lock(_mutex); + if (_map.find(scheme) == _map.end()) + { + _map[scheme] = pFactory; + } + else throw ExistsException("An URIStreamFactory for the given scheme has already been registered", scheme); +} + + +void URIStreamOpener::unregisterStreamFactory(const std::string& scheme) +{ + FastMutex::ScopedLock lock(_mutex); + + FactoryMap::iterator it = _map.find(scheme); + if (it != _map.end()) + { + URIStreamFactory* pFactory = it->second; + _map.erase(it); + delete pFactory; + } + else throw NotFoundException("No URIStreamFactory has been registered for the given scheme", scheme); +} + + +bool URIStreamOpener::supportsScheme(const std::string& scheme) +{ + FastMutex::ScopedLock lock(_mutex); + return _map.find(scheme) != _map.end(); +} + + +URIStreamOpener& URIStreamOpener::defaultOpener() +{ + static SingletonHolder sh; + return *sh.get(); +} + + +std::istream* URIStreamOpener::openFile(const Path& path) const +{ + FileStreamFactory factory; + return factory.open(path); +} + + + +} // namespace Poco diff --git a/Foundation/src/UTF16Encoding.cpp b/Foundation/src/UTF16Encoding.cpp index 40ec6a578..8695546c4 100644 --- a/Foundation/src/UTF16Encoding.cpp +++ b/Foundation/src/UTF16Encoding.cpp @@ -1,161 +1,161 @@ -// -// UTF16Encoding.cpp -// -// $Id: //poco/1.2/Foundation/src/UTF16Encoding.cpp#1 $ -// -// Library: Foundation -// Package: Text -// Module: UTF16Encoding -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/UTF16Encoding.h" -#include "Poco/ByteOrder.h" - - -namespace Poco { - - -const TextEncoding::CharacterMap UTF16Encoding::_charMap = -{ - /* 00 */ -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, - /* 10 */ -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, - /* 20 */ -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, - /* 30 */ -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, - /* 40 */ -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, - /* 50 */ -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, - /* 60 */ -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, - /* 70 */ -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, - /* 80 */ -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, - /* 90 */ -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, - /* a0 */ -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, - /* b0 */ -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, - /* c0 */ -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, - /* d0 */ -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, - /* e0 */ -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, - /* f0 */ -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -}; - - -UTF16Encoding::UTF16Encoding(ByteOrderType byteOrder) -{ - setByteOrder(byteOrder); -} - - -UTF16Encoding::UTF16Encoding(int byteOrderMark) -{ - setByteOrder(byteOrderMark); -} - - -UTF16Encoding::~UTF16Encoding() -{ -} - - -UTF16Encoding::ByteOrderType UTF16Encoding::getByteOrder() const -{ -#if defined(POCO_ARCH_BIG_ENDIAN) - return _flipBytes ? LITTLE_ENDIAN_BYTE_ORDER : BIG_ENDIAN_BYTE_ORDER; -#else - return _flipBytes ? BIG_ENDIAN_BYTE_ORDER : LITTLE_ENDIAN_BYTE_ORDER; -#endif -} - - -void UTF16Encoding::setByteOrder(ByteOrderType byteOrder) -{ -#if defined(POCO_ARCH_BIG_ENDIAN) - _flipBytes = byteOrder == LITTLE_ENDIAN_BYTE_ORDER; -#else - _flipBytes = byteOrder == BIG_ENDIAN_BYTE_ORDER;; -#endif -} - - -void UTF16Encoding::setByteOrder(int byteOrderMark) -{ - _flipBytes = byteOrderMark != 0xFEFF; -} - - -const TextEncoding::CharacterMap& UTF16Encoding::characterMap() const -{ - return _charMap; -} - - -int UTF16Encoding::convert(const unsigned char* bytes) const -{ - UInt16 uc; - unsigned char* p = (unsigned char*) &uc; - *p++ = *bytes++; - *p++ = *bytes++; - return _flipBytes ? ByteOrder::flipBytes(uc) : uc; -} - - -int UTF16Encoding::convert(int ch, unsigned char* bytes, int length) const -{ - if (ch <= 0xFFFF) - { - if (length >= 2) - { - UInt16 ch1 = _flipBytes ? ByteOrder::flipBytes((UInt16) ch) : (UInt16) ch; - unsigned char* p = (unsigned char*) &ch1; - *bytes++ = *p++; - *bytes++ = *p++; - } - return 2; - } - else - { - if (length >= 4) - { - int ch1 = ch - 0x10000; - UInt16 w1 = 0xD800 + ((ch1 >> 10) & 0x3FF); - UInt16 w2 = 0xDC00 + (ch1 & 0x3FF); - if (_flipBytes) - { - w1 = ByteOrder::flipBytes(w1); - w2 = ByteOrder::flipBytes(w2); - } - unsigned char* p = (unsigned char*) &w1; - *bytes++ = *p++; - *bytes++ = *p++; - p = (unsigned char*) &w2; - *bytes++ = *p++; - *bytes++ = *p++; - } - return 4; - } -} - - -} // namespace Poco +// +// UTF16Encoding.cpp +// +// $Id: //poco/1.2/Foundation/src/UTF16Encoding.cpp#1 $ +// +// Library: Foundation +// Package: Text +// Module: UTF16Encoding +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/UTF16Encoding.h" +#include "Poco/ByteOrder.h" + + +namespace Poco { + + +const TextEncoding::CharacterMap UTF16Encoding::_charMap = +{ + /* 00 */ -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, + /* 10 */ -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, + /* 20 */ -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, + /* 30 */ -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, + /* 40 */ -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, + /* 50 */ -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, + /* 60 */ -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, + /* 70 */ -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, + /* 80 */ -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, + /* 90 */ -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, + /* a0 */ -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, + /* b0 */ -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, + /* c0 */ -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, + /* d0 */ -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, + /* e0 */ -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, + /* f0 */ -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, +}; + + +UTF16Encoding::UTF16Encoding(ByteOrderType byteOrder) +{ + setByteOrder(byteOrder); +} + + +UTF16Encoding::UTF16Encoding(int byteOrderMark) +{ + setByteOrder(byteOrderMark); +} + + +UTF16Encoding::~UTF16Encoding() +{ +} + + +UTF16Encoding::ByteOrderType UTF16Encoding::getByteOrder() const +{ +#if defined(POCO_ARCH_BIG_ENDIAN) + return _flipBytes ? LITTLE_ENDIAN_BYTE_ORDER : BIG_ENDIAN_BYTE_ORDER; +#else + return _flipBytes ? BIG_ENDIAN_BYTE_ORDER : LITTLE_ENDIAN_BYTE_ORDER; +#endif +} + + +void UTF16Encoding::setByteOrder(ByteOrderType byteOrder) +{ +#if defined(POCO_ARCH_BIG_ENDIAN) + _flipBytes = byteOrder == LITTLE_ENDIAN_BYTE_ORDER; +#else + _flipBytes = byteOrder == BIG_ENDIAN_BYTE_ORDER;; +#endif +} + + +void UTF16Encoding::setByteOrder(int byteOrderMark) +{ + _flipBytes = byteOrderMark != 0xFEFF; +} + + +const TextEncoding::CharacterMap& UTF16Encoding::characterMap() const +{ + return _charMap; +} + + +int UTF16Encoding::convert(const unsigned char* bytes) const +{ + UInt16 uc; + unsigned char* p = (unsigned char*) &uc; + *p++ = *bytes++; + *p++ = *bytes++; + return _flipBytes ? ByteOrder::flipBytes(uc) : uc; +} + + +int UTF16Encoding::convert(int ch, unsigned char* bytes, int length) const +{ + if (ch <= 0xFFFF) + { + if (length >= 2) + { + UInt16 ch1 = _flipBytes ? ByteOrder::flipBytes((UInt16) ch) : (UInt16) ch; + unsigned char* p = (unsigned char*) &ch1; + *bytes++ = *p++; + *bytes++ = *p++; + } + return 2; + } + else + { + if (length >= 4) + { + int ch1 = ch - 0x10000; + UInt16 w1 = 0xD800 + ((ch1 >> 10) & 0x3FF); + UInt16 w2 = 0xDC00 + (ch1 & 0x3FF); + if (_flipBytes) + { + w1 = ByteOrder::flipBytes(w1); + w2 = ByteOrder::flipBytes(w2); + } + unsigned char* p = (unsigned char*) &w1; + *bytes++ = *p++; + *bytes++ = *p++; + p = (unsigned char*) &w2; + *bytes++ = *p++; + *bytes++ = *p++; + } + return 4; + } +} + + +} // namespace Poco diff --git a/Foundation/src/UTF8Encoding.cpp b/Foundation/src/UTF8Encoding.cpp index a68f353d8..8485d061e 100644 --- a/Foundation/src/UTF8Encoding.cpp +++ b/Foundation/src/UTF8Encoding.cpp @@ -1,160 +1,160 @@ -// -// UTF8Encoding.cpp -// -// $Id: //poco/1.2/Foundation/src/UTF8Encoding.cpp#1 $ -// -// Library: Foundation -// Package: Text -// Module: UTF8Encoding -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/UTF8Encoding.h" - - -namespace Poco { - - -const TextEncoding::CharacterMap UTF8Encoding::_charMap = -{ - /* 00 */ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, - /* 10 */ 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, - /* 20 */ 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, - /* 30 */ 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, - /* 40 */ 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, - /* 50 */ 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, - /* 60 */ 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, - /* 70 */ 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, - /* 80 */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - /* 90 */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - /* a0 */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - /* b0 */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - /* c0 */ -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, - /* d0 */ -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, - /* e0 */ -3, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3, - /* f0 */ -4, -4, -4, -4, -4, -4, -4, -4, -5, -5, -5, -5, -6, -6, -1, -1, -}; - - -UTF8Encoding::UTF8Encoding() -{ -} - - -UTF8Encoding::~UTF8Encoding() -{ -} - - -const TextEncoding::CharacterMap& UTF8Encoding::characterMap() const -{ - return _charMap; -} - - -int UTF8Encoding::convert(const unsigned char* bytes) const -{ - int n = _charMap[*bytes]; - int uc; - switch (n) - { - case -6: - uc = *bytes & 0x01; break; - case -5: - uc = *bytes & 0x03; break; - case -4: - uc = *bytes & 0x07; break; - case -3: - uc = *bytes & 0x0F; break; - case -2: - uc = *bytes & 0x1F; break; - default: - uc = n; - } - while (n++ < -1) - { - // TODO: check for malformed or overlong sequences - uc <<= 6; - uc |= (*++bytes & 0x3F); - } - return uc; -} - - -int UTF8Encoding::convert(int ch, unsigned char* bytes, int length) const -{ - if (ch <= 0x7F && length >= 1) - { - *bytes = (unsigned char) ch; - return 1; - } - else if (ch <= 0x7FF && length >= 2) - { - *bytes++ = (unsigned char) ((ch >> 6) & 0x1F | 0xC0); - *bytes = (unsigned char) ((ch & 0x3F) | 0x80); - return 2; - } - else if (ch <= 0xFFFF && length >= 3) - { - *bytes++ = (unsigned char) ((ch >> 12) & 0x0F | 0xE0); - *bytes++ = (unsigned char) ((ch >> 6) & 0x3F | 0x80); - *bytes = (unsigned char) ((ch & 0x3F) | 0x80); - return 3; - } - else if (ch <= 0x1FFFFF && length >= 4) - { - *bytes++ = (unsigned char) ((ch >> 18) & 0x07 | 0xF0); - *bytes++ = (unsigned char) ((ch >> 12) & 0x3F | 0x80); - *bytes++ = (unsigned char) ((ch >> 6) & 0x3F | 0x80); - *bytes = (unsigned char) ((ch & 0x3F) | 0x80); - return 4; - } - else if (ch <= 0x3FFFFFF && length >= 5) - { - *bytes++ = (unsigned char) ((ch >> 24) & 0x03 | 0xF8); - *bytes++ = (unsigned char) ((ch >> 18) & 0x3F | 0x80); - *bytes++ = (unsigned char) ((ch >> 12) & 0x3F | 0x80); - *bytes++ = (unsigned char) ((ch >> 6) & 0x3F | 0x80); - *bytes = (unsigned char) ((ch & 0x3F) | 0x80); - return 5; - } - else if (ch <= 0x7FFFFFFF && length >= 6) - { - *bytes++ = (unsigned char) ((ch >> 30) & 0x01 | 0xFC); - *bytes++ = (unsigned char) ((ch >> 24) & 0x3F | 0x80); - *bytes++ = (unsigned char) ((ch >> 18) & 0x3F | 0x80); - *bytes++ = (unsigned char) ((ch >> 12) & 0x3F | 0x80); - *bytes++ = (unsigned char) ((ch >> 6) & 0x3F | 0x80); - *bytes = (unsigned char) ((ch & 0x3F) | 0x80); - return 6; - } - else return 0; -} - - -} // namespace Poco +// +// UTF8Encoding.cpp +// +// $Id: //poco/1.2/Foundation/src/UTF8Encoding.cpp#1 $ +// +// Library: Foundation +// Package: Text +// Module: UTF8Encoding +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/UTF8Encoding.h" + + +namespace Poco { + + +const TextEncoding::CharacterMap UTF8Encoding::_charMap = +{ + /* 00 */ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, + /* 10 */ 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, + /* 20 */ 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, + /* 30 */ 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, + /* 40 */ 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, + /* 50 */ 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, + /* 60 */ 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, + /* 70 */ 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, + /* 80 */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + /* 90 */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + /* a0 */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + /* b0 */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + /* c0 */ -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, + /* d0 */ -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, + /* e0 */ -3, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3, + /* f0 */ -4, -4, -4, -4, -4, -4, -4, -4, -5, -5, -5, -5, -6, -6, -1, -1, +}; + + +UTF8Encoding::UTF8Encoding() +{ +} + + +UTF8Encoding::~UTF8Encoding() +{ +} + + +const TextEncoding::CharacterMap& UTF8Encoding::characterMap() const +{ + return _charMap; +} + + +int UTF8Encoding::convert(const unsigned char* bytes) const +{ + int n = _charMap[*bytes]; + int uc; + switch (n) + { + case -6: + uc = *bytes & 0x01; break; + case -5: + uc = *bytes & 0x03; break; + case -4: + uc = *bytes & 0x07; break; + case -3: + uc = *bytes & 0x0F; break; + case -2: + uc = *bytes & 0x1F; break; + default: + uc = n; + } + while (n++ < -1) + { + // TODO: check for malformed or overlong sequences + uc <<= 6; + uc |= (*++bytes & 0x3F); + } + return uc; +} + + +int UTF8Encoding::convert(int ch, unsigned char* bytes, int length) const +{ + if (ch <= 0x7F && length >= 1) + { + *bytes = (unsigned char) ch; + return 1; + } + else if (ch <= 0x7FF && length >= 2) + { + *bytes++ = (unsigned char) ((ch >> 6) & 0x1F | 0xC0); + *bytes = (unsigned char) ((ch & 0x3F) | 0x80); + return 2; + } + else if (ch <= 0xFFFF && length >= 3) + { + *bytes++ = (unsigned char) ((ch >> 12) & 0x0F | 0xE0); + *bytes++ = (unsigned char) ((ch >> 6) & 0x3F | 0x80); + *bytes = (unsigned char) ((ch & 0x3F) | 0x80); + return 3; + } + else if (ch <= 0x1FFFFF && length >= 4) + { + *bytes++ = (unsigned char) ((ch >> 18) & 0x07 | 0xF0); + *bytes++ = (unsigned char) ((ch >> 12) & 0x3F | 0x80); + *bytes++ = (unsigned char) ((ch >> 6) & 0x3F | 0x80); + *bytes = (unsigned char) ((ch & 0x3F) | 0x80); + return 4; + } + else if (ch <= 0x3FFFFFF && length >= 5) + { + *bytes++ = (unsigned char) ((ch >> 24) & 0x03 | 0xF8); + *bytes++ = (unsigned char) ((ch >> 18) & 0x3F | 0x80); + *bytes++ = (unsigned char) ((ch >> 12) & 0x3F | 0x80); + *bytes++ = (unsigned char) ((ch >> 6) & 0x3F | 0x80); + *bytes = (unsigned char) ((ch & 0x3F) | 0x80); + return 5; + } + else if (ch <= 0x7FFFFFFF && length >= 6) + { + *bytes++ = (unsigned char) ((ch >> 30) & 0x01 | 0xFC); + *bytes++ = (unsigned char) ((ch >> 24) & 0x3F | 0x80); + *bytes++ = (unsigned char) ((ch >> 18) & 0x3F | 0x80); + *bytes++ = (unsigned char) ((ch >> 12) & 0x3F | 0x80); + *bytes++ = (unsigned char) ((ch >> 6) & 0x3F | 0x80); + *bytes = (unsigned char) ((ch & 0x3F) | 0x80); + return 6; + } + else return 0; +} + + +} // namespace Poco diff --git a/Foundation/src/UUID.cpp b/Foundation/src/UUID.cpp index 76c22aa55..de8372246 100644 --- a/Foundation/src/UUID.cpp +++ b/Foundation/src/UUID.cpp @@ -1,372 +1,372 @@ -// -// UUID.cpp -// -// $Id: //poco/1.2/Foundation/src/UUID.cpp#1 $ -// -// Library: Foundation -// Package: UUID -// Module: UUID -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/UUID.h" -#include "Poco/ByteOrder.h" -#include "Poco/Exception.h" -#include -#include - - -namespace Poco { - - -UUID::UUID(): - _timeLow(0), - _timeMid(0), - _timeHiAndVersion(0), - _clockSeq(0) -{ - memset(_node, 0, sizeof(_node)); -} - - -UUID::UUID(const UUID& uuid): - _timeLow(uuid._timeLow), - _timeMid(uuid._timeMid), - _timeHiAndVersion(uuid._timeHiAndVersion), - _clockSeq(uuid._clockSeq) -{ - memcpy(_node, uuid._node, sizeof(_node)); -} - - -UUID::UUID(const std::string& uuid) -{ - parse(uuid); -} - - -UUID::UUID(const char* uuid) -{ - poco_check_ptr (uuid); - parse(std::string(uuid)); -} - - -UUID::UUID(UInt32 timeLow, UInt32 timeMid, UInt32 timeHiAndVersion, UInt16 clockSeq, UInt8 node[]): - _timeLow(timeLow), - _timeMid(timeMid), - _timeHiAndVersion(timeHiAndVersion), - _clockSeq(clockSeq) -{ - memcpy(_node, node, sizeof(_node)); -} - - -UUID::UUID(const char* bytes, Version version) -{ - UInt32 i32; - UInt16 i16; - memcpy(&i32, bytes, sizeof(i32)); - _timeLow = ByteOrder::fromNetwork(i32); - bytes += sizeof(i32); - memcpy(&i16, bytes, sizeof(i16)); - _timeMid = ByteOrder::fromNetwork(i16); - bytes += sizeof(i16); - memcpy(&i16, bytes, sizeof(i16)); - _timeHiAndVersion = ByteOrder::fromNetwork(i16); - bytes += sizeof(i16); - memcpy(&i16, bytes, sizeof(i16)); - _clockSeq = ByteOrder::fromNetwork(i16); - bytes += sizeof(i16); - memcpy(_node, bytes, sizeof(_node)); - - _timeHiAndVersion &= 0x0FFF; - _timeHiAndVersion |= (version << 12); - _clockSeq &= 0x3FFF; - _clockSeq |= 0x8000; -} - - -UUID::~UUID() -{ -} - - -UUID& UUID::operator = (const UUID& uuid) -{ - if (&uuid != this) - { - _timeLow = uuid._timeLow; - _timeMid = uuid._timeMid; - _timeHiAndVersion = uuid._timeHiAndVersion; - _clockSeq = uuid._clockSeq; - memcpy(_node, uuid._node, sizeof(_node)); - } - return *this; -} - - -void UUID::swap(UUID& uuid) -{ - std::swap(_timeLow, uuid._timeLow); - std::swap(_timeMid, uuid._timeMid); - std::swap(_timeHiAndVersion, uuid._timeHiAndVersion); - std::swap(_clockSeq, uuid._clockSeq); - std::swap_ranges(_node, _node + 6, uuid._node); -} - - -void UUID::parse(const std::string& uuid) -{ - UInt32 timeLow = 0; - UInt16 timeMid = 0; - UInt16 timeHiAndVersion = 0; - UInt16 clockSeq = 0; - UInt8 node[6] = {0, 0, 0, 0, 0, 0}; - std::string::const_iterator it = uuid.begin(); - std::string::const_iterator end = uuid.end(); - if (it != end) - { - for (int i = 0; i < 8; ++i) - { - timeLow = timeLow*16 + nibble(*it++); - if (it == end) throw SyntaxException(uuid); - } - if (*it != '-') throw SyntaxException(uuid); - ++it; - for (int i = 0; i < 4; ++i) - { - timeMid = timeMid*16 + nibble(*it++); - if (it == end) throw SyntaxException(uuid); - } - if (*it != '-') throw SyntaxException(uuid); - ++it; - for (int i = 0; i < 4; ++i) - { - timeHiAndVersion = timeHiAndVersion*16 + nibble(*it++); - if (it == end) throw SyntaxException(uuid); - } - if (*it != '-') throw SyntaxException(uuid); - ++it; - for (int i = 0; i < 4; ++i) - { - clockSeq = clockSeq*16 + nibble(*it++); - if (it == end) throw SyntaxException(uuid); - } - if (*it != '-') throw SyntaxException(uuid); - ++it; - for (int i = 0; i < 6; ++i) - { - if (it == end) throw SyntaxException(uuid); - node[i] = node[i]*16 + nibble(*it++); - if (it == end) throw SyntaxException(uuid); - node[i] = node[i]*16 + nibble(*it++); - } - _timeLow = timeLow; - _timeMid = timeMid; - _timeHiAndVersion = timeHiAndVersion; - _clockSeq = clockSeq; - memcpy(_node, node, sizeof(_node)); - } -} - - -std::string UUID::toString() const -{ - std::string result; - result.reserve(36); - appendHex(result, _timeLow); - result += '-'; - appendHex(result, _timeMid); - result += '-'; - appendHex(result, _timeHiAndVersion); - result += '-'; - appendHex(result, _clockSeq); - result += '-'; - for (int i = 0; i < sizeof(_node); ++i) - appendHex(result, _node[i]); - return result; -} - - -void UUID::copyFrom(const char* buffer) -{ - UInt32 i32; - UInt16 i16; - memcpy(&i32, buffer, sizeof(i32)); - _timeLow = ByteOrder::fromNetwork(i32); - buffer += sizeof(i32); - memcpy(&i16, buffer, sizeof(i16)); - _timeMid = ByteOrder::fromNetwork(i16); - buffer += sizeof(i16); - memcpy(&i16, buffer, sizeof(i16)); - _timeHiAndVersion = ByteOrder::fromNetwork(i16); - buffer += sizeof(i16); - memcpy(&i16, buffer, sizeof(i16)); - _clockSeq = ByteOrder::fromNetwork(i16); - buffer += sizeof(i16); - memcpy(_node, buffer, sizeof(_node)); -} - - -void UUID::copyTo(char* buffer) const -{ - UInt32 i32 = ByteOrder::toNetwork(_timeLow); - memcpy(buffer, &i32, sizeof(i32)); - buffer += sizeof(i32); - UInt16 i16 = ByteOrder::toNetwork(_timeMid); - memcpy(buffer, &i16, sizeof(i16)); - buffer += sizeof(i16); - i16 = ByteOrder::toNetwork(_timeHiAndVersion); - memcpy(buffer, &i16, sizeof(i16)); - buffer += sizeof(i16); - i16 = ByteOrder::toNetwork(_clockSeq); - memcpy(buffer, &i16, sizeof(i16)); - buffer += sizeof(i16); - memcpy(buffer, _node, sizeof(_node)); -} - - -int UUID::variant() const -{ - int v = _clockSeq >> 13; - if ((v & 6) == 6) - return v; - else if (v & 4) - return 2; - else - return 0; -} - - -int UUID::compare(const UUID& uuid) const -{ - if (_timeLow != uuid._timeLow) return _timeLow < uuid._timeLow ? -1 : 1; - if (_timeMid != uuid._timeMid) return _timeMid < uuid._timeMid ? -1 : 1; - if (_timeHiAndVersion != uuid._timeHiAndVersion) return _timeHiAndVersion < uuid._timeHiAndVersion ? -1 : 1; - if (_clockSeq != uuid._clockSeq) return _clockSeq < uuid._clockSeq ? -1 : 1; - for (int i = 0; i < sizeof(_node); ++i) - { - if (_node[i] < uuid._node[i]) - return -1; - else if (_node[i] > uuid._node[i]) - return 1; - } - return 0; -} - - -void UUID::appendHex(std::string& str, UInt8 n) -{ - static const char* digits = "0123456789abcdef"; - str += digits[(n >> 4) & 0xF]; - str += digits[n & 0xF]; -} - - -void UUID::appendHex(std::string& str, UInt16 n) -{ - appendHex(str, UInt8(n >> 8)); - appendHex(str, UInt8(n & 0xFF)); -} - - -void UUID::appendHex(std::string& str, UInt32 n) -{ - appendHex(str, UInt16(n >> 16)); - appendHex(str, UInt16(n & 0xFFFF)); -} - - -int UUID::nibble(char hex) -{ - if (hex >= 'a' && hex <= 'f') - return hex - 'a' + 10; - else if (hex >= 'A' && hex <= 'F') - return hex - 'A' + 10; - else if (hex >= '0' && hex <= '9') - return hex - '0'; - else - return 0; -} - - -void UUID::fromNetwork() -{ - _timeLow = ByteOrder::fromNetwork(_timeLow); - _timeMid = ByteOrder::fromNetwork(_timeMid); - _timeHiAndVersion = ByteOrder::fromNetwork(_timeHiAndVersion); - _clockSeq = ByteOrder::fromNetwork(_clockSeq); -} - - -void UUID::toNetwork() -{ - _timeLow = ByteOrder::toNetwork(_timeLow); - _timeMid = ByteOrder::toNetwork(_timeMid); - _timeHiAndVersion = ByteOrder::toNetwork(_timeHiAndVersion); - _clockSeq = ByteOrder::toNetwork(_clockSeq); -} - - -const UUID& UUID::nil() -{ - static UUID nil; - return nil; -} - - -const UUID& UUID::dns() -{ - static UUID uuidDNS("6ba7b810-9dad-11d1-80b4-00c04fd430c8"); - return uuidDNS; -} - - -const UUID& UUID::uri() -{ - static UUID uuidURI("6ba7b811-9dad-11d1-80b4-00c04fd430c8"); - return uuidURI; -} - - -const UUID& UUID::oid() -{ - static UUID uuidOID("6ba7b812-9dad-11d1-80b4-00c04fd430c8"); - return uuidOID; -} - - -const UUID& UUID::x500() -{ - static UUID uuidX500("6ba7b814-9dad-11d1-80b4-00c04fd430c8"); - return uuidX500; -} - - -} // namespace Poco +// +// UUID.cpp +// +// $Id: //poco/1.2/Foundation/src/UUID.cpp#1 $ +// +// Library: Foundation +// Package: UUID +// Module: UUID +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/UUID.h" +#include "Poco/ByteOrder.h" +#include "Poco/Exception.h" +#include +#include + + +namespace Poco { + + +UUID::UUID(): + _timeLow(0), + _timeMid(0), + _timeHiAndVersion(0), + _clockSeq(0) +{ + memset(_node, 0, sizeof(_node)); +} + + +UUID::UUID(const UUID& uuid): + _timeLow(uuid._timeLow), + _timeMid(uuid._timeMid), + _timeHiAndVersion(uuid._timeHiAndVersion), + _clockSeq(uuid._clockSeq) +{ + memcpy(_node, uuid._node, sizeof(_node)); +} + + +UUID::UUID(const std::string& uuid) +{ + parse(uuid); +} + + +UUID::UUID(const char* uuid) +{ + poco_check_ptr (uuid); + parse(std::string(uuid)); +} + + +UUID::UUID(UInt32 timeLow, UInt32 timeMid, UInt32 timeHiAndVersion, UInt16 clockSeq, UInt8 node[]): + _timeLow(timeLow), + _timeMid(timeMid), + _timeHiAndVersion(timeHiAndVersion), + _clockSeq(clockSeq) +{ + memcpy(_node, node, sizeof(_node)); +} + + +UUID::UUID(const char* bytes, Version version) +{ + UInt32 i32; + UInt16 i16; + memcpy(&i32, bytes, sizeof(i32)); + _timeLow = ByteOrder::fromNetwork(i32); + bytes += sizeof(i32); + memcpy(&i16, bytes, sizeof(i16)); + _timeMid = ByteOrder::fromNetwork(i16); + bytes += sizeof(i16); + memcpy(&i16, bytes, sizeof(i16)); + _timeHiAndVersion = ByteOrder::fromNetwork(i16); + bytes += sizeof(i16); + memcpy(&i16, bytes, sizeof(i16)); + _clockSeq = ByteOrder::fromNetwork(i16); + bytes += sizeof(i16); + memcpy(_node, bytes, sizeof(_node)); + + _timeHiAndVersion &= 0x0FFF; + _timeHiAndVersion |= (version << 12); + _clockSeq &= 0x3FFF; + _clockSeq |= 0x8000; +} + + +UUID::~UUID() +{ +} + + +UUID& UUID::operator = (const UUID& uuid) +{ + if (&uuid != this) + { + _timeLow = uuid._timeLow; + _timeMid = uuid._timeMid; + _timeHiAndVersion = uuid._timeHiAndVersion; + _clockSeq = uuid._clockSeq; + memcpy(_node, uuid._node, sizeof(_node)); + } + return *this; +} + + +void UUID::swap(UUID& uuid) +{ + std::swap(_timeLow, uuid._timeLow); + std::swap(_timeMid, uuid._timeMid); + std::swap(_timeHiAndVersion, uuid._timeHiAndVersion); + std::swap(_clockSeq, uuid._clockSeq); + std::swap_ranges(_node, _node + 6, uuid._node); +} + + +void UUID::parse(const std::string& uuid) +{ + UInt32 timeLow = 0; + UInt16 timeMid = 0; + UInt16 timeHiAndVersion = 0; + UInt16 clockSeq = 0; + UInt8 node[6] = {0, 0, 0, 0, 0, 0}; + std::string::const_iterator it = uuid.begin(); + std::string::const_iterator end = uuid.end(); + if (it != end) + { + for (int i = 0; i < 8; ++i) + { + timeLow = timeLow*16 + nibble(*it++); + if (it == end) throw SyntaxException(uuid); + } + if (*it != '-') throw SyntaxException(uuid); + ++it; + for (int i = 0; i < 4; ++i) + { + timeMid = timeMid*16 + nibble(*it++); + if (it == end) throw SyntaxException(uuid); + } + if (*it != '-') throw SyntaxException(uuid); + ++it; + for (int i = 0; i < 4; ++i) + { + timeHiAndVersion = timeHiAndVersion*16 + nibble(*it++); + if (it == end) throw SyntaxException(uuid); + } + if (*it != '-') throw SyntaxException(uuid); + ++it; + for (int i = 0; i < 4; ++i) + { + clockSeq = clockSeq*16 + nibble(*it++); + if (it == end) throw SyntaxException(uuid); + } + if (*it != '-') throw SyntaxException(uuid); + ++it; + for (int i = 0; i < 6; ++i) + { + if (it == end) throw SyntaxException(uuid); + node[i] = node[i]*16 + nibble(*it++); + if (it == end) throw SyntaxException(uuid); + node[i] = node[i]*16 + nibble(*it++); + } + _timeLow = timeLow; + _timeMid = timeMid; + _timeHiAndVersion = timeHiAndVersion; + _clockSeq = clockSeq; + memcpy(_node, node, sizeof(_node)); + } +} + + +std::string UUID::toString() const +{ + std::string result; + result.reserve(36); + appendHex(result, _timeLow); + result += '-'; + appendHex(result, _timeMid); + result += '-'; + appendHex(result, _timeHiAndVersion); + result += '-'; + appendHex(result, _clockSeq); + result += '-'; + for (int i = 0; i < sizeof(_node); ++i) + appendHex(result, _node[i]); + return result; +} + + +void UUID::copyFrom(const char* buffer) +{ + UInt32 i32; + UInt16 i16; + memcpy(&i32, buffer, sizeof(i32)); + _timeLow = ByteOrder::fromNetwork(i32); + buffer += sizeof(i32); + memcpy(&i16, buffer, sizeof(i16)); + _timeMid = ByteOrder::fromNetwork(i16); + buffer += sizeof(i16); + memcpy(&i16, buffer, sizeof(i16)); + _timeHiAndVersion = ByteOrder::fromNetwork(i16); + buffer += sizeof(i16); + memcpy(&i16, buffer, sizeof(i16)); + _clockSeq = ByteOrder::fromNetwork(i16); + buffer += sizeof(i16); + memcpy(_node, buffer, sizeof(_node)); +} + + +void UUID::copyTo(char* buffer) const +{ + UInt32 i32 = ByteOrder::toNetwork(_timeLow); + memcpy(buffer, &i32, sizeof(i32)); + buffer += sizeof(i32); + UInt16 i16 = ByteOrder::toNetwork(_timeMid); + memcpy(buffer, &i16, sizeof(i16)); + buffer += sizeof(i16); + i16 = ByteOrder::toNetwork(_timeHiAndVersion); + memcpy(buffer, &i16, sizeof(i16)); + buffer += sizeof(i16); + i16 = ByteOrder::toNetwork(_clockSeq); + memcpy(buffer, &i16, sizeof(i16)); + buffer += sizeof(i16); + memcpy(buffer, _node, sizeof(_node)); +} + + +int UUID::variant() const +{ + int v = _clockSeq >> 13; + if ((v & 6) == 6) + return v; + else if (v & 4) + return 2; + else + return 0; +} + + +int UUID::compare(const UUID& uuid) const +{ + if (_timeLow != uuid._timeLow) return _timeLow < uuid._timeLow ? -1 : 1; + if (_timeMid != uuid._timeMid) return _timeMid < uuid._timeMid ? -1 : 1; + if (_timeHiAndVersion != uuid._timeHiAndVersion) return _timeHiAndVersion < uuid._timeHiAndVersion ? -1 : 1; + if (_clockSeq != uuid._clockSeq) return _clockSeq < uuid._clockSeq ? -1 : 1; + for (int i = 0; i < sizeof(_node); ++i) + { + if (_node[i] < uuid._node[i]) + return -1; + else if (_node[i] > uuid._node[i]) + return 1; + } + return 0; +} + + +void UUID::appendHex(std::string& str, UInt8 n) +{ + static const char* digits = "0123456789abcdef"; + str += digits[(n >> 4) & 0xF]; + str += digits[n & 0xF]; +} + + +void UUID::appendHex(std::string& str, UInt16 n) +{ + appendHex(str, UInt8(n >> 8)); + appendHex(str, UInt8(n & 0xFF)); +} + + +void UUID::appendHex(std::string& str, UInt32 n) +{ + appendHex(str, UInt16(n >> 16)); + appendHex(str, UInt16(n & 0xFFFF)); +} + + +int UUID::nibble(char hex) +{ + if (hex >= 'a' && hex <= 'f') + return hex - 'a' + 10; + else if (hex >= 'A' && hex <= 'F') + return hex - 'A' + 10; + else if (hex >= '0' && hex <= '9') + return hex - '0'; + else + return 0; +} + + +void UUID::fromNetwork() +{ + _timeLow = ByteOrder::fromNetwork(_timeLow); + _timeMid = ByteOrder::fromNetwork(_timeMid); + _timeHiAndVersion = ByteOrder::fromNetwork(_timeHiAndVersion); + _clockSeq = ByteOrder::fromNetwork(_clockSeq); +} + + +void UUID::toNetwork() +{ + _timeLow = ByteOrder::toNetwork(_timeLow); + _timeMid = ByteOrder::toNetwork(_timeMid); + _timeHiAndVersion = ByteOrder::toNetwork(_timeHiAndVersion); + _clockSeq = ByteOrder::toNetwork(_clockSeq); +} + + +const UUID& UUID::nil() +{ + static UUID nil; + return nil; +} + + +const UUID& UUID::dns() +{ + static UUID uuidDNS("6ba7b810-9dad-11d1-80b4-00c04fd430c8"); + return uuidDNS; +} + + +const UUID& UUID::uri() +{ + static UUID uuidURI("6ba7b811-9dad-11d1-80b4-00c04fd430c8"); + return uuidURI; +} + + +const UUID& UUID::oid() +{ + static UUID uuidOID("6ba7b812-9dad-11d1-80b4-00c04fd430c8"); + return uuidOID; +} + + +const UUID& UUID::x500() +{ + static UUID uuidX500("6ba7b814-9dad-11d1-80b4-00c04fd430c8"); + return uuidX500; +} + + +} // namespace Poco diff --git a/Foundation/src/UUIDGenerator.cpp b/Foundation/src/UUIDGenerator.cpp index 7d645babf..e1883a922 100644 --- a/Foundation/src/UUIDGenerator.cpp +++ b/Foundation/src/UUIDGenerator.cpp @@ -1,361 +1,361 @@ -// -// UUIDGenerator.cpp -// -// $Id: //poco/1.2/Foundation/src/UUIDGenerator.cpp#1 $ -// -// Library: Foundation -// Package: UUID -// Module: UUID -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/UUIDGenerator.h" -#include "Poco/Thread.h" -#include "Poco/RandomStream.h" -#include "Poco/DigestEngine.h" -#include "Poco/MD5Engine.h" -#include "Poco/SingletonHolder.h" -#include - - -namespace Poco { - - -UUIDGenerator::UUIDGenerator(): _ticks(0), _haveNode(false) -{ -} - - -UUIDGenerator::~UUIDGenerator() -{ -} - - -UUID UUIDGenerator::create() -{ - FastMutex::ScopedLock lock(_mutex); - - if (!_haveNode) - { - getNode(); - _haveNode = true; - } - Timestamp::UtcTimeVal tv = timeStamp(); - UInt32 timeLow = UInt32(tv & 0xFFFFFFFF); - UInt16 timeMid = UInt16((tv >> 32) & 0xFFFF); - UInt16 timeHiAndVersion = UInt16((tv >> 48) & 0x0FFF) + (UUID::UUID_TIME_BASED << 12); - UInt16 clockSeq = (UInt16(_random.next() >> 4) & 0x3FFF) | 0x8000; - return UUID(timeLow, timeMid, timeHiAndVersion, clockSeq, _node); -} - - -UUID UUIDGenerator::createFromName(const UUID& nsid, const std::string& name) -{ - MD5Engine md5; - return createFromName(nsid, name, md5); -} - - -UUID UUIDGenerator::createFromName(const UUID& nsid, const std::string& name, DigestEngine& de) -{ - poco_assert_dbg (de.digestLength() >= 16); - - UUID netNsid = nsid; - netNsid.toNetwork(); - de.reset(); - de.update(&netNsid, sizeof(netNsid)); - de.update(name); - char buffer[16]; - const DigestEngine::Digest& d = de.digest(); - for (int i = 0; i < 16; ++i) - { - buffer[i] = d[i]; - } - return UUID(buffer, UUID::UUID_NAME_BASED); -} - - -UUID UUIDGenerator::createRandom() -{ - char buffer[16]; - RandomInputStream ris; - ris.read(buffer, sizeof(buffer)); - return UUID(buffer, UUID::UUID_RANDOM); -} - - -Timestamp::UtcTimeVal UUIDGenerator::timeStamp() -{ - Timestamp now; - for (;;) - { - if (now != _lastTime) - { - _lastTime = now; - _ticks = 0; - break; - } - if (_ticks < 100) - { - ++_ticks; - break; - } - now.update(); - } - Timestamp::UtcTimeVal tv = now.utcTime(); - return tv + _ticks; -} - - -UUID UUIDGenerator::createOne() -{ - try - { - return create(); - } - catch (Exception&) - { - return createRandom(); - } -} - - -UUIDGenerator& UUIDGenerator::defaultGenerator() -{ - static SingletonHolder sh; - return *sh.get(); -} - - -} // namespace Poco - - -// -// platform-specific code below -// - - -#if defined(POCO_OS_FAMILY_WINDOWS) -// -// Windows -// -#include -#include - - -namespace Poco { - - -void UUIDGenerator::getNode() -{ - PIP_ADAPTER_INFO pAdapterInfo; - PIP_ADAPTER_INFO pAdapter = 0; - ULONG len = sizeof(IP_ADAPTER_INFO); - pAdapterInfo = reinterpret_cast(new char[len]); - // Make an initial call to GetAdaptersInfo to get - // the necessary size into len - DWORD rc = GetAdaptersInfo(pAdapterInfo, &len); - if (rc == ERROR_BUFFER_OVERFLOW) - { - delete [] reinterpret_cast(pAdapterInfo); - pAdapterInfo = reinterpret_cast(new char[len]); - } - else if (rc != ERROR_SUCCESS) - { - throw SystemException("cannot get network adapter list"); - } - try - { - bool found = false; - if (GetAdaptersInfo(pAdapterInfo, &len) == NO_ERROR) - { - pAdapter = pAdapterInfo; - while (pAdapter && !found) - { - if (pAdapter->Type == MIB_IF_TYPE_ETHERNET && pAdapter->AddressLength == sizeof(_node)) - { - memcpy(_node, pAdapter->Address, pAdapter->AddressLength); - found = true; - } - } - } - else throw SystemException("cannot get network adapter list"); - if (!found) throw SystemException("no Ethernet adapter found"); - } - catch (Exception&) - { - delete [] reinterpret_cast(pAdapterInfo); - throw; - } - delete [] reinterpret_cast(pAdapterInfo); -} - - -} // namespace Poco - - -#elif defined(POCO_OS_FAMILY_BSD) || POCO_OS == POCO_OS_QNX -// -// BSD variants -// -#include -#include -#include -#include - - -namespace Poco { - - -void UUIDGenerator::getNode() -{ - struct ifaddrs* ifaphead; - int rc = getifaddrs(&ifaphead); - if (rc) throw SystemException("cannot get network adapter list"); - - bool foundAdapter = false; - for (struct ifaddrs* ifap = ifaphead; ifap; ifap = ifap->ifa_next) - { - if (ifap->ifa_addr && ifap->ifa_addr->sa_family == AF_LINK) - { - struct sockaddr_dl* sdl = reinterpret_cast(ifap->ifa_addr); - caddr_t ap = (caddr_t) (sdl->sdl_data + sdl->sdl_nlen); - int alen = sdl->sdl_alen; - if (ap && alen > 0) - { - memcpy(_node, ap, sizeof(_node)); - foundAdapter = true; - break; - } - } - } - freeifaddrs(ifaphead); - if (!foundAdapter) throw SystemException("cannot determine MAC address (no suitable network adapter found)"); -} - - -} // namespace Poco - - -#elif defined(__CYGWIN__) || POCO_OS == POCO_OS_LINUX -// -// Linux -// -#include -#include -#include -#include -#include -#include - - -namespace Poco { - - -void UUIDGenerator::getNode() -{ - struct ifreq ifr; - - int s = socket(PF_INET, SOCK_DGRAM, 0); - if (s == -1) throw SystemException("cannot open socket"); - - strcpy(ifr.ifr_name, "eth0"); - int rc = ioctl(s, SIOCGIFHWADDR, &ifr); - close(s); - if (rc < 0) throw SystemException("cannot get MAC address"); - struct sockaddr* sa = reinterpret_cast(&ifr.ifr_addr); - memcpy(_node, sa->sa_data, sizeof(_node)); -} - - -} // namespace Poco - - -#elif defined(POCO_OS_FAMILY_UNIX) || defined(POCO_OS_FAMILY_VMS) -// -// Unix/VMS -// -#if defined(__VMS) -#include -#else -#include -#endif -#if defined(sun) || defined(__sun) -#include -#endif -#include -#include -#include -#include -#if defined(__VMS) -#include -#else -#include -#endif -#include -#include -#include -#include - - -#if defined(__VMS) -#define MAXHOSTNAMELEN 64 -#endif - - -namespace Poco { - - -void UUIDGenerator::getNode() -{ - char name[MAXHOSTNAMELEN]; - if (gethostname(name, sizeof(name))) - throw SystemException("cannot get host name"); - - struct hostent* pHost = gethostbyname(name); - if (!pHost) throw SystemException("cannot get host IP address"); - - int s = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP); - if (s == -1) throw SystemException("cannot open socket"); - - struct arpreq ar; - memset(&ar, 0, sizeof(ar)); - struct sockaddr_in* pAddr = reinterpret_cast(&ar.arp_pa); - pAddr->sin_family = AF_INET; - memcpy(&pAddr->sin_addr, *pHost->h_addr_list, sizeof(struct in_addr)); - int rc = ioctl(s, SIOCGARP, &ar); - close(s); - if (rc < 0) throw SystemException("cannot get MAC address"); - memcpy(_node, ar.arp_ha.sa_data, sizeof(_node)); -} - - -} // namespace Poco - - -#endif +// +// UUIDGenerator.cpp +// +// $Id: //poco/1.2/Foundation/src/UUIDGenerator.cpp#1 $ +// +// Library: Foundation +// Package: UUID +// Module: UUID +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/UUIDGenerator.h" +#include "Poco/Thread.h" +#include "Poco/RandomStream.h" +#include "Poco/DigestEngine.h" +#include "Poco/MD5Engine.h" +#include "Poco/SingletonHolder.h" +#include + + +namespace Poco { + + +UUIDGenerator::UUIDGenerator(): _ticks(0), _haveNode(false) +{ +} + + +UUIDGenerator::~UUIDGenerator() +{ +} + + +UUID UUIDGenerator::create() +{ + FastMutex::ScopedLock lock(_mutex); + + if (!_haveNode) + { + getNode(); + _haveNode = true; + } + Timestamp::UtcTimeVal tv = timeStamp(); + UInt32 timeLow = UInt32(tv & 0xFFFFFFFF); + UInt16 timeMid = UInt16((tv >> 32) & 0xFFFF); + UInt16 timeHiAndVersion = UInt16((tv >> 48) & 0x0FFF) + (UUID::UUID_TIME_BASED << 12); + UInt16 clockSeq = (UInt16(_random.next() >> 4) & 0x3FFF) | 0x8000; + return UUID(timeLow, timeMid, timeHiAndVersion, clockSeq, _node); +} + + +UUID UUIDGenerator::createFromName(const UUID& nsid, const std::string& name) +{ + MD5Engine md5; + return createFromName(nsid, name, md5); +} + + +UUID UUIDGenerator::createFromName(const UUID& nsid, const std::string& name, DigestEngine& de) +{ + poco_assert_dbg (de.digestLength() >= 16); + + UUID netNsid = nsid; + netNsid.toNetwork(); + de.reset(); + de.update(&netNsid, sizeof(netNsid)); + de.update(name); + char buffer[16]; + const DigestEngine::Digest& d = de.digest(); + for (int i = 0; i < 16; ++i) + { + buffer[i] = d[i]; + } + return UUID(buffer, UUID::UUID_NAME_BASED); +} + + +UUID UUIDGenerator::createRandom() +{ + char buffer[16]; + RandomInputStream ris; + ris.read(buffer, sizeof(buffer)); + return UUID(buffer, UUID::UUID_RANDOM); +} + + +Timestamp::UtcTimeVal UUIDGenerator::timeStamp() +{ + Timestamp now; + for (;;) + { + if (now != _lastTime) + { + _lastTime = now; + _ticks = 0; + break; + } + if (_ticks < 100) + { + ++_ticks; + break; + } + now.update(); + } + Timestamp::UtcTimeVal tv = now.utcTime(); + return tv + _ticks; +} + + +UUID UUIDGenerator::createOne() +{ + try + { + return create(); + } + catch (Exception&) + { + return createRandom(); + } +} + + +UUIDGenerator& UUIDGenerator::defaultGenerator() +{ + static SingletonHolder sh; + return *sh.get(); +} + + +} // namespace Poco + + +// +// platform-specific code below +// + + +#if defined(POCO_OS_FAMILY_WINDOWS) +// +// Windows +// +#include +#include + + +namespace Poco { + + +void UUIDGenerator::getNode() +{ + PIP_ADAPTER_INFO pAdapterInfo; + PIP_ADAPTER_INFO pAdapter = 0; + ULONG len = sizeof(IP_ADAPTER_INFO); + pAdapterInfo = reinterpret_cast(new char[len]); + // Make an initial call to GetAdaptersInfo to get + // the necessary size into len + DWORD rc = GetAdaptersInfo(pAdapterInfo, &len); + if (rc == ERROR_BUFFER_OVERFLOW) + { + delete [] reinterpret_cast(pAdapterInfo); + pAdapterInfo = reinterpret_cast(new char[len]); + } + else if (rc != ERROR_SUCCESS) + { + throw SystemException("cannot get network adapter list"); + } + try + { + bool found = false; + if (GetAdaptersInfo(pAdapterInfo, &len) == NO_ERROR) + { + pAdapter = pAdapterInfo; + while (pAdapter && !found) + { + if (pAdapter->Type == MIB_IF_TYPE_ETHERNET && pAdapter->AddressLength == sizeof(_node)) + { + memcpy(_node, pAdapter->Address, pAdapter->AddressLength); + found = true; + } + } + } + else throw SystemException("cannot get network adapter list"); + if (!found) throw SystemException("no Ethernet adapter found"); + } + catch (Exception&) + { + delete [] reinterpret_cast(pAdapterInfo); + throw; + } + delete [] reinterpret_cast(pAdapterInfo); +} + + +} // namespace Poco + + +#elif defined(POCO_OS_FAMILY_BSD) || POCO_OS == POCO_OS_QNX +// +// BSD variants +// +#include +#include +#include +#include + + +namespace Poco { + + +void UUIDGenerator::getNode() +{ + struct ifaddrs* ifaphead; + int rc = getifaddrs(&ifaphead); + if (rc) throw SystemException("cannot get network adapter list"); + + bool foundAdapter = false; + for (struct ifaddrs* ifap = ifaphead; ifap; ifap = ifap->ifa_next) + { + if (ifap->ifa_addr && ifap->ifa_addr->sa_family == AF_LINK) + { + struct sockaddr_dl* sdl = reinterpret_cast(ifap->ifa_addr); + caddr_t ap = (caddr_t) (sdl->sdl_data + sdl->sdl_nlen); + int alen = sdl->sdl_alen; + if (ap && alen > 0) + { + memcpy(_node, ap, sizeof(_node)); + foundAdapter = true; + break; + } + } + } + freeifaddrs(ifaphead); + if (!foundAdapter) throw SystemException("cannot determine MAC address (no suitable network adapter found)"); +} + + +} // namespace Poco + + +#elif defined(__CYGWIN__) || POCO_OS == POCO_OS_LINUX +// +// Linux +// +#include +#include +#include +#include +#include +#include + + +namespace Poco { + + +void UUIDGenerator::getNode() +{ + struct ifreq ifr; + + int s = socket(PF_INET, SOCK_DGRAM, 0); + if (s == -1) throw SystemException("cannot open socket"); + + strcpy(ifr.ifr_name, "eth0"); + int rc = ioctl(s, SIOCGIFHWADDR, &ifr); + close(s); + if (rc < 0) throw SystemException("cannot get MAC address"); + struct sockaddr* sa = reinterpret_cast(&ifr.ifr_addr); + memcpy(_node, sa->sa_data, sizeof(_node)); +} + + +} // namespace Poco + + +#elif defined(POCO_OS_FAMILY_UNIX) || defined(POCO_OS_FAMILY_VMS) +// +// Unix/VMS +// +#if defined(__VMS) +#include +#else +#include +#endif +#if defined(sun) || defined(__sun) +#include +#endif +#include +#include +#include +#include +#if defined(__VMS) +#include +#else +#include +#endif +#include +#include +#include +#include + + +#if defined(__VMS) +#define MAXHOSTNAMELEN 64 +#endif + + +namespace Poco { + + +void UUIDGenerator::getNode() +{ + char name[MAXHOSTNAMELEN]; + if (gethostname(name, sizeof(name))) + throw SystemException("cannot get host name"); + + struct hostent* pHost = gethostbyname(name); + if (!pHost) throw SystemException("cannot get host IP address"); + + int s = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP); + if (s == -1) throw SystemException("cannot open socket"); + + struct arpreq ar; + memset(&ar, 0, sizeof(ar)); + struct sockaddr_in* pAddr = reinterpret_cast(&ar.arp_pa); + pAddr->sin_family = AF_INET; + memcpy(&pAddr->sin_addr, *pHost->h_addr_list, sizeof(struct in_addr)); + int rc = ioctl(s, SIOCGARP, &ar); + close(s); + if (rc < 0) throw SystemException("cannot get MAC address"); + memcpy(_node, ar.arp_ha.sa_data, sizeof(_node)); +} + + +} // namespace Poco + + +#endif diff --git a/Foundation/src/UnicodeConverter.cpp b/Foundation/src/UnicodeConverter.cpp index 74cf3b3fc..58ffbe06c 100644 --- a/Foundation/src/UnicodeConverter.cpp +++ b/Foundation/src/UnicodeConverter.cpp @@ -1,136 +1,136 @@ -// -// UnicodeConverter.cpp -// -// $Id: //poco/1.2/Foundation/src/UnicodeConverter.cpp#1 $ -// -// Library: Foundation -// Package: Text -// Module: UnicodeConverter -// -// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 POCO_NO_WSTRING - - -#include "Poco/UnicodeConverter.h" -#include "Poco/TextConverter.h" -#include "Poco/TextIterator.h" -#include "Poco/UTF8Encoding.h" -#include "Poco/UTF16Encoding.h" -#include -#include - - -namespace Poco { - - -void UnicodeConverter::toUTF16(const std::string& utf8String, std::wstring& utf16String) -{ - utf16String.clear(); - UTF8Encoding utf8Encoding; - TextIterator it(utf8String, utf8Encoding); - TextIterator end(utf8String); - while (it != end) utf16String += (wchar_t) *it++; -} - - -void UnicodeConverter::toUTF16(const char* utf8String, int length, std::wstring& utf16String) -{ - poco_check_ptr (utf8String); - - utf16String.clear(); - - UTF8Encoding utf8Encoding; - UTF16Encoding utf16Encoding; - const unsigned char* it = (const unsigned char*) utf8String; - const unsigned char* end = (const unsigned char*) utf8String + length; - - while (it < end) - { - unsigned char c = *it; - int n = utf8Encoding.characterMap()[c]; - int uc = '?'; - if (n == -1) - { - ++it; - } - else if (n >= 0) - { - uc = n; - ++it; - } - else - { - if (it - n <= end) - { - uc = utf8Encoding.convert(it); - if (uc == -1) uc = '?'; - } - it -= n; - } - utf16String += (wchar_t) uc; // TODO: surrogates - } -} - - -void UnicodeConverter::toUTF16(const char* utf8String, std::wstring& utf16String) -{ - toUTF16(utf8String, (int) strlen(utf8String), utf16String); -} - - -void UnicodeConverter::toUTF8(const std::wstring& utf16String, std::string& utf8String) -{ - utf8String.clear(); - UTF8Encoding utf8Encoding; - UTF16Encoding utf16Encoding; - TextConverter converter(utf16Encoding, utf8Encoding); - converter.convert(utf16String.data(), (int) utf16String.length()*sizeof(wchar_t), utf8String); -} - - -void UnicodeConverter::toUTF8(const wchar_t* utf16String, int length, std::string& utf8String) -{ - utf8String.clear(); - UTF8Encoding utf8Encoding; - UTF16Encoding utf16Encoding; - TextConverter converter(utf16Encoding, utf8Encoding); - converter.convert(utf16String, (int) length*sizeof(wchar_t), utf8String); -} - - -void UnicodeConverter::toUTF8(const wchar_t* utf16String, std::string& utf8String) -{ - toUTF8(utf16String, (int) wcslen(utf16String), utf8String); -} - - -} // namespace Poco - - -#endif // POCO_NO_WSTRING +// +// UnicodeConverter.cpp +// +// $Id: //poco/1.2/Foundation/src/UnicodeConverter.cpp#1 $ +// +// Library: Foundation +// Package: Text +// Module: UnicodeConverter +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 POCO_NO_WSTRING + + +#include "Poco/UnicodeConverter.h" +#include "Poco/TextConverter.h" +#include "Poco/TextIterator.h" +#include "Poco/UTF8Encoding.h" +#include "Poco/UTF16Encoding.h" +#include +#include + + +namespace Poco { + + +void UnicodeConverter::toUTF16(const std::string& utf8String, std::wstring& utf16String) +{ + utf16String.clear(); + UTF8Encoding utf8Encoding; + TextIterator it(utf8String, utf8Encoding); + TextIterator end(utf8String); + while (it != end) utf16String += (wchar_t) *it++; +} + + +void UnicodeConverter::toUTF16(const char* utf8String, int length, std::wstring& utf16String) +{ + poco_check_ptr (utf8String); + + utf16String.clear(); + + UTF8Encoding utf8Encoding; + UTF16Encoding utf16Encoding; + const unsigned char* it = (const unsigned char*) utf8String; + const unsigned char* end = (const unsigned char*) utf8String + length; + + while (it < end) + { + unsigned char c = *it; + int n = utf8Encoding.characterMap()[c]; + int uc = '?'; + if (n == -1) + { + ++it; + } + else if (n >= 0) + { + uc = n; + ++it; + } + else + { + if (it - n <= end) + { + uc = utf8Encoding.convert(it); + if (uc == -1) uc = '?'; + } + it -= n; + } + utf16String += (wchar_t) uc; // TODO: surrogates + } +} + + +void UnicodeConverter::toUTF16(const char* utf8String, std::wstring& utf16String) +{ + toUTF16(utf8String, (int) strlen(utf8String), utf16String); +} + + +void UnicodeConverter::toUTF8(const std::wstring& utf16String, std::string& utf8String) +{ + utf8String.clear(); + UTF8Encoding utf8Encoding; + UTF16Encoding utf16Encoding; + TextConverter converter(utf16Encoding, utf8Encoding); + converter.convert(utf16String.data(), (int) utf16String.length()*sizeof(wchar_t), utf8String); +} + + +void UnicodeConverter::toUTF8(const wchar_t* utf16String, int length, std::string& utf8String) +{ + utf8String.clear(); + UTF8Encoding utf8Encoding; + UTF16Encoding utf16Encoding; + TextConverter converter(utf16Encoding, utf8Encoding); + converter.convert(utf16String, (int) length*sizeof(wchar_t), utf8String); +} + + +void UnicodeConverter::toUTF8(const wchar_t* utf16String, std::string& utf8String) +{ + toUTF8(utf16String, (int) wcslen(utf16String), utf8String); +} + + +} // namespace Poco + + +#endif // POCO_NO_WSTRING diff --git a/Foundation/src/Void.cpp b/Foundation/src/Void.cpp index a8fdfd982..250713147 100644 --- a/Foundation/src/Void.cpp +++ b/Foundation/src/Void.cpp @@ -1,79 +1,79 @@ -// -// Void.cpp -// -// $Id: //poco/1.2/Foundation/src/Void.cpp#1 $ -// -// Library: Foundation -// Package: Core -// Module: Void -// -// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. -// 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. -// -// 3. Redistributions in any form must be accompanied by information on -// how to obtain complete source code for this software and any -// accompanying software that uses this software. The source code -// must either be included in the distribution or be available for no -// more than the cost of distribution plus a nominal fee, and must be -// freely redistributable under reasonable conditions. For an -// executable file, complete source code means the source code for all -// modules it contains. It does not include source code for modules or -// files that typically accompany the major components of the operating -// system on which the executable file runs. -// -// 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. -// - - -#include "Poco/Void.h" - - -namespace Poco { - - -Void::Void() -{ -} - - -Void::Void(const Void& v) -{ - v; -} - - -Void::~Void() -{ -} - - -Void& Void::operator = (const Void& v) -{ - v; - return *this; -} - - -} // namespace Poco +// +// Void.cpp +// +// $Id: //poco/1.2/Foundation/src/Void.cpp#1 $ +// +// Library: Foundation +// Package: Core +// Module: Void +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// 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. +// +// 3. Redistributions in any form must be accompanied by information on +// how to obtain complete source code for this software and any +// accompanying software that uses this software. The source code +// must either be included in the distribution or be available for no +// more than the cost of distribution plus a nominal fee, and must be +// freely redistributable under reasonable conditions. For an +// executable file, complete source code means the source code for all +// modules it contains. It does not include source code for modules or +// files that typically accompany the major components of the operating +// system on which the executable file runs. +// +// 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. +// + + +#include "Poco/Void.h" + + +namespace Poco { + + +Void::Void() +{ +} + + +Void::Void(const Void& v) +{ + v; +} + + +Void::~Void() +{ +} + + +Void& Void::operator = (const Void& v) +{ + v; + return *this; +} + + +} // namespace Poco diff --git a/Foundation/src/Windows1252Encoding.cpp b/Foundation/src/Windows1252Encoding.cpp index 8e64f6c9d..04c7711a6 100644 --- a/Foundation/src/Windows1252Encoding.cpp +++ b/Foundation/src/Windows1252Encoding.cpp @@ -1,98 +1,98 @@ -// -// Windows1252Encoding.cpp -// -// $Id: //poco/1.2/Foundation/src/Windows1252Encoding.cpp#1 $ -// -// Library: Foundation -// Package: Text -// Module: Windows1252Encoding -// -// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/Windows1252Encoding.h" - - -namespace Poco { - - -const TextEncoding::CharacterMap Windows1252Encoding::_charMap = -{ - /* 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f */ - /* 00 */ 0x0000, 0x0001, 0x0002, 0x0003, 0x0004, 0x0005, 0x0006, 0x0007, 0x0008, 0x0009, 0x000a, 0x000b, 0x000c, 0x000d, 0x000e, 0x000f, - /* 10 */ 0x0010, 0x0011, 0x0012, 0x0013, 0x0014, 0x0015, 0x0016, 0x0017, 0x0018, 0x0019, 0x001a, 0x001b, 0x001c, 0x001d, 0x001e, 0x001f, - /* 20 */ 0x0020, 0x0021, 0x0022, 0x0023, 0x0024, 0x0025, 0x0026, 0x0027, 0x0028, 0x0029, 0x002a, 0x002b, 0x002c, 0x002d, 0x002e, 0x002f, - /* 30 */ 0x0030, 0x0031, 0x0032, 0x0033, 0x0034, 0x0035, 0x0036, 0x0037, 0x0038, 0x0039, 0x003a, 0x003b, 0x003c, 0x003d, 0x003e, 0x003f, - /* 40 */ 0x0040, 0x0041, 0x0042, 0x0043, 0x0044, 0x0045, 0x0046, 0x0047, 0x0048, 0x0049, 0x004a, 0x004b, 0x004c, 0x004d, 0x004e, 0x004f, - /* 50 */ 0x0050, 0x0051, 0x0052, 0x0053, 0x0054, 0x0055, 0x0056, 0x0057, 0x0058, 0x0059, 0x005a, 0x005b, 0x005c, 0x005d, 0x005e, 0x005f, - /* 60 */ 0x0060, 0x0061, 0x0062, 0x0063, 0x0064, 0x0065, 0x0066, 0x0067, 0x0068, 0x0069, 0x006a, 0x006b, 0x006c, 0x006d, 0x006e, 0x006f, - /* 70 */ 0x0070, 0x0071, 0x0072, 0x0073, 0x0074, 0x0075, 0x0076, 0x0077, 0x0078, 0x0079, 0x007a, 0x007b, 0x007c, 0x007d, 0x007e, 0x007f, - /* 80 */ 0x20AC, 0x0081, 0x201A, 0x0192, 0x201e, 0x2026, 0x2020, 0x2021, 0x02c6, 0x2030, 0x0160, 0x2039, 0x0152, 0x008d, 0x017d, 0x008f, - /* 90 */ 0x0090, 0x2018, 0x2019, 0x201c, 0x201d, 0x2022, 0x2013, 0x2014, 0x02dc, 0x2122, 0x0161, 0x203a, 0x0153, 0x009d, 0x017e, 0x0178, - /* a0 */ 0x00a0, 0x00a1, 0x00a2, 0x00a3, 0x00a4, 0x00a5, 0x00a6, 0x00a7, 0x00a8, 0x00a9, 0x00aa, 0x00ab, 0x00ac, 0x00ad, 0x00ae, 0x00af, - /* b0 */ 0x00b0, 0x00b1, 0x00b2, 0x00b3, 0x00b4, 0x00b5, 0x00b6, 0x00b7, 0x00b8, 0x00b9, 0x00ba, 0x00bb, 0x00bc, 0x00bd, 0x00be, 0x00bf, - /* c0 */ 0x00c0, 0x00c1, 0x00c2, 0x00c3, 0x00c4, 0x00c5, 0x00c6, 0x00c7, 0x00c8, 0x00c9, 0x00ca, 0x00cb, 0x00cc, 0x00cd, 0x00ce, 0x00cf, - /* d0 */ 0x00d0, 0x00d1, 0x00d2, 0x00d3, 0x00d4, 0x00d5, 0x00d6, 0x00d7, 0x00d8, 0x00d9, 0x00da, 0x00db, 0x00dc, 0x00dd, 0x00de, 0x00df, - /* e0 */ 0x00e0, 0x00e1, 0x00e2, 0x00e3, 0x00e4, 0x00e5, 0x00e6, 0x00e7, 0x00e8, 0x00e9, 0x00ea, 0x00eb, 0x00ec, 0x00ed, 0x00ee, 0x00ef, - /* f0 */ 0x00f0, 0x00f1, 0x00f2, 0x00f3, 0x00f4, 0x00f5, 0x00f6, 0x00f7, 0x00f8, 0x00f9, 0x00fa, 0x00fb, 0x00fc, 0x00fd, 0x00fe, 0x00ff, -}; - - -Windows1252Encoding::Windows1252Encoding() -{ -} - - -Windows1252Encoding::~Windows1252Encoding() -{ -} - - -const TextEncoding::CharacterMap& Windows1252Encoding::characterMap() const -{ - return _charMap; -} - - -int Windows1252Encoding::convert(const unsigned char* bytes) const -{ - return *bytes; -} - - -int Windows1252Encoding::convert(int ch, unsigned char* bytes, int length) const -{ - if (ch >= 0 && ch <= 255) - { - *bytes = (unsigned char) ch; - return 1; - } - else return 0; -} - - -} // namespace Poco +// +// Windows1252Encoding.cpp +// +// $Id: //poco/1.2/Foundation/src/Windows1252Encoding.cpp#1 $ +// +// Library: Foundation +// Package: Text +// Module: Windows1252Encoding +// +// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/Windows1252Encoding.h" + + +namespace Poco { + + +const TextEncoding::CharacterMap Windows1252Encoding::_charMap = +{ + /* 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f */ + /* 00 */ 0x0000, 0x0001, 0x0002, 0x0003, 0x0004, 0x0005, 0x0006, 0x0007, 0x0008, 0x0009, 0x000a, 0x000b, 0x000c, 0x000d, 0x000e, 0x000f, + /* 10 */ 0x0010, 0x0011, 0x0012, 0x0013, 0x0014, 0x0015, 0x0016, 0x0017, 0x0018, 0x0019, 0x001a, 0x001b, 0x001c, 0x001d, 0x001e, 0x001f, + /* 20 */ 0x0020, 0x0021, 0x0022, 0x0023, 0x0024, 0x0025, 0x0026, 0x0027, 0x0028, 0x0029, 0x002a, 0x002b, 0x002c, 0x002d, 0x002e, 0x002f, + /* 30 */ 0x0030, 0x0031, 0x0032, 0x0033, 0x0034, 0x0035, 0x0036, 0x0037, 0x0038, 0x0039, 0x003a, 0x003b, 0x003c, 0x003d, 0x003e, 0x003f, + /* 40 */ 0x0040, 0x0041, 0x0042, 0x0043, 0x0044, 0x0045, 0x0046, 0x0047, 0x0048, 0x0049, 0x004a, 0x004b, 0x004c, 0x004d, 0x004e, 0x004f, + /* 50 */ 0x0050, 0x0051, 0x0052, 0x0053, 0x0054, 0x0055, 0x0056, 0x0057, 0x0058, 0x0059, 0x005a, 0x005b, 0x005c, 0x005d, 0x005e, 0x005f, + /* 60 */ 0x0060, 0x0061, 0x0062, 0x0063, 0x0064, 0x0065, 0x0066, 0x0067, 0x0068, 0x0069, 0x006a, 0x006b, 0x006c, 0x006d, 0x006e, 0x006f, + /* 70 */ 0x0070, 0x0071, 0x0072, 0x0073, 0x0074, 0x0075, 0x0076, 0x0077, 0x0078, 0x0079, 0x007a, 0x007b, 0x007c, 0x007d, 0x007e, 0x007f, + /* 80 */ 0x20AC, 0x0081, 0x201A, 0x0192, 0x201e, 0x2026, 0x2020, 0x2021, 0x02c6, 0x2030, 0x0160, 0x2039, 0x0152, 0x008d, 0x017d, 0x008f, + /* 90 */ 0x0090, 0x2018, 0x2019, 0x201c, 0x201d, 0x2022, 0x2013, 0x2014, 0x02dc, 0x2122, 0x0161, 0x203a, 0x0153, 0x009d, 0x017e, 0x0178, + /* a0 */ 0x00a0, 0x00a1, 0x00a2, 0x00a3, 0x00a4, 0x00a5, 0x00a6, 0x00a7, 0x00a8, 0x00a9, 0x00aa, 0x00ab, 0x00ac, 0x00ad, 0x00ae, 0x00af, + /* b0 */ 0x00b0, 0x00b1, 0x00b2, 0x00b3, 0x00b4, 0x00b5, 0x00b6, 0x00b7, 0x00b8, 0x00b9, 0x00ba, 0x00bb, 0x00bc, 0x00bd, 0x00be, 0x00bf, + /* c0 */ 0x00c0, 0x00c1, 0x00c2, 0x00c3, 0x00c4, 0x00c5, 0x00c6, 0x00c7, 0x00c8, 0x00c9, 0x00ca, 0x00cb, 0x00cc, 0x00cd, 0x00ce, 0x00cf, + /* d0 */ 0x00d0, 0x00d1, 0x00d2, 0x00d3, 0x00d4, 0x00d5, 0x00d6, 0x00d7, 0x00d8, 0x00d9, 0x00da, 0x00db, 0x00dc, 0x00dd, 0x00de, 0x00df, + /* e0 */ 0x00e0, 0x00e1, 0x00e2, 0x00e3, 0x00e4, 0x00e5, 0x00e6, 0x00e7, 0x00e8, 0x00e9, 0x00ea, 0x00eb, 0x00ec, 0x00ed, 0x00ee, 0x00ef, + /* f0 */ 0x00f0, 0x00f1, 0x00f2, 0x00f3, 0x00f4, 0x00f5, 0x00f6, 0x00f7, 0x00f8, 0x00f9, 0x00fa, 0x00fb, 0x00fc, 0x00fd, 0x00fe, 0x00ff, +}; + + +Windows1252Encoding::Windows1252Encoding() +{ +} + + +Windows1252Encoding::~Windows1252Encoding() +{ +} + + +const TextEncoding::CharacterMap& Windows1252Encoding::characterMap() const +{ + return _charMap; +} + + +int Windows1252Encoding::convert(const unsigned char* bytes) const +{ + return *bytes; +} + + +int Windows1252Encoding::convert(int ch, unsigned char* bytes, int length) const +{ + if (ch >= 0 && ch <= 255) + { + *bytes = (unsigned char) ch; + return 1; + } + else return 0; +} + + +} // namespace Poco diff --git a/Foundation/src/adler32.c b/Foundation/src/adler32.c index f201d6701..007ba2627 100644 --- a/Foundation/src/adler32.c +++ b/Foundation/src/adler32.c @@ -1,149 +1,149 @@ -/* adler32.c -- compute the Adler-32 checksum of a data stream - * Copyright (C) 1995-2004 Mark Adler - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -/* @(#) $Id$ */ - -#define ZLIB_INTERNAL -#include "zlib.h" - -#define BASE 65521UL /* largest prime smaller than 65536 */ -#define NMAX 5552 -/* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */ - -#define DO1(buf,i) {adler += (buf)[i]; sum2 += adler;} -#define DO2(buf,i) DO1(buf,i); DO1(buf,i+1); -#define DO4(buf,i) DO2(buf,i); DO2(buf,i+2); -#define DO8(buf,i) DO4(buf,i); DO4(buf,i+4); -#define DO16(buf) DO8(buf,0); DO8(buf,8); - -/* use NO_DIVIDE if your processor does not do division in hardware */ -#ifdef NO_DIVIDE -# define MOD(a) \ - do { \ - if (a >= (BASE << 16)) a -= (BASE << 16); \ - if (a >= (BASE << 15)) a -= (BASE << 15); \ - if (a >= (BASE << 14)) a -= (BASE << 14); \ - if (a >= (BASE << 13)) a -= (BASE << 13); \ - if (a >= (BASE << 12)) a -= (BASE << 12); \ - if (a >= (BASE << 11)) a -= (BASE << 11); \ - if (a >= (BASE << 10)) a -= (BASE << 10); \ - if (a >= (BASE << 9)) a -= (BASE << 9); \ - if (a >= (BASE << 8)) a -= (BASE << 8); \ - if (a >= (BASE << 7)) a -= (BASE << 7); \ - if (a >= (BASE << 6)) a -= (BASE << 6); \ - if (a >= (BASE << 5)) a -= (BASE << 5); \ - if (a >= (BASE << 4)) a -= (BASE << 4); \ - if (a >= (BASE << 3)) a -= (BASE << 3); \ - if (a >= (BASE << 2)) a -= (BASE << 2); \ - if (a >= (BASE << 1)) a -= (BASE << 1); \ - if (a >= BASE) a -= BASE; \ - } while (0) -# define MOD4(a) \ - do { \ - if (a >= (BASE << 4)) a -= (BASE << 4); \ - if (a >= (BASE << 3)) a -= (BASE << 3); \ - if (a >= (BASE << 2)) a -= (BASE << 2); \ - if (a >= (BASE << 1)) a -= (BASE << 1); \ - if (a >= BASE) a -= BASE; \ - } while (0) -#else -# define MOD(a) a %= BASE -# define MOD4(a) a %= BASE -#endif - -/* ========================================================================= */ -uLong ZEXPORT adler32(adler, buf, len) - uLong adler; - const Bytef *buf; - uInt len; -{ - unsigned long sum2; - unsigned n; - - /* split Adler-32 into component sums */ - sum2 = (adler >> 16) & 0xffff; - adler &= 0xffff; - - /* in case user likes doing a byte at a time, keep it fast */ - if (len == 1) { - adler += buf[0]; - if (adler >= BASE) - adler -= BASE; - sum2 += adler; - if (sum2 >= BASE) - sum2 -= BASE; - return adler | (sum2 << 16); - } - - /* initial Adler-32 value (deferred check for len == 1 speed) */ - if (buf == Z_NULL) - return 1L; - - /* in case short lengths are provided, keep it somewhat fast */ - if (len < 16) { - while (len--) { - adler += *buf++; - sum2 += adler; - } - if (adler >= BASE) - adler -= BASE; - MOD4(sum2); /* only added so many BASE's */ - return adler | (sum2 << 16); - } - - /* do length NMAX blocks -- requires just one modulo operation */ - while (len >= NMAX) { - len -= NMAX; - n = NMAX / 16; /* NMAX is divisible by 16 */ - do { - DO16(buf); /* 16 sums unrolled */ - buf += 16; - } while (--n); - MOD(adler); - MOD(sum2); - } - - /* do remaining bytes (less than NMAX, still just one modulo) */ - if (len) { /* avoid modulos if none remaining */ - while (len >= 16) { - len -= 16; - DO16(buf); - buf += 16; - } - while (len--) { - adler += *buf++; - sum2 += adler; - } - MOD(adler); - MOD(sum2); - } - - /* return recombined sums */ - return adler | (sum2 << 16); -} - -/* ========================================================================= */ -uLong ZEXPORT adler32_combine(adler1, adler2, len2) - uLong adler1; - uLong adler2; - z_off_t len2; -{ - unsigned long sum1; - unsigned long sum2; - unsigned rem; - - /* the derivation of this formula is left as an exercise for the reader */ - rem = (unsigned)(len2 % BASE); - sum1 = adler1 & 0xffff; - sum2 = rem * sum1; - MOD(sum2); - sum1 += (adler2 & 0xffff) + BASE - 1; - sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + BASE - rem; - if (sum1 > BASE) sum1 -= BASE; - if (sum1 > BASE) sum1 -= BASE; - if (sum2 > (BASE << 1)) sum2 -= (BASE << 1); - if (sum2 > BASE) sum2 -= BASE; - return sum1 | (sum2 << 16); -} +/* adler32.c -- compute the Adler-32 checksum of a data stream + * Copyright (C) 1995-2004 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* @(#) $Id$ */ + +#define ZLIB_INTERNAL +#include "zlib.h" + +#define BASE 65521UL /* largest prime smaller than 65536 */ +#define NMAX 5552 +/* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */ + +#define DO1(buf,i) {adler += (buf)[i]; sum2 += adler;} +#define DO2(buf,i) DO1(buf,i); DO1(buf,i+1); +#define DO4(buf,i) DO2(buf,i); DO2(buf,i+2); +#define DO8(buf,i) DO4(buf,i); DO4(buf,i+4); +#define DO16(buf) DO8(buf,0); DO8(buf,8); + +/* use NO_DIVIDE if your processor does not do division in hardware */ +#ifdef NO_DIVIDE +# define MOD(a) \ + do { \ + if (a >= (BASE << 16)) a -= (BASE << 16); \ + if (a >= (BASE << 15)) a -= (BASE << 15); \ + if (a >= (BASE << 14)) a -= (BASE << 14); \ + if (a >= (BASE << 13)) a -= (BASE << 13); \ + if (a >= (BASE << 12)) a -= (BASE << 12); \ + if (a >= (BASE << 11)) a -= (BASE << 11); \ + if (a >= (BASE << 10)) a -= (BASE << 10); \ + if (a >= (BASE << 9)) a -= (BASE << 9); \ + if (a >= (BASE << 8)) a -= (BASE << 8); \ + if (a >= (BASE << 7)) a -= (BASE << 7); \ + if (a >= (BASE << 6)) a -= (BASE << 6); \ + if (a >= (BASE << 5)) a -= (BASE << 5); \ + if (a >= (BASE << 4)) a -= (BASE << 4); \ + if (a >= (BASE << 3)) a -= (BASE << 3); \ + if (a >= (BASE << 2)) a -= (BASE << 2); \ + if (a >= (BASE << 1)) a -= (BASE << 1); \ + if (a >= BASE) a -= BASE; \ + } while (0) +# define MOD4(a) \ + do { \ + if (a >= (BASE << 4)) a -= (BASE << 4); \ + if (a >= (BASE << 3)) a -= (BASE << 3); \ + if (a >= (BASE << 2)) a -= (BASE << 2); \ + if (a >= (BASE << 1)) a -= (BASE << 1); \ + if (a >= BASE) a -= BASE; \ + } while (0) +#else +# define MOD(a) a %= BASE +# define MOD4(a) a %= BASE +#endif + +/* ========================================================================= */ +uLong ZEXPORT adler32(adler, buf, len) + uLong adler; + const Bytef *buf; + uInt len; +{ + unsigned long sum2; + unsigned n; + + /* split Adler-32 into component sums */ + sum2 = (adler >> 16) & 0xffff; + adler &= 0xffff; + + /* in case user likes doing a byte at a time, keep it fast */ + if (len == 1) { + adler += buf[0]; + if (adler >= BASE) + adler -= BASE; + sum2 += adler; + if (sum2 >= BASE) + sum2 -= BASE; + return adler | (sum2 << 16); + } + + /* initial Adler-32 value (deferred check for len == 1 speed) */ + if (buf == Z_NULL) + return 1L; + + /* in case short lengths are provided, keep it somewhat fast */ + if (len < 16) { + while (len--) { + adler += *buf++; + sum2 += adler; + } + if (adler >= BASE) + adler -= BASE; + MOD4(sum2); /* only added so many BASE's */ + return adler | (sum2 << 16); + } + + /* do length NMAX blocks -- requires just one modulo operation */ + while (len >= NMAX) { + len -= NMAX; + n = NMAX / 16; /* NMAX is divisible by 16 */ + do { + DO16(buf); /* 16 sums unrolled */ + buf += 16; + } while (--n); + MOD(adler); + MOD(sum2); + } + + /* do remaining bytes (less than NMAX, still just one modulo) */ + if (len) { /* avoid modulos if none remaining */ + while (len >= 16) { + len -= 16; + DO16(buf); + buf += 16; + } + while (len--) { + adler += *buf++; + sum2 += adler; + } + MOD(adler); + MOD(sum2); + } + + /* return recombined sums */ + return adler | (sum2 << 16); +} + +/* ========================================================================= */ +uLong ZEXPORT adler32_combine(adler1, adler2, len2) + uLong adler1; + uLong adler2; + z_off_t len2; +{ + unsigned long sum1; + unsigned long sum2; + unsigned rem; + + /* the derivation of this formula is left as an exercise for the reader */ + rem = (unsigned)(len2 % BASE); + sum1 = adler1 & 0xffff; + sum2 = rem * sum1; + MOD(sum2); + sum1 += (adler2 & 0xffff) + BASE - 1; + sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + BASE - rem; + if (sum1 > BASE) sum1 -= BASE; + if (sum1 > BASE) sum1 -= BASE; + if (sum2 > (BASE << 1)) sum2 -= (BASE << 1); + if (sum2 > BASE) sum2 -= BASE; + return sum1 | (sum2 << 16); +} diff --git a/Foundation/src/chartables.c b/Foundation/src/chartables.c index 240960a8b..55e413cfc 100644 --- a/Foundation/src/chartables.c +++ b/Foundation/src/chartables.c @@ -1,183 +1,183 @@ -/************************************************* -* Perl-Compatible Regular Expressions * -*************************************************/ - -/* This file is automatically written by the dftables auxiliary -program. If you edit it by hand, you might like to edit the Makefile to -prevent its ever being regenerated. - -This file is #included in the compilation of pcre.c to build the default -character tables which are used when no tables are passed to the compile -function. */ - -static unsigned char pcre_default_tables[] = { - -/* This table is a lower casing table. */ - - 0, 1, 2, 3, 4, 5, 6, 7, - 8, 9, 10, 11, 12, 13, 14, 15, - 16, 17, 18, 19, 20, 21, 22, 23, - 24, 25, 26, 27, 28, 29, 30, 31, - 32, 33, 34, 35, 36, 37, 38, 39, - 40, 41, 42, 43, 44, 45, 46, 47, - 48, 49, 50, 51, 52, 53, 54, 55, - 56, 57, 58, 59, 60, 61, 62, 63, - 64, 97, 98, 99,100,101,102,103, - 104,105,106,107,108,109,110,111, - 112,113,114,115,116,117,118,119, - 120,121,122, 91, 92, 93, 94, 95, - 96, 97, 98, 99,100,101,102,103, - 104,105,106,107,108,109,110,111, - 112,113,114,115,116,117,118,119, - 120,121,122,123,124,125,126,127, - 128,129,130,131,132,133,134,135, - 136,137,138,139,140,141,142,143, - 144,145,146,147,148,149,150,151, - 152,153,154,155,156,157,158,159, - 160,161,162,163,164,165,166,167, - 168,169,170,171,172,173,174,175, - 176,177,178,179,180,181,182,183, - 184,185,186,187,188,189,190,191, - 192,193,194,195,196,197,198,199, - 200,201,202,203,204,205,206,207, - 208,209,210,211,212,213,214,215, - 216,217,218,219,220,221,222,223, - 224,225,226,227,228,229,230,231, - 232,233,234,235,236,237,238,239, - 240,241,242,243,244,245,246,247, - 248,249,250,251,252,253,254,255, - -/* This table is a case flipping table. */ - - 0, 1, 2, 3, 4, 5, 6, 7, - 8, 9, 10, 11, 12, 13, 14, 15, - 16, 17, 18, 19, 20, 21, 22, 23, - 24, 25, 26, 27, 28, 29, 30, 31, - 32, 33, 34, 35, 36, 37, 38, 39, - 40, 41, 42, 43, 44, 45, 46, 47, - 48, 49, 50, 51, 52, 53, 54, 55, - 56, 57, 58, 59, 60, 61, 62, 63, - 64, 97, 98, 99,100,101,102,103, - 104,105,106,107,108,109,110,111, - 112,113,114,115,116,117,118,119, - 120,121,122, 91, 92, 93, 94, 95, - 96, 65, 66, 67, 68, 69, 70, 71, - 72, 73, 74, 75, 76, 77, 78, 79, - 80, 81, 82, 83, 84, 85, 86, 87, - 88, 89, 90,123,124,125,126,127, - 128,129,130,131,132,133,134,135, - 136,137,138,139,140,141,142,143, - 144,145,146,147,148,149,150,151, - 152,153,154,155,156,157,158,159, - 160,161,162,163,164,165,166,167, - 168,169,170,171,172,173,174,175, - 176,177,178,179,180,181,182,183, - 184,185,186,187,188,189,190,191, - 192,193,194,195,196,197,198,199, - 200,201,202,203,204,205,206,207, - 208,209,210,211,212,213,214,215, - 216,217,218,219,220,221,222,223, - 224,225,226,227,228,229,230,231, - 232,233,234,235,236,237,238,239, - 240,241,242,243,244,245,246,247, - 248,249,250,251,252,253,254,255, - -/* This table contains bit maps for various character classes. -Each map is 32 bytes long and the bits run from the least -significant end of each byte. The classes that have their own -maps are: space, xdigit, digit, upper, lower, word, graph -print, punct, and cntrl. Other classes are built from combinations. */ - - 0x00,0x3e,0x00,0x00,0x01,0x00,0x00,0x00, - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, - - 0x00,0x00,0x00,0x00,0x00,0x00,0xff,0x03, - 0x7e,0x00,0x00,0x00,0x7e,0x00,0x00,0x00, - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, - - 0x00,0x00,0x00,0x00,0x00,0x00,0xff,0x03, - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, - - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, - 0xfe,0xff,0xff,0x07,0x00,0x00,0x00,0x00, - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, - - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, - 0x00,0x00,0x00,0x00,0xfe,0xff,0xff,0x07, - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, - - 0x00,0x00,0x00,0x00,0x00,0x00,0xff,0x03, - 0xfe,0xff,0xff,0x87,0xfe,0xff,0xff,0x07, - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, - - 0x00,0x00,0x00,0x00,0xfe,0xff,0xff,0xff, - 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x7f, - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, - - 0x00,0x00,0x00,0x00,0xff,0xff,0xff,0xff, - 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x7f, - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, - - 0x00,0x00,0x00,0x00,0xfe,0xff,0x00,0xfc, - 0x01,0x00,0x00,0xf8,0x01,0x00,0x00,0x78, - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, - - 0xff,0xff,0xff,0xff,0x00,0x00,0x00,0x00, - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x80, - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, - -/* This table identifies various classes of character by individual bits: - 0x01 white space character - 0x02 letter - 0x04 decimal digit - 0x08 hexadecimal digit - 0x10 alphanumeric or '_' - 0x80 regular expression metacharacter or binary zero -*/ - - 0x80,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 0- 7 */ - 0x00,0x01,0x01,0x00,0x01,0x01,0x00,0x00, /* 8- 15 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 16- 23 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 24- 31 */ - 0x01,0x00,0x00,0x00,0x80,0x00,0x00,0x00, /* - ' */ - 0x80,0x80,0x80,0x80,0x00,0x00,0x80,0x00, /* ( - / */ - 0x1c,0x1c,0x1c,0x1c,0x1c,0x1c,0x1c,0x1c, /* 0 - 7 */ - 0x1c,0x1c,0x00,0x00,0x00,0x00,0x00,0x80, /* 8 - ? */ - 0x00,0x1a,0x1a,0x1a,0x1a,0x1a,0x1a,0x12, /* @ - G */ - 0x12,0x12,0x12,0x12,0x12,0x12,0x12,0x12, /* H - O */ - 0x12,0x12,0x12,0x12,0x12,0x12,0x12,0x12, /* P - W */ - 0x12,0x12,0x12,0x80,0x00,0x00,0x80,0x10, /* X - _ */ - 0x00,0x1a,0x1a,0x1a,0x1a,0x1a,0x1a,0x12, /* ` - g */ - 0x12,0x12,0x12,0x12,0x12,0x12,0x12,0x12, /* h - o */ - 0x12,0x12,0x12,0x12,0x12,0x12,0x12,0x12, /* p - w */ - 0x12,0x12,0x12,0x80,0x80,0x00,0x00,0x00, /* x -127 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 128-135 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 136-143 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 144-151 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 152-159 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 160-167 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 168-175 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 176-183 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 184-191 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 192-199 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 200-207 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 208-215 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 216-223 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 224-231 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 232-239 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 240-247 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};/* 248-255 */ - -/* End of chartables.c */ +/************************************************* +* Perl-Compatible Regular Expressions * +*************************************************/ + +/* This file is automatically written by the dftables auxiliary +program. If you edit it by hand, you might like to edit the Makefile to +prevent its ever being regenerated. + +This file is #included in the compilation of pcre.c to build the default +character tables which are used when no tables are passed to the compile +function. */ + +static unsigned char pcre_default_tables[] = { + +/* This table is a lower casing table. */ + + 0, 1, 2, 3, 4, 5, 6, 7, + 8, 9, 10, 11, 12, 13, 14, 15, + 16, 17, 18, 19, 20, 21, 22, 23, + 24, 25, 26, 27, 28, 29, 30, 31, + 32, 33, 34, 35, 36, 37, 38, 39, + 40, 41, 42, 43, 44, 45, 46, 47, + 48, 49, 50, 51, 52, 53, 54, 55, + 56, 57, 58, 59, 60, 61, 62, 63, + 64, 97, 98, 99,100,101,102,103, + 104,105,106,107,108,109,110,111, + 112,113,114,115,116,117,118,119, + 120,121,122, 91, 92, 93, 94, 95, + 96, 97, 98, 99,100,101,102,103, + 104,105,106,107,108,109,110,111, + 112,113,114,115,116,117,118,119, + 120,121,122,123,124,125,126,127, + 128,129,130,131,132,133,134,135, + 136,137,138,139,140,141,142,143, + 144,145,146,147,148,149,150,151, + 152,153,154,155,156,157,158,159, + 160,161,162,163,164,165,166,167, + 168,169,170,171,172,173,174,175, + 176,177,178,179,180,181,182,183, + 184,185,186,187,188,189,190,191, + 192,193,194,195,196,197,198,199, + 200,201,202,203,204,205,206,207, + 208,209,210,211,212,213,214,215, + 216,217,218,219,220,221,222,223, + 224,225,226,227,228,229,230,231, + 232,233,234,235,236,237,238,239, + 240,241,242,243,244,245,246,247, + 248,249,250,251,252,253,254,255, + +/* This table is a case flipping table. */ + + 0, 1, 2, 3, 4, 5, 6, 7, + 8, 9, 10, 11, 12, 13, 14, 15, + 16, 17, 18, 19, 20, 21, 22, 23, + 24, 25, 26, 27, 28, 29, 30, 31, + 32, 33, 34, 35, 36, 37, 38, 39, + 40, 41, 42, 43, 44, 45, 46, 47, + 48, 49, 50, 51, 52, 53, 54, 55, + 56, 57, 58, 59, 60, 61, 62, 63, + 64, 97, 98, 99,100,101,102,103, + 104,105,106,107,108,109,110,111, + 112,113,114,115,116,117,118,119, + 120,121,122, 91, 92, 93, 94, 95, + 96, 65, 66, 67, 68, 69, 70, 71, + 72, 73, 74, 75, 76, 77, 78, 79, + 80, 81, 82, 83, 84, 85, 86, 87, + 88, 89, 90,123,124,125,126,127, + 128,129,130,131,132,133,134,135, + 136,137,138,139,140,141,142,143, + 144,145,146,147,148,149,150,151, + 152,153,154,155,156,157,158,159, + 160,161,162,163,164,165,166,167, + 168,169,170,171,172,173,174,175, + 176,177,178,179,180,181,182,183, + 184,185,186,187,188,189,190,191, + 192,193,194,195,196,197,198,199, + 200,201,202,203,204,205,206,207, + 208,209,210,211,212,213,214,215, + 216,217,218,219,220,221,222,223, + 224,225,226,227,228,229,230,231, + 232,233,234,235,236,237,238,239, + 240,241,242,243,244,245,246,247, + 248,249,250,251,252,253,254,255, + +/* This table contains bit maps for various character classes. +Each map is 32 bytes long and the bits run from the least +significant end of each byte. The classes that have their own +maps are: space, xdigit, digit, upper, lower, word, graph +print, punct, and cntrl. Other classes are built from combinations. */ + + 0x00,0x3e,0x00,0x00,0x01,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + + 0x00,0x00,0x00,0x00,0x00,0x00,0xff,0x03, + 0x7e,0x00,0x00,0x00,0x7e,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + + 0x00,0x00,0x00,0x00,0x00,0x00,0xff,0x03, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0xfe,0xff,0xff,0x07,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0xfe,0xff,0xff,0x07, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + + 0x00,0x00,0x00,0x00,0x00,0x00,0xff,0x03, + 0xfe,0xff,0xff,0x87,0xfe,0xff,0xff,0x07, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + + 0x00,0x00,0x00,0x00,0xfe,0xff,0xff,0xff, + 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x7f, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + + 0x00,0x00,0x00,0x00,0xff,0xff,0xff,0xff, + 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x7f, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + + 0x00,0x00,0x00,0x00,0xfe,0xff,0x00,0xfc, + 0x01,0x00,0x00,0xf8,0x01,0x00,0x00,0x78, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + + 0xff,0xff,0xff,0xff,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x80, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + +/* This table identifies various classes of character by individual bits: + 0x01 white space character + 0x02 letter + 0x04 decimal digit + 0x08 hexadecimal digit + 0x10 alphanumeric or '_' + 0x80 regular expression metacharacter or binary zero +*/ + + 0x80,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 0- 7 */ + 0x00,0x01,0x01,0x00,0x01,0x01,0x00,0x00, /* 8- 15 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 16- 23 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 24- 31 */ + 0x01,0x00,0x00,0x00,0x80,0x00,0x00,0x00, /* - ' */ + 0x80,0x80,0x80,0x80,0x00,0x00,0x80,0x00, /* ( - / */ + 0x1c,0x1c,0x1c,0x1c,0x1c,0x1c,0x1c,0x1c, /* 0 - 7 */ + 0x1c,0x1c,0x00,0x00,0x00,0x00,0x00,0x80, /* 8 - ? */ + 0x00,0x1a,0x1a,0x1a,0x1a,0x1a,0x1a,0x12, /* @ - G */ + 0x12,0x12,0x12,0x12,0x12,0x12,0x12,0x12, /* H - O */ + 0x12,0x12,0x12,0x12,0x12,0x12,0x12,0x12, /* P - W */ + 0x12,0x12,0x12,0x80,0x00,0x00,0x80,0x10, /* X - _ */ + 0x00,0x1a,0x1a,0x1a,0x1a,0x1a,0x1a,0x12, /* ` - g */ + 0x12,0x12,0x12,0x12,0x12,0x12,0x12,0x12, /* h - o */ + 0x12,0x12,0x12,0x12,0x12,0x12,0x12,0x12, /* p - w */ + 0x12,0x12,0x12,0x80,0x80,0x00,0x00,0x00, /* x -127 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 128-135 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 136-143 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 144-151 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 152-159 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 160-167 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 168-175 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 176-183 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 184-191 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 192-199 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 200-207 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 208-215 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 216-223 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 224-231 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 232-239 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 240-247 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};/* 248-255 */ + +/* End of chartables.c */ diff --git a/Foundation/src/compress.c b/Foundation/src/compress.c index 0d0f2cd37..2bbca37e7 100644 --- a/Foundation/src/compress.c +++ b/Foundation/src/compress.c @@ -1,79 +1,79 @@ -/* compress.c -- compress a memory buffer - * Copyright (C) 1995-2003 Jean-loup Gailly. - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -/* @(#) $Id: //poco/1.2/Foundation/src/compress.c#1 $ */ - -#define ZLIB_INTERNAL -#include "zlib.h" - -/* =========================================================================== - Compresses the source buffer into the destination buffer. The level - parameter has the same meaning as in deflateInit. sourceLen is the byte - length of the source buffer. Upon entry, destLen is the total size of the - destination buffer, which must be at least 0.1% larger than sourceLen plus - 12 bytes. Upon exit, destLen is the actual size of the compressed buffer. - - compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough - memory, Z_BUF_ERROR if there was not enough room in the output buffer, - Z_STREAM_ERROR if the level parameter is invalid. -*/ -int ZEXPORT compress2 (dest, destLen, source, sourceLen, level) - Bytef *dest; - uLongf *destLen; - const Bytef *source; - uLong sourceLen; - int level; -{ - z_stream stream; - int err; - - stream.next_in = (Bytef*)source; - stream.avail_in = (uInt)sourceLen; -#ifdef MAXSEG_64K - /* Check for source > 64K on 16-bit machine: */ - if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR; -#endif - stream.next_out = dest; - stream.avail_out = (uInt)*destLen; - if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR; - - stream.zalloc = (alloc_func)0; - stream.zfree = (free_func)0; - stream.opaque = (voidpf)0; - - err = deflateInit(&stream, level); - if (err != Z_OK) return err; - - err = deflate(&stream, Z_FINISH); - if (err != Z_STREAM_END) { - deflateEnd(&stream); - return err == Z_OK ? Z_BUF_ERROR : err; - } - *destLen = stream.total_out; - - err = deflateEnd(&stream); - return err; -} - -/* =========================================================================== - */ -int ZEXPORT compress (dest, destLen, source, sourceLen) - Bytef *dest; - uLongf *destLen; - const Bytef *source; - uLong sourceLen; -{ - return compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION); -} - -/* =========================================================================== - If the default memLevel or windowBits for deflateInit() is changed, then - this function needs to be updated. - */ -uLong ZEXPORT compressBound (sourceLen) - uLong sourceLen; -{ - return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + 11; -} +/* compress.c -- compress a memory buffer + * Copyright (C) 1995-2003 Jean-loup Gailly. + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* @(#) $Id: //poco/1.2/Foundation/src/compress.c#1 $ */ + +#define ZLIB_INTERNAL +#include "zlib.h" + +/* =========================================================================== + Compresses the source buffer into the destination buffer. The level + parameter has the same meaning as in deflateInit. sourceLen is the byte + length of the source buffer. Upon entry, destLen is the total size of the + destination buffer, which must be at least 0.1% larger than sourceLen plus + 12 bytes. Upon exit, destLen is the actual size of the compressed buffer. + + compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_BUF_ERROR if there was not enough room in the output buffer, + Z_STREAM_ERROR if the level parameter is invalid. +*/ +int ZEXPORT compress2 (dest, destLen, source, sourceLen, level) + Bytef *dest; + uLongf *destLen; + const Bytef *source; + uLong sourceLen; + int level; +{ + z_stream stream; + int err; + + stream.next_in = (Bytef*)source; + stream.avail_in = (uInt)sourceLen; +#ifdef MAXSEG_64K + /* Check for source > 64K on 16-bit machine: */ + if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR; +#endif + stream.next_out = dest; + stream.avail_out = (uInt)*destLen; + if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR; + + stream.zalloc = (alloc_func)0; + stream.zfree = (free_func)0; + stream.opaque = (voidpf)0; + + err = deflateInit(&stream, level); + if (err != Z_OK) return err; + + err = deflate(&stream, Z_FINISH); + if (err != Z_STREAM_END) { + deflateEnd(&stream); + return err == Z_OK ? Z_BUF_ERROR : err; + } + *destLen = stream.total_out; + + err = deflateEnd(&stream); + return err; +} + +/* =========================================================================== + */ +int ZEXPORT compress (dest, destLen, source, sourceLen) + Bytef *dest; + uLongf *destLen; + const Bytef *source; + uLong sourceLen; +{ + return compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION); +} + +/* =========================================================================== + If the default memLevel or windowBits for deflateInit() is changed, then + this function needs to be updated. + */ +uLong ZEXPORT compressBound (sourceLen) + uLong sourceLen; +{ + return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + 11; +} diff --git a/Foundation/src/crc32.c b/Foundation/src/crc32.c index 2dacc87c9..11982bcee 100644 --- a/Foundation/src/crc32.c +++ b/Foundation/src/crc32.c @@ -1,423 +1,423 @@ -/* crc32.c -- compute the CRC-32 of a data stream - * Copyright (C) 1995-2005 Mark Adler - * For conditions of distribution and use, see copyright notice in zlib.h - * - * Thanks to Rodney Brown for his contribution of faster - * CRC methods: exclusive-oring 32 bits of data at a time, and pre-computing - * tables for updating the shift register in one step with three exclusive-ors - * instead of four steps with four exclusive-ors. This results in about a - * factor of two increase in speed on a Power PC G4 (PPC7455) using gcc -O3. - */ - -/* @(#) $Id: //poco/1.2/Foundation/src/crc32.c#1 $ */ - -/* - Note on the use of DYNAMIC_CRC_TABLE: there is no mutex or semaphore - protection on the static variables used to control the first-use generation - of the crc tables. Therefore, if you #define DYNAMIC_CRC_TABLE, you should - first call get_crc_table() to initialize the tables before allowing more than - one thread to use crc32(). - */ - -#ifdef MAKECRCH -# include -# ifndef DYNAMIC_CRC_TABLE -# define DYNAMIC_CRC_TABLE -# endif /* !DYNAMIC_CRC_TABLE */ -#endif /* MAKECRCH */ - -#include "zutil.h" /* for STDC and FAR definitions */ - -#define local static - -/* Find a four-byte integer type for crc32_little() and crc32_big(). */ -#ifndef NOBYFOUR -# ifdef STDC /* need ANSI C limits.h to determine sizes */ -# include -# define BYFOUR -# if (UINT_MAX == 0xffffffffUL) - typedef unsigned int u4; -# else -# if (ULONG_MAX == 0xffffffffUL) - typedef unsigned long u4; -# else -# if (USHRT_MAX == 0xffffffffUL) - typedef unsigned short u4; -# else -# undef BYFOUR /* can't find a four-byte integer type! */ -# endif -# endif -# endif -# endif /* STDC */ -#endif /* !NOBYFOUR */ - -/* Definitions for doing the crc four data bytes at a time. */ -#ifdef BYFOUR -# define REV(w) (((w)>>24)+(((w)>>8)&0xff00)+ \ - (((w)&0xff00)<<8)+(((w)&0xff)<<24)) - local unsigned long crc32_little OF((unsigned long, - const unsigned char FAR *, unsigned)); - local unsigned long crc32_big OF((unsigned long, - const unsigned char FAR *, unsigned)); -# define TBLS 8 -#else -# define TBLS 1 -#endif /* BYFOUR */ - -/* Local functions for crc concatenation */ -local unsigned long gf2_matrix_times OF((unsigned long *mat, - unsigned long vec)); -local void gf2_matrix_square OF((unsigned long *square, unsigned long *mat)); - -#ifdef DYNAMIC_CRC_TABLE - -local volatile int crc_table_empty = 1; -local unsigned long FAR crc_table[TBLS][256]; -local void make_crc_table OF((void)); -#ifdef MAKECRCH - local void write_table OF((FILE *, const unsigned long FAR *)); -#endif /* MAKECRCH */ -/* - Generate tables for a byte-wise 32-bit CRC calculation on the polynomial: - x^32+x^26+x^23+x^22+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x+1. - - Polynomials over GF(2) are represented in binary, one bit per coefficient, - with the lowest powers in the most significant bit. Then adding polynomials - is just exclusive-or, and multiplying a polynomial by x is a right shift by - one. If we call the above polynomial p, and represent a byte as the - polynomial q, also with the lowest power in the most significant bit (so the - byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p, - where a mod b means the remainder after dividing a by b. - - This calculation is done using the shift-register method of multiplying and - taking the remainder. The register is initialized to zero, and for each - incoming bit, x^32 is added mod p to the register if the bit is a one (where - x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by - x (which is shifting right by one and adding x^32 mod p if the bit shifted - out is a one). We start with the highest power (least significant bit) of - q and repeat for all eight bits of q. - - The first table is simply the CRC of all possible eight bit values. This is - all the information needed to generate CRCs on data a byte at a time for all - combinations of CRC register values and incoming bytes. The remaining tables - allow for word-at-a-time CRC calculation for both big-endian and little- - endian machines, where a word is four bytes. -*/ -local void make_crc_table() -{ - unsigned long c; - int n, k; - unsigned long poly; /* polynomial exclusive-or pattern */ - /* terms of polynomial defining this crc (except x^32): */ - static volatile int first = 1; /* flag to limit concurrent making */ - static const unsigned char p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26}; - - /* See if another task is already doing this (not thread-safe, but better - than nothing -- significantly reduces duration of vulnerability in - case the advice about DYNAMIC_CRC_TABLE is ignored) */ - if (first) { - first = 0; - - /* make exclusive-or pattern from polynomial (0xedb88320UL) */ - poly = 0UL; - for (n = 0; n < sizeof(p)/sizeof(unsigned char); n++) - poly |= 1UL << (31 - p[n]); - - /* generate a crc for every 8-bit value */ - for (n = 0; n < 256; n++) { - c = (unsigned long)n; - for (k = 0; k < 8; k++) - c = c & 1 ? poly ^ (c >> 1) : c >> 1; - crc_table[0][n] = c; - } - -#ifdef BYFOUR - /* generate crc for each value followed by one, two, and three zeros, - and then the byte reversal of those as well as the first table */ - for (n = 0; n < 256; n++) { - c = crc_table[0][n]; - crc_table[4][n] = REV(c); - for (k = 1; k < 4; k++) { - c = crc_table[0][c & 0xff] ^ (c >> 8); - crc_table[k][n] = c; - crc_table[k + 4][n] = REV(c); - } - } -#endif /* BYFOUR */ - - crc_table_empty = 0; - } - else { /* not first */ - /* wait for the other guy to finish (not efficient, but rare) */ - while (crc_table_empty) - ; - } - -#ifdef MAKECRCH - /* write out CRC tables to crc32.h */ - { - FILE *out; - - out = fopen("crc32.h", "w"); - if (out == NULL) return; - fprintf(out, "/* crc32.h -- tables for rapid CRC calculation\n"); - fprintf(out, " * Generated automatically by crc32.c\n */\n\n"); - fprintf(out, "local const unsigned long FAR "); - fprintf(out, "crc_table[TBLS][256] =\n{\n {\n"); - write_table(out, crc_table[0]); -# ifdef BYFOUR - fprintf(out, "#ifdef BYFOUR\n"); - for (k = 1; k < 8; k++) { - fprintf(out, " },\n {\n"); - write_table(out, crc_table[k]); - } - fprintf(out, "#endif\n"); -# endif /* BYFOUR */ - fprintf(out, " }\n};\n"); - fclose(out); - } -#endif /* MAKECRCH */ -} - -#ifdef MAKECRCH -local void write_table(out, table) - FILE *out; - const unsigned long FAR *table; -{ - int n; - - for (n = 0; n < 256; n++) - fprintf(out, "%s0x%08lxUL%s", n % 5 ? "" : " ", table[n], - n == 255 ? "\n" : (n % 5 == 4 ? ",\n" : ", ")); -} -#endif /* MAKECRCH */ - -#else /* !DYNAMIC_CRC_TABLE */ -/* ======================================================================== - * Tables of CRC-32s of all single-byte values, made by make_crc_table(). - */ -#include "crc32.h" -#endif /* DYNAMIC_CRC_TABLE */ - -/* ========================================================================= - * This function can be used by asm versions of crc32() - */ -const unsigned long FAR * ZEXPORT get_crc_table() -{ -#ifdef DYNAMIC_CRC_TABLE - if (crc_table_empty) - make_crc_table(); -#endif /* DYNAMIC_CRC_TABLE */ - return (const unsigned long FAR *)crc_table; -} - -/* ========================================================================= */ -#define DO1 crc = crc_table[0][((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8) -#define DO8 DO1; DO1; DO1; DO1; DO1; DO1; DO1; DO1 - -/* ========================================================================= */ -unsigned long ZEXPORT crc32(crc, buf, len) - unsigned long crc; - const unsigned char FAR *buf; - unsigned len; -{ - if (buf == Z_NULL) return 0UL; - -#ifdef DYNAMIC_CRC_TABLE - if (crc_table_empty) - make_crc_table(); -#endif /* DYNAMIC_CRC_TABLE */ - -#ifdef BYFOUR - if (sizeof(void *) == sizeof(ptrdiff_t)) { - u4 endian; - - endian = 1; - if (*((unsigned char *)(&endian))) - return crc32_little(crc, buf, len); - else - return crc32_big(crc, buf, len); - } -#endif /* BYFOUR */ - crc = crc ^ 0xffffffffUL; - while (len >= 8) { - DO8; - len -= 8; - } - if (len) do { - DO1; - } while (--len); - return crc ^ 0xffffffffUL; -} - -#ifdef BYFOUR - -/* ========================================================================= */ -#define DOLIT4 c ^= *buf4++; \ - c = crc_table[3][c & 0xff] ^ crc_table[2][(c >> 8) & 0xff] ^ \ - crc_table[1][(c >> 16) & 0xff] ^ crc_table[0][c >> 24] -#define DOLIT32 DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4 - -/* ========================================================================= */ -local unsigned long crc32_little(crc, buf, len) - unsigned long crc; - const unsigned char FAR *buf; - unsigned len; -{ - register u4 c; - register const u4 FAR *buf4; - - c = (u4)crc; - c = ~c; - while (len && ((ptrdiff_t)buf & 3)) { - c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8); - len--; - } - - buf4 = (const u4 FAR *)(const void FAR *)buf; - while (len >= 32) { - DOLIT32; - len -= 32; - } - while (len >= 4) { - DOLIT4; - len -= 4; - } - buf = (const unsigned char FAR *)buf4; - - if (len) do { - c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8); - } while (--len); - c = ~c; - return (unsigned long)c; -} - -/* ========================================================================= */ -#define DOBIG4 c ^= *++buf4; \ - c = crc_table[4][c & 0xff] ^ crc_table[5][(c >> 8) & 0xff] ^ \ - crc_table[6][(c >> 16) & 0xff] ^ crc_table[7][c >> 24] -#define DOBIG32 DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4 - -/* ========================================================================= */ -local unsigned long crc32_big(crc, buf, len) - unsigned long crc; - const unsigned char FAR *buf; - unsigned len; -{ - register u4 c; - register const u4 FAR *buf4; - - c = REV((u4)crc); - c = ~c; - while (len && ((ptrdiff_t)buf & 3)) { - c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8); - len--; - } - - buf4 = (const u4 FAR *)(const void FAR *)buf; - buf4--; - while (len >= 32) { - DOBIG32; - len -= 32; - } - while (len >= 4) { - DOBIG4; - len -= 4; - } - buf4++; - buf = (const unsigned char FAR *)buf4; - - if (len) do { - c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8); - } while (--len); - c = ~c; - return (unsigned long)(REV(c)); -} - -#endif /* BYFOUR */ - -#define GF2_DIM 32 /* dimension of GF(2) vectors (length of CRC) */ - -/* ========================================================================= */ -local unsigned long gf2_matrix_times(mat, vec) - unsigned long *mat; - unsigned long vec; -{ - unsigned long sum; - - sum = 0; - while (vec) { - if (vec & 1) - sum ^= *mat; - vec >>= 1; - mat++; - } - return sum; -} - -/* ========================================================================= */ -local void gf2_matrix_square(square, mat) - unsigned long *square; - unsigned long *mat; -{ - int n; - - for (n = 0; n < GF2_DIM; n++) - square[n] = gf2_matrix_times(mat, mat[n]); -} - -/* ========================================================================= */ -uLong ZEXPORT crc32_combine(crc1, crc2, len2) - uLong crc1; - uLong crc2; - z_off_t len2; -{ - int n; - unsigned long row; - unsigned long even[GF2_DIM]; /* even-power-of-two zeros operator */ - unsigned long odd[GF2_DIM]; /* odd-power-of-two zeros operator */ - - /* degenerate case */ - if (len2 == 0) - return crc1; - - /* put operator for one zero bit in odd */ - odd[0] = 0xedb88320L; /* CRC-32 polynomial */ - row = 1; - for (n = 1; n < GF2_DIM; n++) { - odd[n] = row; - row <<= 1; - } - - /* put operator for two zero bits in even */ - gf2_matrix_square(even, odd); - - /* put operator for four zero bits in odd */ - gf2_matrix_square(odd, even); - - /* apply len2 zeros to crc1 (first square will put the operator for one - zero byte, eight zero bits, in even) */ - do { - /* apply zeros operator for this bit of len2 */ - gf2_matrix_square(even, odd); - if (len2 & 1) - crc1 = gf2_matrix_times(even, crc1); - len2 >>= 1; - - /* if no more bits set, then done */ - if (len2 == 0) - break; - - /* another iteration of the loop with odd and even swapped */ - gf2_matrix_square(odd, even); - if (len2 & 1) - crc1 = gf2_matrix_times(odd, crc1); - len2 >>= 1; - - /* if no more bits set, then done */ - } while (len2 != 0); - - /* return combined crc */ - crc1 ^= crc2; - return crc1; -} +/* crc32.c -- compute the CRC-32 of a data stream + * Copyright (C) 1995-2005 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + * + * Thanks to Rodney Brown for his contribution of faster + * CRC methods: exclusive-oring 32 bits of data at a time, and pre-computing + * tables for updating the shift register in one step with three exclusive-ors + * instead of four steps with four exclusive-ors. This results in about a + * factor of two increase in speed on a Power PC G4 (PPC7455) using gcc -O3. + */ + +/* @(#) $Id: //poco/1.2/Foundation/src/crc32.c#1 $ */ + +/* + Note on the use of DYNAMIC_CRC_TABLE: there is no mutex or semaphore + protection on the static variables used to control the first-use generation + of the crc tables. Therefore, if you #define DYNAMIC_CRC_TABLE, you should + first call get_crc_table() to initialize the tables before allowing more than + one thread to use crc32(). + */ + +#ifdef MAKECRCH +# include +# ifndef DYNAMIC_CRC_TABLE +# define DYNAMIC_CRC_TABLE +# endif /* !DYNAMIC_CRC_TABLE */ +#endif /* MAKECRCH */ + +#include "zutil.h" /* for STDC and FAR definitions */ + +#define local static + +/* Find a four-byte integer type for crc32_little() and crc32_big(). */ +#ifndef NOBYFOUR +# ifdef STDC /* need ANSI C limits.h to determine sizes */ +# include +# define BYFOUR +# if (UINT_MAX == 0xffffffffUL) + typedef unsigned int u4; +# else +# if (ULONG_MAX == 0xffffffffUL) + typedef unsigned long u4; +# else +# if (USHRT_MAX == 0xffffffffUL) + typedef unsigned short u4; +# else +# undef BYFOUR /* can't find a four-byte integer type! */ +# endif +# endif +# endif +# endif /* STDC */ +#endif /* !NOBYFOUR */ + +/* Definitions for doing the crc four data bytes at a time. */ +#ifdef BYFOUR +# define REV(w) (((w)>>24)+(((w)>>8)&0xff00)+ \ + (((w)&0xff00)<<8)+(((w)&0xff)<<24)) + local unsigned long crc32_little OF((unsigned long, + const unsigned char FAR *, unsigned)); + local unsigned long crc32_big OF((unsigned long, + const unsigned char FAR *, unsigned)); +# define TBLS 8 +#else +# define TBLS 1 +#endif /* BYFOUR */ + +/* Local functions for crc concatenation */ +local unsigned long gf2_matrix_times OF((unsigned long *mat, + unsigned long vec)); +local void gf2_matrix_square OF((unsigned long *square, unsigned long *mat)); + +#ifdef DYNAMIC_CRC_TABLE + +local volatile int crc_table_empty = 1; +local unsigned long FAR crc_table[TBLS][256]; +local void make_crc_table OF((void)); +#ifdef MAKECRCH + local void write_table OF((FILE *, const unsigned long FAR *)); +#endif /* MAKECRCH */ +/* + Generate tables for a byte-wise 32-bit CRC calculation on the polynomial: + x^32+x^26+x^23+x^22+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x+1. + + Polynomials over GF(2) are represented in binary, one bit per coefficient, + with the lowest powers in the most significant bit. Then adding polynomials + is just exclusive-or, and multiplying a polynomial by x is a right shift by + one. If we call the above polynomial p, and represent a byte as the + polynomial q, also with the lowest power in the most significant bit (so the + byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p, + where a mod b means the remainder after dividing a by b. + + This calculation is done using the shift-register method of multiplying and + taking the remainder. The register is initialized to zero, and for each + incoming bit, x^32 is added mod p to the register if the bit is a one (where + x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by + x (which is shifting right by one and adding x^32 mod p if the bit shifted + out is a one). We start with the highest power (least significant bit) of + q and repeat for all eight bits of q. + + The first table is simply the CRC of all possible eight bit values. This is + all the information needed to generate CRCs on data a byte at a time for all + combinations of CRC register values and incoming bytes. The remaining tables + allow for word-at-a-time CRC calculation for both big-endian and little- + endian machines, where a word is four bytes. +*/ +local void make_crc_table() +{ + unsigned long c; + int n, k; + unsigned long poly; /* polynomial exclusive-or pattern */ + /* terms of polynomial defining this crc (except x^32): */ + static volatile int first = 1; /* flag to limit concurrent making */ + static const unsigned char p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26}; + + /* See if another task is already doing this (not thread-safe, but better + than nothing -- significantly reduces duration of vulnerability in + case the advice about DYNAMIC_CRC_TABLE is ignored) */ + if (first) { + first = 0; + + /* make exclusive-or pattern from polynomial (0xedb88320UL) */ + poly = 0UL; + for (n = 0; n < sizeof(p)/sizeof(unsigned char); n++) + poly |= 1UL << (31 - p[n]); + + /* generate a crc for every 8-bit value */ + for (n = 0; n < 256; n++) { + c = (unsigned long)n; + for (k = 0; k < 8; k++) + c = c & 1 ? poly ^ (c >> 1) : c >> 1; + crc_table[0][n] = c; + } + +#ifdef BYFOUR + /* generate crc for each value followed by one, two, and three zeros, + and then the byte reversal of those as well as the first table */ + for (n = 0; n < 256; n++) { + c = crc_table[0][n]; + crc_table[4][n] = REV(c); + for (k = 1; k < 4; k++) { + c = crc_table[0][c & 0xff] ^ (c >> 8); + crc_table[k][n] = c; + crc_table[k + 4][n] = REV(c); + } + } +#endif /* BYFOUR */ + + crc_table_empty = 0; + } + else { /* not first */ + /* wait for the other guy to finish (not efficient, but rare) */ + while (crc_table_empty) + ; + } + +#ifdef MAKECRCH + /* write out CRC tables to crc32.h */ + { + FILE *out; + + out = fopen("crc32.h", "w"); + if (out == NULL) return; + fprintf(out, "/* crc32.h -- tables for rapid CRC calculation\n"); + fprintf(out, " * Generated automatically by crc32.c\n */\n\n"); + fprintf(out, "local const unsigned long FAR "); + fprintf(out, "crc_table[TBLS][256] =\n{\n {\n"); + write_table(out, crc_table[0]); +# ifdef BYFOUR + fprintf(out, "#ifdef BYFOUR\n"); + for (k = 1; k < 8; k++) { + fprintf(out, " },\n {\n"); + write_table(out, crc_table[k]); + } + fprintf(out, "#endif\n"); +# endif /* BYFOUR */ + fprintf(out, " }\n};\n"); + fclose(out); + } +#endif /* MAKECRCH */ +} + +#ifdef MAKECRCH +local void write_table(out, table) + FILE *out; + const unsigned long FAR *table; +{ + int n; + + for (n = 0; n < 256; n++) + fprintf(out, "%s0x%08lxUL%s", n % 5 ? "" : " ", table[n], + n == 255 ? "\n" : (n % 5 == 4 ? ",\n" : ", ")); +} +#endif /* MAKECRCH */ + +#else /* !DYNAMIC_CRC_TABLE */ +/* ======================================================================== + * Tables of CRC-32s of all single-byte values, made by make_crc_table(). + */ +#include "crc32.h" +#endif /* DYNAMIC_CRC_TABLE */ + +/* ========================================================================= + * This function can be used by asm versions of crc32() + */ +const unsigned long FAR * ZEXPORT get_crc_table() +{ +#ifdef DYNAMIC_CRC_TABLE + if (crc_table_empty) + make_crc_table(); +#endif /* DYNAMIC_CRC_TABLE */ + return (const unsigned long FAR *)crc_table; +} + +/* ========================================================================= */ +#define DO1 crc = crc_table[0][((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8) +#define DO8 DO1; DO1; DO1; DO1; DO1; DO1; DO1; DO1 + +/* ========================================================================= */ +unsigned long ZEXPORT crc32(crc, buf, len) + unsigned long crc; + const unsigned char FAR *buf; + unsigned len; +{ + if (buf == Z_NULL) return 0UL; + +#ifdef DYNAMIC_CRC_TABLE + if (crc_table_empty) + make_crc_table(); +#endif /* DYNAMIC_CRC_TABLE */ + +#ifdef BYFOUR + if (sizeof(void *) == sizeof(ptrdiff_t)) { + u4 endian; + + endian = 1; + if (*((unsigned char *)(&endian))) + return crc32_little(crc, buf, len); + else + return crc32_big(crc, buf, len); + } +#endif /* BYFOUR */ + crc = crc ^ 0xffffffffUL; + while (len >= 8) { + DO8; + len -= 8; + } + if (len) do { + DO1; + } while (--len); + return crc ^ 0xffffffffUL; +} + +#ifdef BYFOUR + +/* ========================================================================= */ +#define DOLIT4 c ^= *buf4++; \ + c = crc_table[3][c & 0xff] ^ crc_table[2][(c >> 8) & 0xff] ^ \ + crc_table[1][(c >> 16) & 0xff] ^ crc_table[0][c >> 24] +#define DOLIT32 DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4 + +/* ========================================================================= */ +local unsigned long crc32_little(crc, buf, len) + unsigned long crc; + const unsigned char FAR *buf; + unsigned len; +{ + register u4 c; + register const u4 FAR *buf4; + + c = (u4)crc; + c = ~c; + while (len && ((ptrdiff_t)buf & 3)) { + c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8); + len--; + } + + buf4 = (const u4 FAR *)(const void FAR *)buf; + while (len >= 32) { + DOLIT32; + len -= 32; + } + while (len >= 4) { + DOLIT4; + len -= 4; + } + buf = (const unsigned char FAR *)buf4; + + if (len) do { + c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8); + } while (--len); + c = ~c; + return (unsigned long)c; +} + +/* ========================================================================= */ +#define DOBIG4 c ^= *++buf4; \ + c = crc_table[4][c & 0xff] ^ crc_table[5][(c >> 8) & 0xff] ^ \ + crc_table[6][(c >> 16) & 0xff] ^ crc_table[7][c >> 24] +#define DOBIG32 DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4 + +/* ========================================================================= */ +local unsigned long crc32_big(crc, buf, len) + unsigned long crc; + const unsigned char FAR *buf; + unsigned len; +{ + register u4 c; + register const u4 FAR *buf4; + + c = REV((u4)crc); + c = ~c; + while (len && ((ptrdiff_t)buf & 3)) { + c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8); + len--; + } + + buf4 = (const u4 FAR *)(const void FAR *)buf; + buf4--; + while (len >= 32) { + DOBIG32; + len -= 32; + } + while (len >= 4) { + DOBIG4; + len -= 4; + } + buf4++; + buf = (const unsigned char FAR *)buf4; + + if (len) do { + c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8); + } while (--len); + c = ~c; + return (unsigned long)(REV(c)); +} + +#endif /* BYFOUR */ + +#define GF2_DIM 32 /* dimension of GF(2) vectors (length of CRC) */ + +/* ========================================================================= */ +local unsigned long gf2_matrix_times(mat, vec) + unsigned long *mat; + unsigned long vec; +{ + unsigned long sum; + + sum = 0; + while (vec) { + if (vec & 1) + sum ^= *mat; + vec >>= 1; + mat++; + } + return sum; +} + +/* ========================================================================= */ +local void gf2_matrix_square(square, mat) + unsigned long *square; + unsigned long *mat; +{ + int n; + + for (n = 0; n < GF2_DIM; n++) + square[n] = gf2_matrix_times(mat, mat[n]); +} + +/* ========================================================================= */ +uLong ZEXPORT crc32_combine(crc1, crc2, len2) + uLong crc1; + uLong crc2; + z_off_t len2; +{ + int n; + unsigned long row; + unsigned long even[GF2_DIM]; /* even-power-of-two zeros operator */ + unsigned long odd[GF2_DIM]; /* odd-power-of-two zeros operator */ + + /* degenerate case */ + if (len2 == 0) + return crc1; + + /* put operator for one zero bit in odd */ + odd[0] = 0xedb88320L; /* CRC-32 polynomial */ + row = 1; + for (n = 1; n < GF2_DIM; n++) { + odd[n] = row; + row <<= 1; + } + + /* put operator for two zero bits in even */ + gf2_matrix_square(even, odd); + + /* put operator for four zero bits in odd */ + gf2_matrix_square(odd, even); + + /* apply len2 zeros to crc1 (first square will put the operator for one + zero byte, eight zero bits, in even) */ + do { + /* apply zeros operator for this bit of len2 */ + gf2_matrix_square(even, odd); + if (len2 & 1) + crc1 = gf2_matrix_times(even, crc1); + len2 >>= 1; + + /* if no more bits set, then done */ + if (len2 == 0) + break; + + /* another iteration of the loop with odd and even swapped */ + gf2_matrix_square(odd, even); + if (len2 & 1) + crc1 = gf2_matrix_times(odd, crc1); + len2 >>= 1; + + /* if no more bits set, then done */ + } while (len2 != 0); + + /* return combined crc */ + crc1 ^= crc2; + return crc1; +} diff --git a/Foundation/src/crc32.h b/Foundation/src/crc32.h index 5de49bc97..8053b6117 100644 --- a/Foundation/src/crc32.h +++ b/Foundation/src/crc32.h @@ -1,441 +1,441 @@ -/* crc32.h -- tables for rapid CRC calculation - * Generated automatically by crc32.c - */ - -local const unsigned long FAR crc_table[TBLS][256] = -{ - { - 0x00000000UL, 0x77073096UL, 0xee0e612cUL, 0x990951baUL, 0x076dc419UL, - 0x706af48fUL, 0xe963a535UL, 0x9e6495a3UL, 0x0edb8832UL, 0x79dcb8a4UL, - 0xe0d5e91eUL, 0x97d2d988UL, 0x09b64c2bUL, 0x7eb17cbdUL, 0xe7b82d07UL, - 0x90bf1d91UL, 0x1db71064UL, 0x6ab020f2UL, 0xf3b97148UL, 0x84be41deUL, - 0x1adad47dUL, 0x6ddde4ebUL, 0xf4d4b551UL, 0x83d385c7UL, 0x136c9856UL, - 0x646ba8c0UL, 0xfd62f97aUL, 0x8a65c9ecUL, 0x14015c4fUL, 0x63066cd9UL, - 0xfa0f3d63UL, 0x8d080df5UL, 0x3b6e20c8UL, 0x4c69105eUL, 0xd56041e4UL, - 0xa2677172UL, 0x3c03e4d1UL, 0x4b04d447UL, 0xd20d85fdUL, 0xa50ab56bUL, - 0x35b5a8faUL, 0x42b2986cUL, 0xdbbbc9d6UL, 0xacbcf940UL, 0x32d86ce3UL, - 0x45df5c75UL, 0xdcd60dcfUL, 0xabd13d59UL, 0x26d930acUL, 0x51de003aUL, - 0xc8d75180UL, 0xbfd06116UL, 0x21b4f4b5UL, 0x56b3c423UL, 0xcfba9599UL, - 0xb8bda50fUL, 0x2802b89eUL, 0x5f058808UL, 0xc60cd9b2UL, 0xb10be924UL, - 0x2f6f7c87UL, 0x58684c11UL, 0xc1611dabUL, 0xb6662d3dUL, 0x76dc4190UL, - 0x01db7106UL, 0x98d220bcUL, 0xefd5102aUL, 0x71b18589UL, 0x06b6b51fUL, - 0x9fbfe4a5UL, 0xe8b8d433UL, 0x7807c9a2UL, 0x0f00f934UL, 0x9609a88eUL, - 0xe10e9818UL, 0x7f6a0dbbUL, 0x086d3d2dUL, 0x91646c97UL, 0xe6635c01UL, - 0x6b6b51f4UL, 0x1c6c6162UL, 0x856530d8UL, 0xf262004eUL, 0x6c0695edUL, - 0x1b01a57bUL, 0x8208f4c1UL, 0xf50fc457UL, 0x65b0d9c6UL, 0x12b7e950UL, - 0x8bbeb8eaUL, 0xfcb9887cUL, 0x62dd1ddfUL, 0x15da2d49UL, 0x8cd37cf3UL, - 0xfbd44c65UL, 0x4db26158UL, 0x3ab551ceUL, 0xa3bc0074UL, 0xd4bb30e2UL, - 0x4adfa541UL, 0x3dd895d7UL, 0xa4d1c46dUL, 0xd3d6f4fbUL, 0x4369e96aUL, - 0x346ed9fcUL, 0xad678846UL, 0xda60b8d0UL, 0x44042d73UL, 0x33031de5UL, - 0xaa0a4c5fUL, 0xdd0d7cc9UL, 0x5005713cUL, 0x270241aaUL, 0xbe0b1010UL, - 0xc90c2086UL, 0x5768b525UL, 0x206f85b3UL, 0xb966d409UL, 0xce61e49fUL, - 0x5edef90eUL, 0x29d9c998UL, 0xb0d09822UL, 0xc7d7a8b4UL, 0x59b33d17UL, - 0x2eb40d81UL, 0xb7bd5c3bUL, 0xc0ba6cadUL, 0xedb88320UL, 0x9abfb3b6UL, - 0x03b6e20cUL, 0x74b1d29aUL, 0xead54739UL, 0x9dd277afUL, 0x04db2615UL, - 0x73dc1683UL, 0xe3630b12UL, 0x94643b84UL, 0x0d6d6a3eUL, 0x7a6a5aa8UL, - 0xe40ecf0bUL, 0x9309ff9dUL, 0x0a00ae27UL, 0x7d079eb1UL, 0xf00f9344UL, - 0x8708a3d2UL, 0x1e01f268UL, 0x6906c2feUL, 0xf762575dUL, 0x806567cbUL, - 0x196c3671UL, 0x6e6b06e7UL, 0xfed41b76UL, 0x89d32be0UL, 0x10da7a5aUL, - 0x67dd4accUL, 0xf9b9df6fUL, 0x8ebeeff9UL, 0x17b7be43UL, 0x60b08ed5UL, - 0xd6d6a3e8UL, 0xa1d1937eUL, 0x38d8c2c4UL, 0x4fdff252UL, 0xd1bb67f1UL, - 0xa6bc5767UL, 0x3fb506ddUL, 0x48b2364bUL, 0xd80d2bdaUL, 0xaf0a1b4cUL, - 0x36034af6UL, 0x41047a60UL, 0xdf60efc3UL, 0xa867df55UL, 0x316e8eefUL, - 0x4669be79UL, 0xcb61b38cUL, 0xbc66831aUL, 0x256fd2a0UL, 0x5268e236UL, - 0xcc0c7795UL, 0xbb0b4703UL, 0x220216b9UL, 0x5505262fUL, 0xc5ba3bbeUL, - 0xb2bd0b28UL, 0x2bb45a92UL, 0x5cb36a04UL, 0xc2d7ffa7UL, 0xb5d0cf31UL, - 0x2cd99e8bUL, 0x5bdeae1dUL, 0x9b64c2b0UL, 0xec63f226UL, 0x756aa39cUL, - 0x026d930aUL, 0x9c0906a9UL, 0xeb0e363fUL, 0x72076785UL, 0x05005713UL, - 0x95bf4a82UL, 0xe2b87a14UL, 0x7bb12baeUL, 0x0cb61b38UL, 0x92d28e9bUL, - 0xe5d5be0dUL, 0x7cdcefb7UL, 0x0bdbdf21UL, 0x86d3d2d4UL, 0xf1d4e242UL, - 0x68ddb3f8UL, 0x1fda836eUL, 0x81be16cdUL, 0xf6b9265bUL, 0x6fb077e1UL, - 0x18b74777UL, 0x88085ae6UL, 0xff0f6a70UL, 0x66063bcaUL, 0x11010b5cUL, - 0x8f659effUL, 0xf862ae69UL, 0x616bffd3UL, 0x166ccf45UL, 0xa00ae278UL, - 0xd70dd2eeUL, 0x4e048354UL, 0x3903b3c2UL, 0xa7672661UL, 0xd06016f7UL, - 0x4969474dUL, 0x3e6e77dbUL, 0xaed16a4aUL, 0xd9d65adcUL, 0x40df0b66UL, - 0x37d83bf0UL, 0xa9bcae53UL, 0xdebb9ec5UL, 0x47b2cf7fUL, 0x30b5ffe9UL, - 0xbdbdf21cUL, 0xcabac28aUL, 0x53b39330UL, 0x24b4a3a6UL, 0xbad03605UL, - 0xcdd70693UL, 0x54de5729UL, 0x23d967bfUL, 0xb3667a2eUL, 0xc4614ab8UL, - 0x5d681b02UL, 0x2a6f2b94UL, 0xb40bbe37UL, 0xc30c8ea1UL, 0x5a05df1bUL, - 0x2d02ef8dUL -#ifdef BYFOUR - }, - { - 0x00000000UL, 0x191b3141UL, 0x32366282UL, 0x2b2d53c3UL, 0x646cc504UL, - 0x7d77f445UL, 0x565aa786UL, 0x4f4196c7UL, 0xc8d98a08UL, 0xd1c2bb49UL, - 0xfaefe88aUL, 0xe3f4d9cbUL, 0xacb54f0cUL, 0xb5ae7e4dUL, 0x9e832d8eUL, - 0x87981ccfUL, 0x4ac21251UL, 0x53d92310UL, 0x78f470d3UL, 0x61ef4192UL, - 0x2eaed755UL, 0x37b5e614UL, 0x1c98b5d7UL, 0x05838496UL, 0x821b9859UL, - 0x9b00a918UL, 0xb02dfadbUL, 0xa936cb9aUL, 0xe6775d5dUL, 0xff6c6c1cUL, - 0xd4413fdfUL, 0xcd5a0e9eUL, 0x958424a2UL, 0x8c9f15e3UL, 0xa7b24620UL, - 0xbea97761UL, 0xf1e8e1a6UL, 0xe8f3d0e7UL, 0xc3de8324UL, 0xdac5b265UL, - 0x5d5daeaaUL, 0x44469febUL, 0x6f6bcc28UL, 0x7670fd69UL, 0x39316baeUL, - 0x202a5aefUL, 0x0b07092cUL, 0x121c386dUL, 0xdf4636f3UL, 0xc65d07b2UL, - 0xed705471UL, 0xf46b6530UL, 0xbb2af3f7UL, 0xa231c2b6UL, 0x891c9175UL, - 0x9007a034UL, 0x179fbcfbUL, 0x0e848dbaUL, 0x25a9de79UL, 0x3cb2ef38UL, - 0x73f379ffUL, 0x6ae848beUL, 0x41c51b7dUL, 0x58de2a3cUL, 0xf0794f05UL, - 0xe9627e44UL, 0xc24f2d87UL, 0xdb541cc6UL, 0x94158a01UL, 0x8d0ebb40UL, - 0xa623e883UL, 0xbf38d9c2UL, 0x38a0c50dUL, 0x21bbf44cUL, 0x0a96a78fUL, - 0x138d96ceUL, 0x5ccc0009UL, 0x45d73148UL, 0x6efa628bUL, 0x77e153caUL, - 0xbabb5d54UL, 0xa3a06c15UL, 0x888d3fd6UL, 0x91960e97UL, 0xded79850UL, - 0xc7cca911UL, 0xece1fad2UL, 0xf5facb93UL, 0x7262d75cUL, 0x6b79e61dUL, - 0x4054b5deUL, 0x594f849fUL, 0x160e1258UL, 0x0f152319UL, 0x243870daUL, - 0x3d23419bUL, 0x65fd6ba7UL, 0x7ce65ae6UL, 0x57cb0925UL, 0x4ed03864UL, - 0x0191aea3UL, 0x188a9fe2UL, 0x33a7cc21UL, 0x2abcfd60UL, 0xad24e1afUL, - 0xb43fd0eeUL, 0x9f12832dUL, 0x8609b26cUL, 0xc94824abUL, 0xd05315eaUL, - 0xfb7e4629UL, 0xe2657768UL, 0x2f3f79f6UL, 0x362448b7UL, 0x1d091b74UL, - 0x04122a35UL, 0x4b53bcf2UL, 0x52488db3UL, 0x7965de70UL, 0x607eef31UL, - 0xe7e6f3feUL, 0xfefdc2bfUL, 0xd5d0917cUL, 0xcccba03dUL, 0x838a36faUL, - 0x9a9107bbUL, 0xb1bc5478UL, 0xa8a76539UL, 0x3b83984bUL, 0x2298a90aUL, - 0x09b5fac9UL, 0x10aecb88UL, 0x5fef5d4fUL, 0x46f46c0eUL, 0x6dd93fcdUL, - 0x74c20e8cUL, 0xf35a1243UL, 0xea412302UL, 0xc16c70c1UL, 0xd8774180UL, - 0x9736d747UL, 0x8e2de606UL, 0xa500b5c5UL, 0xbc1b8484UL, 0x71418a1aUL, - 0x685abb5bUL, 0x4377e898UL, 0x5a6cd9d9UL, 0x152d4f1eUL, 0x0c367e5fUL, - 0x271b2d9cUL, 0x3e001cddUL, 0xb9980012UL, 0xa0833153UL, 0x8bae6290UL, - 0x92b553d1UL, 0xddf4c516UL, 0xc4eff457UL, 0xefc2a794UL, 0xf6d996d5UL, - 0xae07bce9UL, 0xb71c8da8UL, 0x9c31de6bUL, 0x852aef2aUL, 0xca6b79edUL, - 0xd37048acUL, 0xf85d1b6fUL, 0xe1462a2eUL, 0x66de36e1UL, 0x7fc507a0UL, - 0x54e85463UL, 0x4df36522UL, 0x02b2f3e5UL, 0x1ba9c2a4UL, 0x30849167UL, - 0x299fa026UL, 0xe4c5aeb8UL, 0xfdde9ff9UL, 0xd6f3cc3aUL, 0xcfe8fd7bUL, - 0x80a96bbcUL, 0x99b25afdUL, 0xb29f093eUL, 0xab84387fUL, 0x2c1c24b0UL, - 0x350715f1UL, 0x1e2a4632UL, 0x07317773UL, 0x4870e1b4UL, 0x516bd0f5UL, - 0x7a468336UL, 0x635db277UL, 0xcbfad74eUL, 0xd2e1e60fUL, 0xf9ccb5ccUL, - 0xe0d7848dUL, 0xaf96124aUL, 0xb68d230bUL, 0x9da070c8UL, 0x84bb4189UL, - 0x03235d46UL, 0x1a386c07UL, 0x31153fc4UL, 0x280e0e85UL, 0x674f9842UL, - 0x7e54a903UL, 0x5579fac0UL, 0x4c62cb81UL, 0x8138c51fUL, 0x9823f45eUL, - 0xb30ea79dUL, 0xaa1596dcUL, 0xe554001bUL, 0xfc4f315aUL, 0xd7626299UL, - 0xce7953d8UL, 0x49e14f17UL, 0x50fa7e56UL, 0x7bd72d95UL, 0x62cc1cd4UL, - 0x2d8d8a13UL, 0x3496bb52UL, 0x1fbbe891UL, 0x06a0d9d0UL, 0x5e7ef3ecUL, - 0x4765c2adUL, 0x6c48916eUL, 0x7553a02fUL, 0x3a1236e8UL, 0x230907a9UL, - 0x0824546aUL, 0x113f652bUL, 0x96a779e4UL, 0x8fbc48a5UL, 0xa4911b66UL, - 0xbd8a2a27UL, 0xf2cbbce0UL, 0xebd08da1UL, 0xc0fdde62UL, 0xd9e6ef23UL, - 0x14bce1bdUL, 0x0da7d0fcUL, 0x268a833fUL, 0x3f91b27eUL, 0x70d024b9UL, - 0x69cb15f8UL, 0x42e6463bUL, 0x5bfd777aUL, 0xdc656bb5UL, 0xc57e5af4UL, - 0xee530937UL, 0xf7483876UL, 0xb809aeb1UL, 0xa1129ff0UL, 0x8a3fcc33UL, - 0x9324fd72UL - }, - { - 0x00000000UL, 0x01c26a37UL, 0x0384d46eUL, 0x0246be59UL, 0x0709a8dcUL, - 0x06cbc2ebUL, 0x048d7cb2UL, 0x054f1685UL, 0x0e1351b8UL, 0x0fd13b8fUL, - 0x0d9785d6UL, 0x0c55efe1UL, 0x091af964UL, 0x08d89353UL, 0x0a9e2d0aUL, - 0x0b5c473dUL, 0x1c26a370UL, 0x1de4c947UL, 0x1fa2771eUL, 0x1e601d29UL, - 0x1b2f0bacUL, 0x1aed619bUL, 0x18abdfc2UL, 0x1969b5f5UL, 0x1235f2c8UL, - 0x13f798ffUL, 0x11b126a6UL, 0x10734c91UL, 0x153c5a14UL, 0x14fe3023UL, - 0x16b88e7aUL, 0x177ae44dUL, 0x384d46e0UL, 0x398f2cd7UL, 0x3bc9928eUL, - 0x3a0bf8b9UL, 0x3f44ee3cUL, 0x3e86840bUL, 0x3cc03a52UL, 0x3d025065UL, - 0x365e1758UL, 0x379c7d6fUL, 0x35dac336UL, 0x3418a901UL, 0x3157bf84UL, - 0x3095d5b3UL, 0x32d36beaUL, 0x331101ddUL, 0x246be590UL, 0x25a98fa7UL, - 0x27ef31feUL, 0x262d5bc9UL, 0x23624d4cUL, 0x22a0277bUL, 0x20e69922UL, - 0x2124f315UL, 0x2a78b428UL, 0x2bbade1fUL, 0x29fc6046UL, 0x283e0a71UL, - 0x2d711cf4UL, 0x2cb376c3UL, 0x2ef5c89aUL, 0x2f37a2adUL, 0x709a8dc0UL, - 0x7158e7f7UL, 0x731e59aeUL, 0x72dc3399UL, 0x7793251cUL, 0x76514f2bUL, - 0x7417f172UL, 0x75d59b45UL, 0x7e89dc78UL, 0x7f4bb64fUL, 0x7d0d0816UL, - 0x7ccf6221UL, 0x798074a4UL, 0x78421e93UL, 0x7a04a0caUL, 0x7bc6cafdUL, - 0x6cbc2eb0UL, 0x6d7e4487UL, 0x6f38fadeUL, 0x6efa90e9UL, 0x6bb5866cUL, - 0x6a77ec5bUL, 0x68315202UL, 0x69f33835UL, 0x62af7f08UL, 0x636d153fUL, - 0x612bab66UL, 0x60e9c151UL, 0x65a6d7d4UL, 0x6464bde3UL, 0x662203baUL, - 0x67e0698dUL, 0x48d7cb20UL, 0x4915a117UL, 0x4b531f4eUL, 0x4a917579UL, - 0x4fde63fcUL, 0x4e1c09cbUL, 0x4c5ab792UL, 0x4d98dda5UL, 0x46c49a98UL, - 0x4706f0afUL, 0x45404ef6UL, 0x448224c1UL, 0x41cd3244UL, 0x400f5873UL, - 0x4249e62aUL, 0x438b8c1dUL, 0x54f16850UL, 0x55330267UL, 0x5775bc3eUL, - 0x56b7d609UL, 0x53f8c08cUL, 0x523aaabbUL, 0x507c14e2UL, 0x51be7ed5UL, - 0x5ae239e8UL, 0x5b2053dfUL, 0x5966ed86UL, 0x58a487b1UL, 0x5deb9134UL, - 0x5c29fb03UL, 0x5e6f455aUL, 0x5fad2f6dUL, 0xe1351b80UL, 0xe0f771b7UL, - 0xe2b1cfeeUL, 0xe373a5d9UL, 0xe63cb35cUL, 0xe7fed96bUL, 0xe5b86732UL, - 0xe47a0d05UL, 0xef264a38UL, 0xeee4200fUL, 0xeca29e56UL, 0xed60f461UL, - 0xe82fe2e4UL, 0xe9ed88d3UL, 0xebab368aUL, 0xea695cbdUL, 0xfd13b8f0UL, - 0xfcd1d2c7UL, 0xfe976c9eUL, 0xff5506a9UL, 0xfa1a102cUL, 0xfbd87a1bUL, - 0xf99ec442UL, 0xf85cae75UL, 0xf300e948UL, 0xf2c2837fUL, 0xf0843d26UL, - 0xf1465711UL, 0xf4094194UL, 0xf5cb2ba3UL, 0xf78d95faUL, 0xf64fffcdUL, - 0xd9785d60UL, 0xd8ba3757UL, 0xdafc890eUL, 0xdb3ee339UL, 0xde71f5bcUL, - 0xdfb39f8bUL, 0xddf521d2UL, 0xdc374be5UL, 0xd76b0cd8UL, 0xd6a966efUL, - 0xd4efd8b6UL, 0xd52db281UL, 0xd062a404UL, 0xd1a0ce33UL, 0xd3e6706aUL, - 0xd2241a5dUL, 0xc55efe10UL, 0xc49c9427UL, 0xc6da2a7eUL, 0xc7184049UL, - 0xc25756ccUL, 0xc3953cfbUL, 0xc1d382a2UL, 0xc011e895UL, 0xcb4dafa8UL, - 0xca8fc59fUL, 0xc8c97bc6UL, 0xc90b11f1UL, 0xcc440774UL, 0xcd866d43UL, - 0xcfc0d31aUL, 0xce02b92dUL, 0x91af9640UL, 0x906dfc77UL, 0x922b422eUL, - 0x93e92819UL, 0x96a63e9cUL, 0x976454abUL, 0x9522eaf2UL, 0x94e080c5UL, - 0x9fbcc7f8UL, 0x9e7eadcfUL, 0x9c381396UL, 0x9dfa79a1UL, 0x98b56f24UL, - 0x99770513UL, 0x9b31bb4aUL, 0x9af3d17dUL, 0x8d893530UL, 0x8c4b5f07UL, - 0x8e0de15eUL, 0x8fcf8b69UL, 0x8a809decUL, 0x8b42f7dbUL, 0x89044982UL, - 0x88c623b5UL, 0x839a6488UL, 0x82580ebfUL, 0x801eb0e6UL, 0x81dcdad1UL, - 0x8493cc54UL, 0x8551a663UL, 0x8717183aUL, 0x86d5720dUL, 0xa9e2d0a0UL, - 0xa820ba97UL, 0xaa6604ceUL, 0xaba46ef9UL, 0xaeeb787cUL, 0xaf29124bUL, - 0xad6fac12UL, 0xacadc625UL, 0xa7f18118UL, 0xa633eb2fUL, 0xa4755576UL, - 0xa5b73f41UL, 0xa0f829c4UL, 0xa13a43f3UL, 0xa37cfdaaUL, 0xa2be979dUL, - 0xb5c473d0UL, 0xb40619e7UL, 0xb640a7beUL, 0xb782cd89UL, 0xb2cddb0cUL, - 0xb30fb13bUL, 0xb1490f62UL, 0xb08b6555UL, 0xbbd72268UL, 0xba15485fUL, - 0xb853f606UL, 0xb9919c31UL, 0xbcde8ab4UL, 0xbd1ce083UL, 0xbf5a5edaUL, - 0xbe9834edUL - }, - { - 0x00000000UL, 0xb8bc6765UL, 0xaa09c88bUL, 0x12b5afeeUL, 0x8f629757UL, - 0x37def032UL, 0x256b5fdcUL, 0x9dd738b9UL, 0xc5b428efUL, 0x7d084f8aUL, - 0x6fbde064UL, 0xd7018701UL, 0x4ad6bfb8UL, 0xf26ad8ddUL, 0xe0df7733UL, - 0x58631056UL, 0x5019579fUL, 0xe8a530faUL, 0xfa109f14UL, 0x42acf871UL, - 0xdf7bc0c8UL, 0x67c7a7adUL, 0x75720843UL, 0xcdce6f26UL, 0x95ad7f70UL, - 0x2d111815UL, 0x3fa4b7fbUL, 0x8718d09eUL, 0x1acfe827UL, 0xa2738f42UL, - 0xb0c620acUL, 0x087a47c9UL, 0xa032af3eUL, 0x188ec85bUL, 0x0a3b67b5UL, - 0xb28700d0UL, 0x2f503869UL, 0x97ec5f0cUL, 0x8559f0e2UL, 0x3de59787UL, - 0x658687d1UL, 0xdd3ae0b4UL, 0xcf8f4f5aUL, 0x7733283fUL, 0xeae41086UL, - 0x525877e3UL, 0x40edd80dUL, 0xf851bf68UL, 0xf02bf8a1UL, 0x48979fc4UL, - 0x5a22302aUL, 0xe29e574fUL, 0x7f496ff6UL, 0xc7f50893UL, 0xd540a77dUL, - 0x6dfcc018UL, 0x359fd04eUL, 0x8d23b72bUL, 0x9f9618c5UL, 0x272a7fa0UL, - 0xbafd4719UL, 0x0241207cUL, 0x10f48f92UL, 0xa848e8f7UL, 0x9b14583dUL, - 0x23a83f58UL, 0x311d90b6UL, 0x89a1f7d3UL, 0x1476cf6aUL, 0xaccaa80fUL, - 0xbe7f07e1UL, 0x06c36084UL, 0x5ea070d2UL, 0xe61c17b7UL, 0xf4a9b859UL, - 0x4c15df3cUL, 0xd1c2e785UL, 0x697e80e0UL, 0x7bcb2f0eUL, 0xc377486bUL, - 0xcb0d0fa2UL, 0x73b168c7UL, 0x6104c729UL, 0xd9b8a04cUL, 0x446f98f5UL, - 0xfcd3ff90UL, 0xee66507eUL, 0x56da371bUL, 0x0eb9274dUL, 0xb6054028UL, - 0xa4b0efc6UL, 0x1c0c88a3UL, 0x81dbb01aUL, 0x3967d77fUL, 0x2bd27891UL, - 0x936e1ff4UL, 0x3b26f703UL, 0x839a9066UL, 0x912f3f88UL, 0x299358edUL, - 0xb4446054UL, 0x0cf80731UL, 0x1e4da8dfUL, 0xa6f1cfbaUL, 0xfe92dfecUL, - 0x462eb889UL, 0x549b1767UL, 0xec277002UL, 0x71f048bbUL, 0xc94c2fdeUL, - 0xdbf98030UL, 0x6345e755UL, 0x6b3fa09cUL, 0xd383c7f9UL, 0xc1366817UL, - 0x798a0f72UL, 0xe45d37cbUL, 0x5ce150aeUL, 0x4e54ff40UL, 0xf6e89825UL, - 0xae8b8873UL, 0x1637ef16UL, 0x048240f8UL, 0xbc3e279dUL, 0x21e91f24UL, - 0x99557841UL, 0x8be0d7afUL, 0x335cb0caUL, 0xed59b63bUL, 0x55e5d15eUL, - 0x47507eb0UL, 0xffec19d5UL, 0x623b216cUL, 0xda874609UL, 0xc832e9e7UL, - 0x708e8e82UL, 0x28ed9ed4UL, 0x9051f9b1UL, 0x82e4565fUL, 0x3a58313aUL, - 0xa78f0983UL, 0x1f336ee6UL, 0x0d86c108UL, 0xb53aa66dUL, 0xbd40e1a4UL, - 0x05fc86c1UL, 0x1749292fUL, 0xaff54e4aUL, 0x322276f3UL, 0x8a9e1196UL, - 0x982bbe78UL, 0x2097d91dUL, 0x78f4c94bUL, 0xc048ae2eUL, 0xd2fd01c0UL, - 0x6a4166a5UL, 0xf7965e1cUL, 0x4f2a3979UL, 0x5d9f9697UL, 0xe523f1f2UL, - 0x4d6b1905UL, 0xf5d77e60UL, 0xe762d18eUL, 0x5fdeb6ebUL, 0xc2098e52UL, - 0x7ab5e937UL, 0x680046d9UL, 0xd0bc21bcUL, 0x88df31eaUL, 0x3063568fUL, - 0x22d6f961UL, 0x9a6a9e04UL, 0x07bda6bdUL, 0xbf01c1d8UL, 0xadb46e36UL, - 0x15080953UL, 0x1d724e9aUL, 0xa5ce29ffUL, 0xb77b8611UL, 0x0fc7e174UL, - 0x9210d9cdUL, 0x2aacbea8UL, 0x38191146UL, 0x80a57623UL, 0xd8c66675UL, - 0x607a0110UL, 0x72cfaefeUL, 0xca73c99bUL, 0x57a4f122UL, 0xef189647UL, - 0xfdad39a9UL, 0x45115eccUL, 0x764dee06UL, 0xcef18963UL, 0xdc44268dUL, - 0x64f841e8UL, 0xf92f7951UL, 0x41931e34UL, 0x5326b1daUL, 0xeb9ad6bfUL, - 0xb3f9c6e9UL, 0x0b45a18cUL, 0x19f00e62UL, 0xa14c6907UL, 0x3c9b51beUL, - 0x842736dbUL, 0x96929935UL, 0x2e2efe50UL, 0x2654b999UL, 0x9ee8defcUL, - 0x8c5d7112UL, 0x34e11677UL, 0xa9362eceUL, 0x118a49abUL, 0x033fe645UL, - 0xbb838120UL, 0xe3e09176UL, 0x5b5cf613UL, 0x49e959fdUL, 0xf1553e98UL, - 0x6c820621UL, 0xd43e6144UL, 0xc68bceaaUL, 0x7e37a9cfUL, 0xd67f4138UL, - 0x6ec3265dUL, 0x7c7689b3UL, 0xc4caeed6UL, 0x591dd66fUL, 0xe1a1b10aUL, - 0xf3141ee4UL, 0x4ba87981UL, 0x13cb69d7UL, 0xab770eb2UL, 0xb9c2a15cUL, - 0x017ec639UL, 0x9ca9fe80UL, 0x241599e5UL, 0x36a0360bUL, 0x8e1c516eUL, - 0x866616a7UL, 0x3eda71c2UL, 0x2c6fde2cUL, 0x94d3b949UL, 0x090481f0UL, - 0xb1b8e695UL, 0xa30d497bUL, 0x1bb12e1eUL, 0x43d23e48UL, 0xfb6e592dUL, - 0xe9dbf6c3UL, 0x516791a6UL, 0xccb0a91fUL, 0x740cce7aUL, 0x66b96194UL, - 0xde0506f1UL - }, - { - 0x00000000UL, 0x96300777UL, 0x2c610eeeUL, 0xba510999UL, 0x19c46d07UL, - 0x8ff46a70UL, 0x35a563e9UL, 0xa395649eUL, 0x3288db0eUL, 0xa4b8dc79UL, - 0x1ee9d5e0UL, 0x88d9d297UL, 0x2b4cb609UL, 0xbd7cb17eUL, 0x072db8e7UL, - 0x911dbf90UL, 0x6410b71dUL, 0xf220b06aUL, 0x4871b9f3UL, 0xde41be84UL, - 0x7dd4da1aUL, 0xebe4dd6dUL, 0x51b5d4f4UL, 0xc785d383UL, 0x56986c13UL, - 0xc0a86b64UL, 0x7af962fdUL, 0xecc9658aUL, 0x4f5c0114UL, 0xd96c0663UL, - 0x633d0ffaUL, 0xf50d088dUL, 0xc8206e3bUL, 0x5e10694cUL, 0xe44160d5UL, - 0x727167a2UL, 0xd1e4033cUL, 0x47d4044bUL, 0xfd850dd2UL, 0x6bb50aa5UL, - 0xfaa8b535UL, 0x6c98b242UL, 0xd6c9bbdbUL, 0x40f9bcacUL, 0xe36cd832UL, - 0x755cdf45UL, 0xcf0dd6dcUL, 0x593dd1abUL, 0xac30d926UL, 0x3a00de51UL, - 0x8051d7c8UL, 0x1661d0bfUL, 0xb5f4b421UL, 0x23c4b356UL, 0x9995bacfUL, - 0x0fa5bdb8UL, 0x9eb80228UL, 0x0888055fUL, 0xb2d90cc6UL, 0x24e90bb1UL, - 0x877c6f2fUL, 0x114c6858UL, 0xab1d61c1UL, 0x3d2d66b6UL, 0x9041dc76UL, - 0x0671db01UL, 0xbc20d298UL, 0x2a10d5efUL, 0x8985b171UL, 0x1fb5b606UL, - 0xa5e4bf9fUL, 0x33d4b8e8UL, 0xa2c90778UL, 0x34f9000fUL, 0x8ea80996UL, - 0x18980ee1UL, 0xbb0d6a7fUL, 0x2d3d6d08UL, 0x976c6491UL, 0x015c63e6UL, - 0xf4516b6bUL, 0x62616c1cUL, 0xd8306585UL, 0x4e0062f2UL, 0xed95066cUL, - 0x7ba5011bUL, 0xc1f40882UL, 0x57c40ff5UL, 0xc6d9b065UL, 0x50e9b712UL, - 0xeab8be8bUL, 0x7c88b9fcUL, 0xdf1ddd62UL, 0x492dda15UL, 0xf37cd38cUL, - 0x654cd4fbUL, 0x5861b24dUL, 0xce51b53aUL, 0x7400bca3UL, 0xe230bbd4UL, - 0x41a5df4aUL, 0xd795d83dUL, 0x6dc4d1a4UL, 0xfbf4d6d3UL, 0x6ae96943UL, - 0xfcd96e34UL, 0x468867adUL, 0xd0b860daUL, 0x732d0444UL, 0xe51d0333UL, - 0x5f4c0aaaUL, 0xc97c0dddUL, 0x3c710550UL, 0xaa410227UL, 0x10100bbeUL, - 0x86200cc9UL, 0x25b56857UL, 0xb3856f20UL, 0x09d466b9UL, 0x9fe461ceUL, - 0x0ef9de5eUL, 0x98c9d929UL, 0x2298d0b0UL, 0xb4a8d7c7UL, 0x173db359UL, - 0x810db42eUL, 0x3b5cbdb7UL, 0xad6cbac0UL, 0x2083b8edUL, 0xb6b3bf9aUL, - 0x0ce2b603UL, 0x9ad2b174UL, 0x3947d5eaUL, 0xaf77d29dUL, 0x1526db04UL, - 0x8316dc73UL, 0x120b63e3UL, 0x843b6494UL, 0x3e6a6d0dUL, 0xa85a6a7aUL, - 0x0bcf0ee4UL, 0x9dff0993UL, 0x27ae000aUL, 0xb19e077dUL, 0x44930ff0UL, - 0xd2a30887UL, 0x68f2011eUL, 0xfec20669UL, 0x5d5762f7UL, 0xcb676580UL, - 0x71366c19UL, 0xe7066b6eUL, 0x761bd4feUL, 0xe02bd389UL, 0x5a7ada10UL, - 0xcc4add67UL, 0x6fdfb9f9UL, 0xf9efbe8eUL, 0x43beb717UL, 0xd58eb060UL, - 0xe8a3d6d6UL, 0x7e93d1a1UL, 0xc4c2d838UL, 0x52f2df4fUL, 0xf167bbd1UL, - 0x6757bca6UL, 0xdd06b53fUL, 0x4b36b248UL, 0xda2b0dd8UL, 0x4c1b0aafUL, - 0xf64a0336UL, 0x607a0441UL, 0xc3ef60dfUL, 0x55df67a8UL, 0xef8e6e31UL, - 0x79be6946UL, 0x8cb361cbUL, 0x1a8366bcUL, 0xa0d26f25UL, 0x36e26852UL, - 0x95770cccUL, 0x03470bbbUL, 0xb9160222UL, 0x2f260555UL, 0xbe3bbac5UL, - 0x280bbdb2UL, 0x925ab42bUL, 0x046ab35cUL, 0xa7ffd7c2UL, 0x31cfd0b5UL, - 0x8b9ed92cUL, 0x1daede5bUL, 0xb0c2649bUL, 0x26f263ecUL, 0x9ca36a75UL, - 0x0a936d02UL, 0xa906099cUL, 0x3f360eebUL, 0x85670772UL, 0x13570005UL, - 0x824abf95UL, 0x147ab8e2UL, 0xae2bb17bUL, 0x381bb60cUL, 0x9b8ed292UL, - 0x0dbed5e5UL, 0xb7efdc7cUL, 0x21dfdb0bUL, 0xd4d2d386UL, 0x42e2d4f1UL, - 0xf8b3dd68UL, 0x6e83da1fUL, 0xcd16be81UL, 0x5b26b9f6UL, 0xe177b06fUL, - 0x7747b718UL, 0xe65a0888UL, 0x706a0fffUL, 0xca3b0666UL, 0x5c0b0111UL, - 0xff9e658fUL, 0x69ae62f8UL, 0xd3ff6b61UL, 0x45cf6c16UL, 0x78e20aa0UL, - 0xeed20dd7UL, 0x5483044eUL, 0xc2b30339UL, 0x612667a7UL, 0xf71660d0UL, - 0x4d476949UL, 0xdb776e3eUL, 0x4a6ad1aeUL, 0xdc5ad6d9UL, 0x660bdf40UL, - 0xf03bd837UL, 0x53aebca9UL, 0xc59ebbdeUL, 0x7fcfb247UL, 0xe9ffb530UL, - 0x1cf2bdbdUL, 0x8ac2bacaUL, 0x3093b353UL, 0xa6a3b424UL, 0x0536d0baUL, - 0x9306d7cdUL, 0x2957de54UL, 0xbf67d923UL, 0x2e7a66b3UL, 0xb84a61c4UL, - 0x021b685dUL, 0x942b6f2aUL, 0x37be0bb4UL, 0xa18e0cc3UL, 0x1bdf055aUL, - 0x8def022dUL - }, - { - 0x00000000UL, 0x41311b19UL, 0x82623632UL, 0xc3532d2bUL, 0x04c56c64UL, - 0x45f4777dUL, 0x86a75a56UL, 0xc796414fUL, 0x088ad9c8UL, 0x49bbc2d1UL, - 0x8ae8effaUL, 0xcbd9f4e3UL, 0x0c4fb5acUL, 0x4d7eaeb5UL, 0x8e2d839eUL, - 0xcf1c9887UL, 0x5112c24aUL, 0x1023d953UL, 0xd370f478UL, 0x9241ef61UL, - 0x55d7ae2eUL, 0x14e6b537UL, 0xd7b5981cUL, 0x96848305UL, 0x59981b82UL, - 0x18a9009bUL, 0xdbfa2db0UL, 0x9acb36a9UL, 0x5d5d77e6UL, 0x1c6c6cffUL, - 0xdf3f41d4UL, 0x9e0e5acdUL, 0xa2248495UL, 0xe3159f8cUL, 0x2046b2a7UL, - 0x6177a9beUL, 0xa6e1e8f1UL, 0xe7d0f3e8UL, 0x2483dec3UL, 0x65b2c5daUL, - 0xaaae5d5dUL, 0xeb9f4644UL, 0x28cc6b6fUL, 0x69fd7076UL, 0xae6b3139UL, - 0xef5a2a20UL, 0x2c09070bUL, 0x6d381c12UL, 0xf33646dfUL, 0xb2075dc6UL, - 0x715470edUL, 0x30656bf4UL, 0xf7f32abbUL, 0xb6c231a2UL, 0x75911c89UL, - 0x34a00790UL, 0xfbbc9f17UL, 0xba8d840eUL, 0x79dea925UL, 0x38efb23cUL, - 0xff79f373UL, 0xbe48e86aUL, 0x7d1bc541UL, 0x3c2ade58UL, 0x054f79f0UL, - 0x447e62e9UL, 0x872d4fc2UL, 0xc61c54dbUL, 0x018a1594UL, 0x40bb0e8dUL, - 0x83e823a6UL, 0xc2d938bfUL, 0x0dc5a038UL, 0x4cf4bb21UL, 0x8fa7960aUL, - 0xce968d13UL, 0x0900cc5cUL, 0x4831d745UL, 0x8b62fa6eUL, 0xca53e177UL, - 0x545dbbbaUL, 0x156ca0a3UL, 0xd63f8d88UL, 0x970e9691UL, 0x5098d7deUL, - 0x11a9ccc7UL, 0xd2fae1ecUL, 0x93cbfaf5UL, 0x5cd76272UL, 0x1de6796bUL, - 0xdeb55440UL, 0x9f844f59UL, 0x58120e16UL, 0x1923150fUL, 0xda703824UL, - 0x9b41233dUL, 0xa76bfd65UL, 0xe65ae67cUL, 0x2509cb57UL, 0x6438d04eUL, - 0xa3ae9101UL, 0xe29f8a18UL, 0x21cca733UL, 0x60fdbc2aUL, 0xafe124adUL, - 0xeed03fb4UL, 0x2d83129fUL, 0x6cb20986UL, 0xab2448c9UL, 0xea1553d0UL, - 0x29467efbUL, 0x687765e2UL, 0xf6793f2fUL, 0xb7482436UL, 0x741b091dUL, - 0x352a1204UL, 0xf2bc534bUL, 0xb38d4852UL, 0x70de6579UL, 0x31ef7e60UL, - 0xfef3e6e7UL, 0xbfc2fdfeUL, 0x7c91d0d5UL, 0x3da0cbccUL, 0xfa368a83UL, - 0xbb07919aUL, 0x7854bcb1UL, 0x3965a7a8UL, 0x4b98833bUL, 0x0aa99822UL, - 0xc9fab509UL, 0x88cbae10UL, 0x4f5def5fUL, 0x0e6cf446UL, 0xcd3fd96dUL, - 0x8c0ec274UL, 0x43125af3UL, 0x022341eaUL, 0xc1706cc1UL, 0x804177d8UL, - 0x47d73697UL, 0x06e62d8eUL, 0xc5b500a5UL, 0x84841bbcUL, 0x1a8a4171UL, - 0x5bbb5a68UL, 0x98e87743UL, 0xd9d96c5aUL, 0x1e4f2d15UL, 0x5f7e360cUL, - 0x9c2d1b27UL, 0xdd1c003eUL, 0x120098b9UL, 0x533183a0UL, 0x9062ae8bUL, - 0xd153b592UL, 0x16c5f4ddUL, 0x57f4efc4UL, 0x94a7c2efUL, 0xd596d9f6UL, - 0xe9bc07aeUL, 0xa88d1cb7UL, 0x6bde319cUL, 0x2aef2a85UL, 0xed796bcaUL, - 0xac4870d3UL, 0x6f1b5df8UL, 0x2e2a46e1UL, 0xe136de66UL, 0xa007c57fUL, - 0x6354e854UL, 0x2265f34dUL, 0xe5f3b202UL, 0xa4c2a91bUL, 0x67918430UL, - 0x26a09f29UL, 0xb8aec5e4UL, 0xf99fdefdUL, 0x3accf3d6UL, 0x7bfde8cfUL, - 0xbc6ba980UL, 0xfd5ab299UL, 0x3e099fb2UL, 0x7f3884abUL, 0xb0241c2cUL, - 0xf1150735UL, 0x32462a1eUL, 0x73773107UL, 0xb4e17048UL, 0xf5d06b51UL, - 0x3683467aUL, 0x77b25d63UL, 0x4ed7facbUL, 0x0fe6e1d2UL, 0xccb5ccf9UL, - 0x8d84d7e0UL, 0x4a1296afUL, 0x0b238db6UL, 0xc870a09dUL, 0x8941bb84UL, - 0x465d2303UL, 0x076c381aUL, 0xc43f1531UL, 0x850e0e28UL, 0x42984f67UL, - 0x03a9547eUL, 0xc0fa7955UL, 0x81cb624cUL, 0x1fc53881UL, 0x5ef42398UL, - 0x9da70eb3UL, 0xdc9615aaUL, 0x1b0054e5UL, 0x5a314ffcUL, 0x996262d7UL, - 0xd85379ceUL, 0x174fe149UL, 0x567efa50UL, 0x952dd77bUL, 0xd41ccc62UL, - 0x138a8d2dUL, 0x52bb9634UL, 0x91e8bb1fUL, 0xd0d9a006UL, 0xecf37e5eUL, - 0xadc26547UL, 0x6e91486cUL, 0x2fa05375UL, 0xe836123aUL, 0xa9070923UL, - 0x6a542408UL, 0x2b653f11UL, 0xe479a796UL, 0xa548bc8fUL, 0x661b91a4UL, - 0x272a8abdUL, 0xe0bccbf2UL, 0xa18dd0ebUL, 0x62defdc0UL, 0x23efe6d9UL, - 0xbde1bc14UL, 0xfcd0a70dUL, 0x3f838a26UL, 0x7eb2913fUL, 0xb924d070UL, - 0xf815cb69UL, 0x3b46e642UL, 0x7a77fd5bUL, 0xb56b65dcUL, 0xf45a7ec5UL, - 0x370953eeUL, 0x763848f7UL, 0xb1ae09b8UL, 0xf09f12a1UL, 0x33cc3f8aUL, - 0x72fd2493UL - }, - { - 0x00000000UL, 0x376ac201UL, 0x6ed48403UL, 0x59be4602UL, 0xdca80907UL, - 0xebc2cb06UL, 0xb27c8d04UL, 0x85164f05UL, 0xb851130eUL, 0x8f3bd10fUL, - 0xd685970dUL, 0xe1ef550cUL, 0x64f91a09UL, 0x5393d808UL, 0x0a2d9e0aUL, - 0x3d475c0bUL, 0x70a3261cUL, 0x47c9e41dUL, 0x1e77a21fUL, 0x291d601eUL, - 0xac0b2f1bUL, 0x9b61ed1aUL, 0xc2dfab18UL, 0xf5b56919UL, 0xc8f23512UL, - 0xff98f713UL, 0xa626b111UL, 0x914c7310UL, 0x145a3c15UL, 0x2330fe14UL, - 0x7a8eb816UL, 0x4de47a17UL, 0xe0464d38UL, 0xd72c8f39UL, 0x8e92c93bUL, - 0xb9f80b3aUL, 0x3cee443fUL, 0x0b84863eUL, 0x523ac03cUL, 0x6550023dUL, - 0x58175e36UL, 0x6f7d9c37UL, 0x36c3da35UL, 0x01a91834UL, 0x84bf5731UL, - 0xb3d59530UL, 0xea6bd332UL, 0xdd011133UL, 0x90e56b24UL, 0xa78fa925UL, - 0xfe31ef27UL, 0xc95b2d26UL, 0x4c4d6223UL, 0x7b27a022UL, 0x2299e620UL, - 0x15f32421UL, 0x28b4782aUL, 0x1fdeba2bUL, 0x4660fc29UL, 0x710a3e28UL, - 0xf41c712dUL, 0xc376b32cUL, 0x9ac8f52eUL, 0xada2372fUL, 0xc08d9a70UL, - 0xf7e75871UL, 0xae591e73UL, 0x9933dc72UL, 0x1c259377UL, 0x2b4f5176UL, - 0x72f11774UL, 0x459bd575UL, 0x78dc897eUL, 0x4fb64b7fUL, 0x16080d7dUL, - 0x2162cf7cUL, 0xa4748079UL, 0x931e4278UL, 0xcaa0047aUL, 0xfdcac67bUL, - 0xb02ebc6cUL, 0x87447e6dUL, 0xdefa386fUL, 0xe990fa6eUL, 0x6c86b56bUL, - 0x5bec776aUL, 0x02523168UL, 0x3538f369UL, 0x087faf62UL, 0x3f156d63UL, - 0x66ab2b61UL, 0x51c1e960UL, 0xd4d7a665UL, 0xe3bd6464UL, 0xba032266UL, - 0x8d69e067UL, 0x20cbd748UL, 0x17a11549UL, 0x4e1f534bUL, 0x7975914aUL, - 0xfc63de4fUL, 0xcb091c4eUL, 0x92b75a4cUL, 0xa5dd984dUL, 0x989ac446UL, - 0xaff00647UL, 0xf64e4045UL, 0xc1248244UL, 0x4432cd41UL, 0x73580f40UL, - 0x2ae64942UL, 0x1d8c8b43UL, 0x5068f154UL, 0x67023355UL, 0x3ebc7557UL, - 0x09d6b756UL, 0x8cc0f853UL, 0xbbaa3a52UL, 0xe2147c50UL, 0xd57ebe51UL, - 0xe839e25aUL, 0xdf53205bUL, 0x86ed6659UL, 0xb187a458UL, 0x3491eb5dUL, - 0x03fb295cUL, 0x5a456f5eUL, 0x6d2fad5fUL, 0x801b35e1UL, 0xb771f7e0UL, - 0xeecfb1e2UL, 0xd9a573e3UL, 0x5cb33ce6UL, 0x6bd9fee7UL, 0x3267b8e5UL, - 0x050d7ae4UL, 0x384a26efUL, 0x0f20e4eeUL, 0x569ea2ecUL, 0x61f460edUL, - 0xe4e22fe8UL, 0xd388ede9UL, 0x8a36abebUL, 0xbd5c69eaUL, 0xf0b813fdUL, - 0xc7d2d1fcUL, 0x9e6c97feUL, 0xa90655ffUL, 0x2c101afaUL, 0x1b7ad8fbUL, - 0x42c49ef9UL, 0x75ae5cf8UL, 0x48e900f3UL, 0x7f83c2f2UL, 0x263d84f0UL, - 0x115746f1UL, 0x944109f4UL, 0xa32bcbf5UL, 0xfa958df7UL, 0xcdff4ff6UL, - 0x605d78d9UL, 0x5737bad8UL, 0x0e89fcdaUL, 0x39e33edbUL, 0xbcf571deUL, - 0x8b9fb3dfUL, 0xd221f5ddUL, 0xe54b37dcUL, 0xd80c6bd7UL, 0xef66a9d6UL, - 0xb6d8efd4UL, 0x81b22dd5UL, 0x04a462d0UL, 0x33cea0d1UL, 0x6a70e6d3UL, - 0x5d1a24d2UL, 0x10fe5ec5UL, 0x27949cc4UL, 0x7e2adac6UL, 0x494018c7UL, - 0xcc5657c2UL, 0xfb3c95c3UL, 0xa282d3c1UL, 0x95e811c0UL, 0xa8af4dcbUL, - 0x9fc58fcaUL, 0xc67bc9c8UL, 0xf1110bc9UL, 0x740744ccUL, 0x436d86cdUL, - 0x1ad3c0cfUL, 0x2db902ceUL, 0x4096af91UL, 0x77fc6d90UL, 0x2e422b92UL, - 0x1928e993UL, 0x9c3ea696UL, 0xab546497UL, 0xf2ea2295UL, 0xc580e094UL, - 0xf8c7bc9fUL, 0xcfad7e9eUL, 0x9613389cUL, 0xa179fa9dUL, 0x246fb598UL, - 0x13057799UL, 0x4abb319bUL, 0x7dd1f39aUL, 0x3035898dUL, 0x075f4b8cUL, - 0x5ee10d8eUL, 0x698bcf8fUL, 0xec9d808aUL, 0xdbf7428bUL, 0x82490489UL, - 0xb523c688UL, 0x88649a83UL, 0xbf0e5882UL, 0xe6b01e80UL, 0xd1dadc81UL, - 0x54cc9384UL, 0x63a65185UL, 0x3a181787UL, 0x0d72d586UL, 0xa0d0e2a9UL, - 0x97ba20a8UL, 0xce0466aaUL, 0xf96ea4abUL, 0x7c78ebaeUL, 0x4b1229afUL, - 0x12ac6fadUL, 0x25c6adacUL, 0x1881f1a7UL, 0x2feb33a6UL, 0x765575a4UL, - 0x413fb7a5UL, 0xc429f8a0UL, 0xf3433aa1UL, 0xaafd7ca3UL, 0x9d97bea2UL, - 0xd073c4b5UL, 0xe71906b4UL, 0xbea740b6UL, 0x89cd82b7UL, 0x0cdbcdb2UL, - 0x3bb10fb3UL, 0x620f49b1UL, 0x55658bb0UL, 0x6822d7bbUL, 0x5f4815baUL, - 0x06f653b8UL, 0x319c91b9UL, 0xb48adebcUL, 0x83e01cbdUL, 0xda5e5abfUL, - 0xed3498beUL - }, - { - 0x00000000UL, 0x6567bcb8UL, 0x8bc809aaUL, 0xeeafb512UL, 0x5797628fUL, - 0x32f0de37UL, 0xdc5f6b25UL, 0xb938d79dUL, 0xef28b4c5UL, 0x8a4f087dUL, - 0x64e0bd6fUL, 0x018701d7UL, 0xb8bfd64aUL, 0xddd86af2UL, 0x3377dfe0UL, - 0x56106358UL, 0x9f571950UL, 0xfa30a5e8UL, 0x149f10faUL, 0x71f8ac42UL, - 0xc8c07bdfUL, 0xada7c767UL, 0x43087275UL, 0x266fcecdUL, 0x707fad95UL, - 0x1518112dUL, 0xfbb7a43fUL, 0x9ed01887UL, 0x27e8cf1aUL, 0x428f73a2UL, - 0xac20c6b0UL, 0xc9477a08UL, 0x3eaf32a0UL, 0x5bc88e18UL, 0xb5673b0aUL, - 0xd00087b2UL, 0x6938502fUL, 0x0c5fec97UL, 0xe2f05985UL, 0x8797e53dUL, - 0xd1878665UL, 0xb4e03addUL, 0x5a4f8fcfUL, 0x3f283377UL, 0x8610e4eaUL, - 0xe3775852UL, 0x0dd8ed40UL, 0x68bf51f8UL, 0xa1f82bf0UL, 0xc49f9748UL, - 0x2a30225aUL, 0x4f579ee2UL, 0xf66f497fUL, 0x9308f5c7UL, 0x7da740d5UL, - 0x18c0fc6dUL, 0x4ed09f35UL, 0x2bb7238dUL, 0xc518969fUL, 0xa07f2a27UL, - 0x1947fdbaUL, 0x7c204102UL, 0x928ff410UL, 0xf7e848a8UL, 0x3d58149bUL, - 0x583fa823UL, 0xb6901d31UL, 0xd3f7a189UL, 0x6acf7614UL, 0x0fa8caacUL, - 0xe1077fbeUL, 0x8460c306UL, 0xd270a05eUL, 0xb7171ce6UL, 0x59b8a9f4UL, - 0x3cdf154cUL, 0x85e7c2d1UL, 0xe0807e69UL, 0x0e2fcb7bUL, 0x6b4877c3UL, - 0xa20f0dcbUL, 0xc768b173UL, 0x29c70461UL, 0x4ca0b8d9UL, 0xf5986f44UL, - 0x90ffd3fcUL, 0x7e5066eeUL, 0x1b37da56UL, 0x4d27b90eUL, 0x284005b6UL, - 0xc6efb0a4UL, 0xa3880c1cUL, 0x1ab0db81UL, 0x7fd76739UL, 0x9178d22bUL, - 0xf41f6e93UL, 0x03f7263bUL, 0x66909a83UL, 0x883f2f91UL, 0xed589329UL, - 0x546044b4UL, 0x3107f80cUL, 0xdfa84d1eUL, 0xbacff1a6UL, 0xecdf92feUL, - 0x89b82e46UL, 0x67179b54UL, 0x027027ecUL, 0xbb48f071UL, 0xde2f4cc9UL, - 0x3080f9dbUL, 0x55e74563UL, 0x9ca03f6bUL, 0xf9c783d3UL, 0x176836c1UL, - 0x720f8a79UL, 0xcb375de4UL, 0xae50e15cUL, 0x40ff544eUL, 0x2598e8f6UL, - 0x73888baeUL, 0x16ef3716UL, 0xf8408204UL, 0x9d273ebcUL, 0x241fe921UL, - 0x41785599UL, 0xafd7e08bUL, 0xcab05c33UL, 0x3bb659edUL, 0x5ed1e555UL, - 0xb07e5047UL, 0xd519ecffUL, 0x6c213b62UL, 0x094687daUL, 0xe7e932c8UL, - 0x828e8e70UL, 0xd49eed28UL, 0xb1f95190UL, 0x5f56e482UL, 0x3a31583aUL, - 0x83098fa7UL, 0xe66e331fUL, 0x08c1860dUL, 0x6da63ab5UL, 0xa4e140bdUL, - 0xc186fc05UL, 0x2f294917UL, 0x4a4ef5afUL, 0xf3762232UL, 0x96119e8aUL, - 0x78be2b98UL, 0x1dd99720UL, 0x4bc9f478UL, 0x2eae48c0UL, 0xc001fdd2UL, - 0xa566416aUL, 0x1c5e96f7UL, 0x79392a4fUL, 0x97969f5dUL, 0xf2f123e5UL, - 0x05196b4dUL, 0x607ed7f5UL, 0x8ed162e7UL, 0xebb6de5fUL, 0x528e09c2UL, - 0x37e9b57aUL, 0xd9460068UL, 0xbc21bcd0UL, 0xea31df88UL, 0x8f566330UL, - 0x61f9d622UL, 0x049e6a9aUL, 0xbda6bd07UL, 0xd8c101bfUL, 0x366eb4adUL, - 0x53090815UL, 0x9a4e721dUL, 0xff29cea5UL, 0x11867bb7UL, 0x74e1c70fUL, - 0xcdd91092UL, 0xa8beac2aUL, 0x46111938UL, 0x2376a580UL, 0x7566c6d8UL, - 0x10017a60UL, 0xfeaecf72UL, 0x9bc973caUL, 0x22f1a457UL, 0x479618efUL, - 0xa939adfdUL, 0xcc5e1145UL, 0x06ee4d76UL, 0x6389f1ceUL, 0x8d2644dcUL, - 0xe841f864UL, 0x51792ff9UL, 0x341e9341UL, 0xdab12653UL, 0xbfd69aebUL, - 0xe9c6f9b3UL, 0x8ca1450bUL, 0x620ef019UL, 0x07694ca1UL, 0xbe519b3cUL, - 0xdb362784UL, 0x35999296UL, 0x50fe2e2eUL, 0x99b95426UL, 0xfcdee89eUL, - 0x12715d8cUL, 0x7716e134UL, 0xce2e36a9UL, 0xab498a11UL, 0x45e63f03UL, - 0x208183bbUL, 0x7691e0e3UL, 0x13f65c5bUL, 0xfd59e949UL, 0x983e55f1UL, - 0x2106826cUL, 0x44613ed4UL, 0xaace8bc6UL, 0xcfa9377eUL, 0x38417fd6UL, - 0x5d26c36eUL, 0xb389767cUL, 0xd6eecac4UL, 0x6fd61d59UL, 0x0ab1a1e1UL, - 0xe41e14f3UL, 0x8179a84bUL, 0xd769cb13UL, 0xb20e77abUL, 0x5ca1c2b9UL, - 0x39c67e01UL, 0x80fea99cUL, 0xe5991524UL, 0x0b36a036UL, 0x6e511c8eUL, - 0xa7166686UL, 0xc271da3eUL, 0x2cde6f2cUL, 0x49b9d394UL, 0xf0810409UL, - 0x95e6b8b1UL, 0x7b490da3UL, 0x1e2eb11bUL, 0x483ed243UL, 0x2d596efbUL, - 0xc3f6dbe9UL, 0xa6916751UL, 0x1fa9b0ccUL, 0x7ace0c74UL, 0x9461b966UL, - 0xf10605deUL -#endif - } -}; +/* crc32.h -- tables for rapid CRC calculation + * Generated automatically by crc32.c + */ + +local const unsigned long FAR crc_table[TBLS][256] = +{ + { + 0x00000000UL, 0x77073096UL, 0xee0e612cUL, 0x990951baUL, 0x076dc419UL, + 0x706af48fUL, 0xe963a535UL, 0x9e6495a3UL, 0x0edb8832UL, 0x79dcb8a4UL, + 0xe0d5e91eUL, 0x97d2d988UL, 0x09b64c2bUL, 0x7eb17cbdUL, 0xe7b82d07UL, + 0x90bf1d91UL, 0x1db71064UL, 0x6ab020f2UL, 0xf3b97148UL, 0x84be41deUL, + 0x1adad47dUL, 0x6ddde4ebUL, 0xf4d4b551UL, 0x83d385c7UL, 0x136c9856UL, + 0x646ba8c0UL, 0xfd62f97aUL, 0x8a65c9ecUL, 0x14015c4fUL, 0x63066cd9UL, + 0xfa0f3d63UL, 0x8d080df5UL, 0x3b6e20c8UL, 0x4c69105eUL, 0xd56041e4UL, + 0xa2677172UL, 0x3c03e4d1UL, 0x4b04d447UL, 0xd20d85fdUL, 0xa50ab56bUL, + 0x35b5a8faUL, 0x42b2986cUL, 0xdbbbc9d6UL, 0xacbcf940UL, 0x32d86ce3UL, + 0x45df5c75UL, 0xdcd60dcfUL, 0xabd13d59UL, 0x26d930acUL, 0x51de003aUL, + 0xc8d75180UL, 0xbfd06116UL, 0x21b4f4b5UL, 0x56b3c423UL, 0xcfba9599UL, + 0xb8bda50fUL, 0x2802b89eUL, 0x5f058808UL, 0xc60cd9b2UL, 0xb10be924UL, + 0x2f6f7c87UL, 0x58684c11UL, 0xc1611dabUL, 0xb6662d3dUL, 0x76dc4190UL, + 0x01db7106UL, 0x98d220bcUL, 0xefd5102aUL, 0x71b18589UL, 0x06b6b51fUL, + 0x9fbfe4a5UL, 0xe8b8d433UL, 0x7807c9a2UL, 0x0f00f934UL, 0x9609a88eUL, + 0xe10e9818UL, 0x7f6a0dbbUL, 0x086d3d2dUL, 0x91646c97UL, 0xe6635c01UL, + 0x6b6b51f4UL, 0x1c6c6162UL, 0x856530d8UL, 0xf262004eUL, 0x6c0695edUL, + 0x1b01a57bUL, 0x8208f4c1UL, 0xf50fc457UL, 0x65b0d9c6UL, 0x12b7e950UL, + 0x8bbeb8eaUL, 0xfcb9887cUL, 0x62dd1ddfUL, 0x15da2d49UL, 0x8cd37cf3UL, + 0xfbd44c65UL, 0x4db26158UL, 0x3ab551ceUL, 0xa3bc0074UL, 0xd4bb30e2UL, + 0x4adfa541UL, 0x3dd895d7UL, 0xa4d1c46dUL, 0xd3d6f4fbUL, 0x4369e96aUL, + 0x346ed9fcUL, 0xad678846UL, 0xda60b8d0UL, 0x44042d73UL, 0x33031de5UL, + 0xaa0a4c5fUL, 0xdd0d7cc9UL, 0x5005713cUL, 0x270241aaUL, 0xbe0b1010UL, + 0xc90c2086UL, 0x5768b525UL, 0x206f85b3UL, 0xb966d409UL, 0xce61e49fUL, + 0x5edef90eUL, 0x29d9c998UL, 0xb0d09822UL, 0xc7d7a8b4UL, 0x59b33d17UL, + 0x2eb40d81UL, 0xb7bd5c3bUL, 0xc0ba6cadUL, 0xedb88320UL, 0x9abfb3b6UL, + 0x03b6e20cUL, 0x74b1d29aUL, 0xead54739UL, 0x9dd277afUL, 0x04db2615UL, + 0x73dc1683UL, 0xe3630b12UL, 0x94643b84UL, 0x0d6d6a3eUL, 0x7a6a5aa8UL, + 0xe40ecf0bUL, 0x9309ff9dUL, 0x0a00ae27UL, 0x7d079eb1UL, 0xf00f9344UL, + 0x8708a3d2UL, 0x1e01f268UL, 0x6906c2feUL, 0xf762575dUL, 0x806567cbUL, + 0x196c3671UL, 0x6e6b06e7UL, 0xfed41b76UL, 0x89d32be0UL, 0x10da7a5aUL, + 0x67dd4accUL, 0xf9b9df6fUL, 0x8ebeeff9UL, 0x17b7be43UL, 0x60b08ed5UL, + 0xd6d6a3e8UL, 0xa1d1937eUL, 0x38d8c2c4UL, 0x4fdff252UL, 0xd1bb67f1UL, + 0xa6bc5767UL, 0x3fb506ddUL, 0x48b2364bUL, 0xd80d2bdaUL, 0xaf0a1b4cUL, + 0x36034af6UL, 0x41047a60UL, 0xdf60efc3UL, 0xa867df55UL, 0x316e8eefUL, + 0x4669be79UL, 0xcb61b38cUL, 0xbc66831aUL, 0x256fd2a0UL, 0x5268e236UL, + 0xcc0c7795UL, 0xbb0b4703UL, 0x220216b9UL, 0x5505262fUL, 0xc5ba3bbeUL, + 0xb2bd0b28UL, 0x2bb45a92UL, 0x5cb36a04UL, 0xc2d7ffa7UL, 0xb5d0cf31UL, + 0x2cd99e8bUL, 0x5bdeae1dUL, 0x9b64c2b0UL, 0xec63f226UL, 0x756aa39cUL, + 0x026d930aUL, 0x9c0906a9UL, 0xeb0e363fUL, 0x72076785UL, 0x05005713UL, + 0x95bf4a82UL, 0xe2b87a14UL, 0x7bb12baeUL, 0x0cb61b38UL, 0x92d28e9bUL, + 0xe5d5be0dUL, 0x7cdcefb7UL, 0x0bdbdf21UL, 0x86d3d2d4UL, 0xf1d4e242UL, + 0x68ddb3f8UL, 0x1fda836eUL, 0x81be16cdUL, 0xf6b9265bUL, 0x6fb077e1UL, + 0x18b74777UL, 0x88085ae6UL, 0xff0f6a70UL, 0x66063bcaUL, 0x11010b5cUL, + 0x8f659effUL, 0xf862ae69UL, 0x616bffd3UL, 0x166ccf45UL, 0xa00ae278UL, + 0xd70dd2eeUL, 0x4e048354UL, 0x3903b3c2UL, 0xa7672661UL, 0xd06016f7UL, + 0x4969474dUL, 0x3e6e77dbUL, 0xaed16a4aUL, 0xd9d65adcUL, 0x40df0b66UL, + 0x37d83bf0UL, 0xa9bcae53UL, 0xdebb9ec5UL, 0x47b2cf7fUL, 0x30b5ffe9UL, + 0xbdbdf21cUL, 0xcabac28aUL, 0x53b39330UL, 0x24b4a3a6UL, 0xbad03605UL, + 0xcdd70693UL, 0x54de5729UL, 0x23d967bfUL, 0xb3667a2eUL, 0xc4614ab8UL, + 0x5d681b02UL, 0x2a6f2b94UL, 0xb40bbe37UL, 0xc30c8ea1UL, 0x5a05df1bUL, + 0x2d02ef8dUL +#ifdef BYFOUR + }, + { + 0x00000000UL, 0x191b3141UL, 0x32366282UL, 0x2b2d53c3UL, 0x646cc504UL, + 0x7d77f445UL, 0x565aa786UL, 0x4f4196c7UL, 0xc8d98a08UL, 0xd1c2bb49UL, + 0xfaefe88aUL, 0xe3f4d9cbUL, 0xacb54f0cUL, 0xb5ae7e4dUL, 0x9e832d8eUL, + 0x87981ccfUL, 0x4ac21251UL, 0x53d92310UL, 0x78f470d3UL, 0x61ef4192UL, + 0x2eaed755UL, 0x37b5e614UL, 0x1c98b5d7UL, 0x05838496UL, 0x821b9859UL, + 0x9b00a918UL, 0xb02dfadbUL, 0xa936cb9aUL, 0xe6775d5dUL, 0xff6c6c1cUL, + 0xd4413fdfUL, 0xcd5a0e9eUL, 0x958424a2UL, 0x8c9f15e3UL, 0xa7b24620UL, + 0xbea97761UL, 0xf1e8e1a6UL, 0xe8f3d0e7UL, 0xc3de8324UL, 0xdac5b265UL, + 0x5d5daeaaUL, 0x44469febUL, 0x6f6bcc28UL, 0x7670fd69UL, 0x39316baeUL, + 0x202a5aefUL, 0x0b07092cUL, 0x121c386dUL, 0xdf4636f3UL, 0xc65d07b2UL, + 0xed705471UL, 0xf46b6530UL, 0xbb2af3f7UL, 0xa231c2b6UL, 0x891c9175UL, + 0x9007a034UL, 0x179fbcfbUL, 0x0e848dbaUL, 0x25a9de79UL, 0x3cb2ef38UL, + 0x73f379ffUL, 0x6ae848beUL, 0x41c51b7dUL, 0x58de2a3cUL, 0xf0794f05UL, + 0xe9627e44UL, 0xc24f2d87UL, 0xdb541cc6UL, 0x94158a01UL, 0x8d0ebb40UL, + 0xa623e883UL, 0xbf38d9c2UL, 0x38a0c50dUL, 0x21bbf44cUL, 0x0a96a78fUL, + 0x138d96ceUL, 0x5ccc0009UL, 0x45d73148UL, 0x6efa628bUL, 0x77e153caUL, + 0xbabb5d54UL, 0xa3a06c15UL, 0x888d3fd6UL, 0x91960e97UL, 0xded79850UL, + 0xc7cca911UL, 0xece1fad2UL, 0xf5facb93UL, 0x7262d75cUL, 0x6b79e61dUL, + 0x4054b5deUL, 0x594f849fUL, 0x160e1258UL, 0x0f152319UL, 0x243870daUL, + 0x3d23419bUL, 0x65fd6ba7UL, 0x7ce65ae6UL, 0x57cb0925UL, 0x4ed03864UL, + 0x0191aea3UL, 0x188a9fe2UL, 0x33a7cc21UL, 0x2abcfd60UL, 0xad24e1afUL, + 0xb43fd0eeUL, 0x9f12832dUL, 0x8609b26cUL, 0xc94824abUL, 0xd05315eaUL, + 0xfb7e4629UL, 0xe2657768UL, 0x2f3f79f6UL, 0x362448b7UL, 0x1d091b74UL, + 0x04122a35UL, 0x4b53bcf2UL, 0x52488db3UL, 0x7965de70UL, 0x607eef31UL, + 0xe7e6f3feUL, 0xfefdc2bfUL, 0xd5d0917cUL, 0xcccba03dUL, 0x838a36faUL, + 0x9a9107bbUL, 0xb1bc5478UL, 0xa8a76539UL, 0x3b83984bUL, 0x2298a90aUL, + 0x09b5fac9UL, 0x10aecb88UL, 0x5fef5d4fUL, 0x46f46c0eUL, 0x6dd93fcdUL, + 0x74c20e8cUL, 0xf35a1243UL, 0xea412302UL, 0xc16c70c1UL, 0xd8774180UL, + 0x9736d747UL, 0x8e2de606UL, 0xa500b5c5UL, 0xbc1b8484UL, 0x71418a1aUL, + 0x685abb5bUL, 0x4377e898UL, 0x5a6cd9d9UL, 0x152d4f1eUL, 0x0c367e5fUL, + 0x271b2d9cUL, 0x3e001cddUL, 0xb9980012UL, 0xa0833153UL, 0x8bae6290UL, + 0x92b553d1UL, 0xddf4c516UL, 0xc4eff457UL, 0xefc2a794UL, 0xf6d996d5UL, + 0xae07bce9UL, 0xb71c8da8UL, 0x9c31de6bUL, 0x852aef2aUL, 0xca6b79edUL, + 0xd37048acUL, 0xf85d1b6fUL, 0xe1462a2eUL, 0x66de36e1UL, 0x7fc507a0UL, + 0x54e85463UL, 0x4df36522UL, 0x02b2f3e5UL, 0x1ba9c2a4UL, 0x30849167UL, + 0x299fa026UL, 0xe4c5aeb8UL, 0xfdde9ff9UL, 0xd6f3cc3aUL, 0xcfe8fd7bUL, + 0x80a96bbcUL, 0x99b25afdUL, 0xb29f093eUL, 0xab84387fUL, 0x2c1c24b0UL, + 0x350715f1UL, 0x1e2a4632UL, 0x07317773UL, 0x4870e1b4UL, 0x516bd0f5UL, + 0x7a468336UL, 0x635db277UL, 0xcbfad74eUL, 0xd2e1e60fUL, 0xf9ccb5ccUL, + 0xe0d7848dUL, 0xaf96124aUL, 0xb68d230bUL, 0x9da070c8UL, 0x84bb4189UL, + 0x03235d46UL, 0x1a386c07UL, 0x31153fc4UL, 0x280e0e85UL, 0x674f9842UL, + 0x7e54a903UL, 0x5579fac0UL, 0x4c62cb81UL, 0x8138c51fUL, 0x9823f45eUL, + 0xb30ea79dUL, 0xaa1596dcUL, 0xe554001bUL, 0xfc4f315aUL, 0xd7626299UL, + 0xce7953d8UL, 0x49e14f17UL, 0x50fa7e56UL, 0x7bd72d95UL, 0x62cc1cd4UL, + 0x2d8d8a13UL, 0x3496bb52UL, 0x1fbbe891UL, 0x06a0d9d0UL, 0x5e7ef3ecUL, + 0x4765c2adUL, 0x6c48916eUL, 0x7553a02fUL, 0x3a1236e8UL, 0x230907a9UL, + 0x0824546aUL, 0x113f652bUL, 0x96a779e4UL, 0x8fbc48a5UL, 0xa4911b66UL, + 0xbd8a2a27UL, 0xf2cbbce0UL, 0xebd08da1UL, 0xc0fdde62UL, 0xd9e6ef23UL, + 0x14bce1bdUL, 0x0da7d0fcUL, 0x268a833fUL, 0x3f91b27eUL, 0x70d024b9UL, + 0x69cb15f8UL, 0x42e6463bUL, 0x5bfd777aUL, 0xdc656bb5UL, 0xc57e5af4UL, + 0xee530937UL, 0xf7483876UL, 0xb809aeb1UL, 0xa1129ff0UL, 0x8a3fcc33UL, + 0x9324fd72UL + }, + { + 0x00000000UL, 0x01c26a37UL, 0x0384d46eUL, 0x0246be59UL, 0x0709a8dcUL, + 0x06cbc2ebUL, 0x048d7cb2UL, 0x054f1685UL, 0x0e1351b8UL, 0x0fd13b8fUL, + 0x0d9785d6UL, 0x0c55efe1UL, 0x091af964UL, 0x08d89353UL, 0x0a9e2d0aUL, + 0x0b5c473dUL, 0x1c26a370UL, 0x1de4c947UL, 0x1fa2771eUL, 0x1e601d29UL, + 0x1b2f0bacUL, 0x1aed619bUL, 0x18abdfc2UL, 0x1969b5f5UL, 0x1235f2c8UL, + 0x13f798ffUL, 0x11b126a6UL, 0x10734c91UL, 0x153c5a14UL, 0x14fe3023UL, + 0x16b88e7aUL, 0x177ae44dUL, 0x384d46e0UL, 0x398f2cd7UL, 0x3bc9928eUL, + 0x3a0bf8b9UL, 0x3f44ee3cUL, 0x3e86840bUL, 0x3cc03a52UL, 0x3d025065UL, + 0x365e1758UL, 0x379c7d6fUL, 0x35dac336UL, 0x3418a901UL, 0x3157bf84UL, + 0x3095d5b3UL, 0x32d36beaUL, 0x331101ddUL, 0x246be590UL, 0x25a98fa7UL, + 0x27ef31feUL, 0x262d5bc9UL, 0x23624d4cUL, 0x22a0277bUL, 0x20e69922UL, + 0x2124f315UL, 0x2a78b428UL, 0x2bbade1fUL, 0x29fc6046UL, 0x283e0a71UL, + 0x2d711cf4UL, 0x2cb376c3UL, 0x2ef5c89aUL, 0x2f37a2adUL, 0x709a8dc0UL, + 0x7158e7f7UL, 0x731e59aeUL, 0x72dc3399UL, 0x7793251cUL, 0x76514f2bUL, + 0x7417f172UL, 0x75d59b45UL, 0x7e89dc78UL, 0x7f4bb64fUL, 0x7d0d0816UL, + 0x7ccf6221UL, 0x798074a4UL, 0x78421e93UL, 0x7a04a0caUL, 0x7bc6cafdUL, + 0x6cbc2eb0UL, 0x6d7e4487UL, 0x6f38fadeUL, 0x6efa90e9UL, 0x6bb5866cUL, + 0x6a77ec5bUL, 0x68315202UL, 0x69f33835UL, 0x62af7f08UL, 0x636d153fUL, + 0x612bab66UL, 0x60e9c151UL, 0x65a6d7d4UL, 0x6464bde3UL, 0x662203baUL, + 0x67e0698dUL, 0x48d7cb20UL, 0x4915a117UL, 0x4b531f4eUL, 0x4a917579UL, + 0x4fde63fcUL, 0x4e1c09cbUL, 0x4c5ab792UL, 0x4d98dda5UL, 0x46c49a98UL, + 0x4706f0afUL, 0x45404ef6UL, 0x448224c1UL, 0x41cd3244UL, 0x400f5873UL, + 0x4249e62aUL, 0x438b8c1dUL, 0x54f16850UL, 0x55330267UL, 0x5775bc3eUL, + 0x56b7d609UL, 0x53f8c08cUL, 0x523aaabbUL, 0x507c14e2UL, 0x51be7ed5UL, + 0x5ae239e8UL, 0x5b2053dfUL, 0x5966ed86UL, 0x58a487b1UL, 0x5deb9134UL, + 0x5c29fb03UL, 0x5e6f455aUL, 0x5fad2f6dUL, 0xe1351b80UL, 0xe0f771b7UL, + 0xe2b1cfeeUL, 0xe373a5d9UL, 0xe63cb35cUL, 0xe7fed96bUL, 0xe5b86732UL, + 0xe47a0d05UL, 0xef264a38UL, 0xeee4200fUL, 0xeca29e56UL, 0xed60f461UL, + 0xe82fe2e4UL, 0xe9ed88d3UL, 0xebab368aUL, 0xea695cbdUL, 0xfd13b8f0UL, + 0xfcd1d2c7UL, 0xfe976c9eUL, 0xff5506a9UL, 0xfa1a102cUL, 0xfbd87a1bUL, + 0xf99ec442UL, 0xf85cae75UL, 0xf300e948UL, 0xf2c2837fUL, 0xf0843d26UL, + 0xf1465711UL, 0xf4094194UL, 0xf5cb2ba3UL, 0xf78d95faUL, 0xf64fffcdUL, + 0xd9785d60UL, 0xd8ba3757UL, 0xdafc890eUL, 0xdb3ee339UL, 0xde71f5bcUL, + 0xdfb39f8bUL, 0xddf521d2UL, 0xdc374be5UL, 0xd76b0cd8UL, 0xd6a966efUL, + 0xd4efd8b6UL, 0xd52db281UL, 0xd062a404UL, 0xd1a0ce33UL, 0xd3e6706aUL, + 0xd2241a5dUL, 0xc55efe10UL, 0xc49c9427UL, 0xc6da2a7eUL, 0xc7184049UL, + 0xc25756ccUL, 0xc3953cfbUL, 0xc1d382a2UL, 0xc011e895UL, 0xcb4dafa8UL, + 0xca8fc59fUL, 0xc8c97bc6UL, 0xc90b11f1UL, 0xcc440774UL, 0xcd866d43UL, + 0xcfc0d31aUL, 0xce02b92dUL, 0x91af9640UL, 0x906dfc77UL, 0x922b422eUL, + 0x93e92819UL, 0x96a63e9cUL, 0x976454abUL, 0x9522eaf2UL, 0x94e080c5UL, + 0x9fbcc7f8UL, 0x9e7eadcfUL, 0x9c381396UL, 0x9dfa79a1UL, 0x98b56f24UL, + 0x99770513UL, 0x9b31bb4aUL, 0x9af3d17dUL, 0x8d893530UL, 0x8c4b5f07UL, + 0x8e0de15eUL, 0x8fcf8b69UL, 0x8a809decUL, 0x8b42f7dbUL, 0x89044982UL, + 0x88c623b5UL, 0x839a6488UL, 0x82580ebfUL, 0x801eb0e6UL, 0x81dcdad1UL, + 0x8493cc54UL, 0x8551a663UL, 0x8717183aUL, 0x86d5720dUL, 0xa9e2d0a0UL, + 0xa820ba97UL, 0xaa6604ceUL, 0xaba46ef9UL, 0xaeeb787cUL, 0xaf29124bUL, + 0xad6fac12UL, 0xacadc625UL, 0xa7f18118UL, 0xa633eb2fUL, 0xa4755576UL, + 0xa5b73f41UL, 0xa0f829c4UL, 0xa13a43f3UL, 0xa37cfdaaUL, 0xa2be979dUL, + 0xb5c473d0UL, 0xb40619e7UL, 0xb640a7beUL, 0xb782cd89UL, 0xb2cddb0cUL, + 0xb30fb13bUL, 0xb1490f62UL, 0xb08b6555UL, 0xbbd72268UL, 0xba15485fUL, + 0xb853f606UL, 0xb9919c31UL, 0xbcde8ab4UL, 0xbd1ce083UL, 0xbf5a5edaUL, + 0xbe9834edUL + }, + { + 0x00000000UL, 0xb8bc6765UL, 0xaa09c88bUL, 0x12b5afeeUL, 0x8f629757UL, + 0x37def032UL, 0x256b5fdcUL, 0x9dd738b9UL, 0xc5b428efUL, 0x7d084f8aUL, + 0x6fbde064UL, 0xd7018701UL, 0x4ad6bfb8UL, 0xf26ad8ddUL, 0xe0df7733UL, + 0x58631056UL, 0x5019579fUL, 0xe8a530faUL, 0xfa109f14UL, 0x42acf871UL, + 0xdf7bc0c8UL, 0x67c7a7adUL, 0x75720843UL, 0xcdce6f26UL, 0x95ad7f70UL, + 0x2d111815UL, 0x3fa4b7fbUL, 0x8718d09eUL, 0x1acfe827UL, 0xa2738f42UL, + 0xb0c620acUL, 0x087a47c9UL, 0xa032af3eUL, 0x188ec85bUL, 0x0a3b67b5UL, + 0xb28700d0UL, 0x2f503869UL, 0x97ec5f0cUL, 0x8559f0e2UL, 0x3de59787UL, + 0x658687d1UL, 0xdd3ae0b4UL, 0xcf8f4f5aUL, 0x7733283fUL, 0xeae41086UL, + 0x525877e3UL, 0x40edd80dUL, 0xf851bf68UL, 0xf02bf8a1UL, 0x48979fc4UL, + 0x5a22302aUL, 0xe29e574fUL, 0x7f496ff6UL, 0xc7f50893UL, 0xd540a77dUL, + 0x6dfcc018UL, 0x359fd04eUL, 0x8d23b72bUL, 0x9f9618c5UL, 0x272a7fa0UL, + 0xbafd4719UL, 0x0241207cUL, 0x10f48f92UL, 0xa848e8f7UL, 0x9b14583dUL, + 0x23a83f58UL, 0x311d90b6UL, 0x89a1f7d3UL, 0x1476cf6aUL, 0xaccaa80fUL, + 0xbe7f07e1UL, 0x06c36084UL, 0x5ea070d2UL, 0xe61c17b7UL, 0xf4a9b859UL, + 0x4c15df3cUL, 0xd1c2e785UL, 0x697e80e0UL, 0x7bcb2f0eUL, 0xc377486bUL, + 0xcb0d0fa2UL, 0x73b168c7UL, 0x6104c729UL, 0xd9b8a04cUL, 0x446f98f5UL, + 0xfcd3ff90UL, 0xee66507eUL, 0x56da371bUL, 0x0eb9274dUL, 0xb6054028UL, + 0xa4b0efc6UL, 0x1c0c88a3UL, 0x81dbb01aUL, 0x3967d77fUL, 0x2bd27891UL, + 0x936e1ff4UL, 0x3b26f703UL, 0x839a9066UL, 0x912f3f88UL, 0x299358edUL, + 0xb4446054UL, 0x0cf80731UL, 0x1e4da8dfUL, 0xa6f1cfbaUL, 0xfe92dfecUL, + 0x462eb889UL, 0x549b1767UL, 0xec277002UL, 0x71f048bbUL, 0xc94c2fdeUL, + 0xdbf98030UL, 0x6345e755UL, 0x6b3fa09cUL, 0xd383c7f9UL, 0xc1366817UL, + 0x798a0f72UL, 0xe45d37cbUL, 0x5ce150aeUL, 0x4e54ff40UL, 0xf6e89825UL, + 0xae8b8873UL, 0x1637ef16UL, 0x048240f8UL, 0xbc3e279dUL, 0x21e91f24UL, + 0x99557841UL, 0x8be0d7afUL, 0x335cb0caUL, 0xed59b63bUL, 0x55e5d15eUL, + 0x47507eb0UL, 0xffec19d5UL, 0x623b216cUL, 0xda874609UL, 0xc832e9e7UL, + 0x708e8e82UL, 0x28ed9ed4UL, 0x9051f9b1UL, 0x82e4565fUL, 0x3a58313aUL, + 0xa78f0983UL, 0x1f336ee6UL, 0x0d86c108UL, 0xb53aa66dUL, 0xbd40e1a4UL, + 0x05fc86c1UL, 0x1749292fUL, 0xaff54e4aUL, 0x322276f3UL, 0x8a9e1196UL, + 0x982bbe78UL, 0x2097d91dUL, 0x78f4c94bUL, 0xc048ae2eUL, 0xd2fd01c0UL, + 0x6a4166a5UL, 0xf7965e1cUL, 0x4f2a3979UL, 0x5d9f9697UL, 0xe523f1f2UL, + 0x4d6b1905UL, 0xf5d77e60UL, 0xe762d18eUL, 0x5fdeb6ebUL, 0xc2098e52UL, + 0x7ab5e937UL, 0x680046d9UL, 0xd0bc21bcUL, 0x88df31eaUL, 0x3063568fUL, + 0x22d6f961UL, 0x9a6a9e04UL, 0x07bda6bdUL, 0xbf01c1d8UL, 0xadb46e36UL, + 0x15080953UL, 0x1d724e9aUL, 0xa5ce29ffUL, 0xb77b8611UL, 0x0fc7e174UL, + 0x9210d9cdUL, 0x2aacbea8UL, 0x38191146UL, 0x80a57623UL, 0xd8c66675UL, + 0x607a0110UL, 0x72cfaefeUL, 0xca73c99bUL, 0x57a4f122UL, 0xef189647UL, + 0xfdad39a9UL, 0x45115eccUL, 0x764dee06UL, 0xcef18963UL, 0xdc44268dUL, + 0x64f841e8UL, 0xf92f7951UL, 0x41931e34UL, 0x5326b1daUL, 0xeb9ad6bfUL, + 0xb3f9c6e9UL, 0x0b45a18cUL, 0x19f00e62UL, 0xa14c6907UL, 0x3c9b51beUL, + 0x842736dbUL, 0x96929935UL, 0x2e2efe50UL, 0x2654b999UL, 0x9ee8defcUL, + 0x8c5d7112UL, 0x34e11677UL, 0xa9362eceUL, 0x118a49abUL, 0x033fe645UL, + 0xbb838120UL, 0xe3e09176UL, 0x5b5cf613UL, 0x49e959fdUL, 0xf1553e98UL, + 0x6c820621UL, 0xd43e6144UL, 0xc68bceaaUL, 0x7e37a9cfUL, 0xd67f4138UL, + 0x6ec3265dUL, 0x7c7689b3UL, 0xc4caeed6UL, 0x591dd66fUL, 0xe1a1b10aUL, + 0xf3141ee4UL, 0x4ba87981UL, 0x13cb69d7UL, 0xab770eb2UL, 0xb9c2a15cUL, + 0x017ec639UL, 0x9ca9fe80UL, 0x241599e5UL, 0x36a0360bUL, 0x8e1c516eUL, + 0x866616a7UL, 0x3eda71c2UL, 0x2c6fde2cUL, 0x94d3b949UL, 0x090481f0UL, + 0xb1b8e695UL, 0xa30d497bUL, 0x1bb12e1eUL, 0x43d23e48UL, 0xfb6e592dUL, + 0xe9dbf6c3UL, 0x516791a6UL, 0xccb0a91fUL, 0x740cce7aUL, 0x66b96194UL, + 0xde0506f1UL + }, + { + 0x00000000UL, 0x96300777UL, 0x2c610eeeUL, 0xba510999UL, 0x19c46d07UL, + 0x8ff46a70UL, 0x35a563e9UL, 0xa395649eUL, 0x3288db0eUL, 0xa4b8dc79UL, + 0x1ee9d5e0UL, 0x88d9d297UL, 0x2b4cb609UL, 0xbd7cb17eUL, 0x072db8e7UL, + 0x911dbf90UL, 0x6410b71dUL, 0xf220b06aUL, 0x4871b9f3UL, 0xde41be84UL, + 0x7dd4da1aUL, 0xebe4dd6dUL, 0x51b5d4f4UL, 0xc785d383UL, 0x56986c13UL, + 0xc0a86b64UL, 0x7af962fdUL, 0xecc9658aUL, 0x4f5c0114UL, 0xd96c0663UL, + 0x633d0ffaUL, 0xf50d088dUL, 0xc8206e3bUL, 0x5e10694cUL, 0xe44160d5UL, + 0x727167a2UL, 0xd1e4033cUL, 0x47d4044bUL, 0xfd850dd2UL, 0x6bb50aa5UL, + 0xfaa8b535UL, 0x6c98b242UL, 0xd6c9bbdbUL, 0x40f9bcacUL, 0xe36cd832UL, + 0x755cdf45UL, 0xcf0dd6dcUL, 0x593dd1abUL, 0xac30d926UL, 0x3a00de51UL, + 0x8051d7c8UL, 0x1661d0bfUL, 0xb5f4b421UL, 0x23c4b356UL, 0x9995bacfUL, + 0x0fa5bdb8UL, 0x9eb80228UL, 0x0888055fUL, 0xb2d90cc6UL, 0x24e90bb1UL, + 0x877c6f2fUL, 0x114c6858UL, 0xab1d61c1UL, 0x3d2d66b6UL, 0x9041dc76UL, + 0x0671db01UL, 0xbc20d298UL, 0x2a10d5efUL, 0x8985b171UL, 0x1fb5b606UL, + 0xa5e4bf9fUL, 0x33d4b8e8UL, 0xa2c90778UL, 0x34f9000fUL, 0x8ea80996UL, + 0x18980ee1UL, 0xbb0d6a7fUL, 0x2d3d6d08UL, 0x976c6491UL, 0x015c63e6UL, + 0xf4516b6bUL, 0x62616c1cUL, 0xd8306585UL, 0x4e0062f2UL, 0xed95066cUL, + 0x7ba5011bUL, 0xc1f40882UL, 0x57c40ff5UL, 0xc6d9b065UL, 0x50e9b712UL, + 0xeab8be8bUL, 0x7c88b9fcUL, 0xdf1ddd62UL, 0x492dda15UL, 0xf37cd38cUL, + 0x654cd4fbUL, 0x5861b24dUL, 0xce51b53aUL, 0x7400bca3UL, 0xe230bbd4UL, + 0x41a5df4aUL, 0xd795d83dUL, 0x6dc4d1a4UL, 0xfbf4d6d3UL, 0x6ae96943UL, + 0xfcd96e34UL, 0x468867adUL, 0xd0b860daUL, 0x732d0444UL, 0xe51d0333UL, + 0x5f4c0aaaUL, 0xc97c0dddUL, 0x3c710550UL, 0xaa410227UL, 0x10100bbeUL, + 0x86200cc9UL, 0x25b56857UL, 0xb3856f20UL, 0x09d466b9UL, 0x9fe461ceUL, + 0x0ef9de5eUL, 0x98c9d929UL, 0x2298d0b0UL, 0xb4a8d7c7UL, 0x173db359UL, + 0x810db42eUL, 0x3b5cbdb7UL, 0xad6cbac0UL, 0x2083b8edUL, 0xb6b3bf9aUL, + 0x0ce2b603UL, 0x9ad2b174UL, 0x3947d5eaUL, 0xaf77d29dUL, 0x1526db04UL, + 0x8316dc73UL, 0x120b63e3UL, 0x843b6494UL, 0x3e6a6d0dUL, 0xa85a6a7aUL, + 0x0bcf0ee4UL, 0x9dff0993UL, 0x27ae000aUL, 0xb19e077dUL, 0x44930ff0UL, + 0xd2a30887UL, 0x68f2011eUL, 0xfec20669UL, 0x5d5762f7UL, 0xcb676580UL, + 0x71366c19UL, 0xe7066b6eUL, 0x761bd4feUL, 0xe02bd389UL, 0x5a7ada10UL, + 0xcc4add67UL, 0x6fdfb9f9UL, 0xf9efbe8eUL, 0x43beb717UL, 0xd58eb060UL, + 0xe8a3d6d6UL, 0x7e93d1a1UL, 0xc4c2d838UL, 0x52f2df4fUL, 0xf167bbd1UL, + 0x6757bca6UL, 0xdd06b53fUL, 0x4b36b248UL, 0xda2b0dd8UL, 0x4c1b0aafUL, + 0xf64a0336UL, 0x607a0441UL, 0xc3ef60dfUL, 0x55df67a8UL, 0xef8e6e31UL, + 0x79be6946UL, 0x8cb361cbUL, 0x1a8366bcUL, 0xa0d26f25UL, 0x36e26852UL, + 0x95770cccUL, 0x03470bbbUL, 0xb9160222UL, 0x2f260555UL, 0xbe3bbac5UL, + 0x280bbdb2UL, 0x925ab42bUL, 0x046ab35cUL, 0xa7ffd7c2UL, 0x31cfd0b5UL, + 0x8b9ed92cUL, 0x1daede5bUL, 0xb0c2649bUL, 0x26f263ecUL, 0x9ca36a75UL, + 0x0a936d02UL, 0xa906099cUL, 0x3f360eebUL, 0x85670772UL, 0x13570005UL, + 0x824abf95UL, 0x147ab8e2UL, 0xae2bb17bUL, 0x381bb60cUL, 0x9b8ed292UL, + 0x0dbed5e5UL, 0xb7efdc7cUL, 0x21dfdb0bUL, 0xd4d2d386UL, 0x42e2d4f1UL, + 0xf8b3dd68UL, 0x6e83da1fUL, 0xcd16be81UL, 0x5b26b9f6UL, 0xe177b06fUL, + 0x7747b718UL, 0xe65a0888UL, 0x706a0fffUL, 0xca3b0666UL, 0x5c0b0111UL, + 0xff9e658fUL, 0x69ae62f8UL, 0xd3ff6b61UL, 0x45cf6c16UL, 0x78e20aa0UL, + 0xeed20dd7UL, 0x5483044eUL, 0xc2b30339UL, 0x612667a7UL, 0xf71660d0UL, + 0x4d476949UL, 0xdb776e3eUL, 0x4a6ad1aeUL, 0xdc5ad6d9UL, 0x660bdf40UL, + 0xf03bd837UL, 0x53aebca9UL, 0xc59ebbdeUL, 0x7fcfb247UL, 0xe9ffb530UL, + 0x1cf2bdbdUL, 0x8ac2bacaUL, 0x3093b353UL, 0xa6a3b424UL, 0x0536d0baUL, + 0x9306d7cdUL, 0x2957de54UL, 0xbf67d923UL, 0x2e7a66b3UL, 0xb84a61c4UL, + 0x021b685dUL, 0x942b6f2aUL, 0x37be0bb4UL, 0xa18e0cc3UL, 0x1bdf055aUL, + 0x8def022dUL + }, + { + 0x00000000UL, 0x41311b19UL, 0x82623632UL, 0xc3532d2bUL, 0x04c56c64UL, + 0x45f4777dUL, 0x86a75a56UL, 0xc796414fUL, 0x088ad9c8UL, 0x49bbc2d1UL, + 0x8ae8effaUL, 0xcbd9f4e3UL, 0x0c4fb5acUL, 0x4d7eaeb5UL, 0x8e2d839eUL, + 0xcf1c9887UL, 0x5112c24aUL, 0x1023d953UL, 0xd370f478UL, 0x9241ef61UL, + 0x55d7ae2eUL, 0x14e6b537UL, 0xd7b5981cUL, 0x96848305UL, 0x59981b82UL, + 0x18a9009bUL, 0xdbfa2db0UL, 0x9acb36a9UL, 0x5d5d77e6UL, 0x1c6c6cffUL, + 0xdf3f41d4UL, 0x9e0e5acdUL, 0xa2248495UL, 0xe3159f8cUL, 0x2046b2a7UL, + 0x6177a9beUL, 0xa6e1e8f1UL, 0xe7d0f3e8UL, 0x2483dec3UL, 0x65b2c5daUL, + 0xaaae5d5dUL, 0xeb9f4644UL, 0x28cc6b6fUL, 0x69fd7076UL, 0xae6b3139UL, + 0xef5a2a20UL, 0x2c09070bUL, 0x6d381c12UL, 0xf33646dfUL, 0xb2075dc6UL, + 0x715470edUL, 0x30656bf4UL, 0xf7f32abbUL, 0xb6c231a2UL, 0x75911c89UL, + 0x34a00790UL, 0xfbbc9f17UL, 0xba8d840eUL, 0x79dea925UL, 0x38efb23cUL, + 0xff79f373UL, 0xbe48e86aUL, 0x7d1bc541UL, 0x3c2ade58UL, 0x054f79f0UL, + 0x447e62e9UL, 0x872d4fc2UL, 0xc61c54dbUL, 0x018a1594UL, 0x40bb0e8dUL, + 0x83e823a6UL, 0xc2d938bfUL, 0x0dc5a038UL, 0x4cf4bb21UL, 0x8fa7960aUL, + 0xce968d13UL, 0x0900cc5cUL, 0x4831d745UL, 0x8b62fa6eUL, 0xca53e177UL, + 0x545dbbbaUL, 0x156ca0a3UL, 0xd63f8d88UL, 0x970e9691UL, 0x5098d7deUL, + 0x11a9ccc7UL, 0xd2fae1ecUL, 0x93cbfaf5UL, 0x5cd76272UL, 0x1de6796bUL, + 0xdeb55440UL, 0x9f844f59UL, 0x58120e16UL, 0x1923150fUL, 0xda703824UL, + 0x9b41233dUL, 0xa76bfd65UL, 0xe65ae67cUL, 0x2509cb57UL, 0x6438d04eUL, + 0xa3ae9101UL, 0xe29f8a18UL, 0x21cca733UL, 0x60fdbc2aUL, 0xafe124adUL, + 0xeed03fb4UL, 0x2d83129fUL, 0x6cb20986UL, 0xab2448c9UL, 0xea1553d0UL, + 0x29467efbUL, 0x687765e2UL, 0xf6793f2fUL, 0xb7482436UL, 0x741b091dUL, + 0x352a1204UL, 0xf2bc534bUL, 0xb38d4852UL, 0x70de6579UL, 0x31ef7e60UL, + 0xfef3e6e7UL, 0xbfc2fdfeUL, 0x7c91d0d5UL, 0x3da0cbccUL, 0xfa368a83UL, + 0xbb07919aUL, 0x7854bcb1UL, 0x3965a7a8UL, 0x4b98833bUL, 0x0aa99822UL, + 0xc9fab509UL, 0x88cbae10UL, 0x4f5def5fUL, 0x0e6cf446UL, 0xcd3fd96dUL, + 0x8c0ec274UL, 0x43125af3UL, 0x022341eaUL, 0xc1706cc1UL, 0x804177d8UL, + 0x47d73697UL, 0x06e62d8eUL, 0xc5b500a5UL, 0x84841bbcUL, 0x1a8a4171UL, + 0x5bbb5a68UL, 0x98e87743UL, 0xd9d96c5aUL, 0x1e4f2d15UL, 0x5f7e360cUL, + 0x9c2d1b27UL, 0xdd1c003eUL, 0x120098b9UL, 0x533183a0UL, 0x9062ae8bUL, + 0xd153b592UL, 0x16c5f4ddUL, 0x57f4efc4UL, 0x94a7c2efUL, 0xd596d9f6UL, + 0xe9bc07aeUL, 0xa88d1cb7UL, 0x6bde319cUL, 0x2aef2a85UL, 0xed796bcaUL, + 0xac4870d3UL, 0x6f1b5df8UL, 0x2e2a46e1UL, 0xe136de66UL, 0xa007c57fUL, + 0x6354e854UL, 0x2265f34dUL, 0xe5f3b202UL, 0xa4c2a91bUL, 0x67918430UL, + 0x26a09f29UL, 0xb8aec5e4UL, 0xf99fdefdUL, 0x3accf3d6UL, 0x7bfde8cfUL, + 0xbc6ba980UL, 0xfd5ab299UL, 0x3e099fb2UL, 0x7f3884abUL, 0xb0241c2cUL, + 0xf1150735UL, 0x32462a1eUL, 0x73773107UL, 0xb4e17048UL, 0xf5d06b51UL, + 0x3683467aUL, 0x77b25d63UL, 0x4ed7facbUL, 0x0fe6e1d2UL, 0xccb5ccf9UL, + 0x8d84d7e0UL, 0x4a1296afUL, 0x0b238db6UL, 0xc870a09dUL, 0x8941bb84UL, + 0x465d2303UL, 0x076c381aUL, 0xc43f1531UL, 0x850e0e28UL, 0x42984f67UL, + 0x03a9547eUL, 0xc0fa7955UL, 0x81cb624cUL, 0x1fc53881UL, 0x5ef42398UL, + 0x9da70eb3UL, 0xdc9615aaUL, 0x1b0054e5UL, 0x5a314ffcUL, 0x996262d7UL, + 0xd85379ceUL, 0x174fe149UL, 0x567efa50UL, 0x952dd77bUL, 0xd41ccc62UL, + 0x138a8d2dUL, 0x52bb9634UL, 0x91e8bb1fUL, 0xd0d9a006UL, 0xecf37e5eUL, + 0xadc26547UL, 0x6e91486cUL, 0x2fa05375UL, 0xe836123aUL, 0xa9070923UL, + 0x6a542408UL, 0x2b653f11UL, 0xe479a796UL, 0xa548bc8fUL, 0x661b91a4UL, + 0x272a8abdUL, 0xe0bccbf2UL, 0xa18dd0ebUL, 0x62defdc0UL, 0x23efe6d9UL, + 0xbde1bc14UL, 0xfcd0a70dUL, 0x3f838a26UL, 0x7eb2913fUL, 0xb924d070UL, + 0xf815cb69UL, 0x3b46e642UL, 0x7a77fd5bUL, 0xb56b65dcUL, 0xf45a7ec5UL, + 0x370953eeUL, 0x763848f7UL, 0xb1ae09b8UL, 0xf09f12a1UL, 0x33cc3f8aUL, + 0x72fd2493UL + }, + { + 0x00000000UL, 0x376ac201UL, 0x6ed48403UL, 0x59be4602UL, 0xdca80907UL, + 0xebc2cb06UL, 0xb27c8d04UL, 0x85164f05UL, 0xb851130eUL, 0x8f3bd10fUL, + 0xd685970dUL, 0xe1ef550cUL, 0x64f91a09UL, 0x5393d808UL, 0x0a2d9e0aUL, + 0x3d475c0bUL, 0x70a3261cUL, 0x47c9e41dUL, 0x1e77a21fUL, 0x291d601eUL, + 0xac0b2f1bUL, 0x9b61ed1aUL, 0xc2dfab18UL, 0xf5b56919UL, 0xc8f23512UL, + 0xff98f713UL, 0xa626b111UL, 0x914c7310UL, 0x145a3c15UL, 0x2330fe14UL, + 0x7a8eb816UL, 0x4de47a17UL, 0xe0464d38UL, 0xd72c8f39UL, 0x8e92c93bUL, + 0xb9f80b3aUL, 0x3cee443fUL, 0x0b84863eUL, 0x523ac03cUL, 0x6550023dUL, + 0x58175e36UL, 0x6f7d9c37UL, 0x36c3da35UL, 0x01a91834UL, 0x84bf5731UL, + 0xb3d59530UL, 0xea6bd332UL, 0xdd011133UL, 0x90e56b24UL, 0xa78fa925UL, + 0xfe31ef27UL, 0xc95b2d26UL, 0x4c4d6223UL, 0x7b27a022UL, 0x2299e620UL, + 0x15f32421UL, 0x28b4782aUL, 0x1fdeba2bUL, 0x4660fc29UL, 0x710a3e28UL, + 0xf41c712dUL, 0xc376b32cUL, 0x9ac8f52eUL, 0xada2372fUL, 0xc08d9a70UL, + 0xf7e75871UL, 0xae591e73UL, 0x9933dc72UL, 0x1c259377UL, 0x2b4f5176UL, + 0x72f11774UL, 0x459bd575UL, 0x78dc897eUL, 0x4fb64b7fUL, 0x16080d7dUL, + 0x2162cf7cUL, 0xa4748079UL, 0x931e4278UL, 0xcaa0047aUL, 0xfdcac67bUL, + 0xb02ebc6cUL, 0x87447e6dUL, 0xdefa386fUL, 0xe990fa6eUL, 0x6c86b56bUL, + 0x5bec776aUL, 0x02523168UL, 0x3538f369UL, 0x087faf62UL, 0x3f156d63UL, + 0x66ab2b61UL, 0x51c1e960UL, 0xd4d7a665UL, 0xe3bd6464UL, 0xba032266UL, + 0x8d69e067UL, 0x20cbd748UL, 0x17a11549UL, 0x4e1f534bUL, 0x7975914aUL, + 0xfc63de4fUL, 0xcb091c4eUL, 0x92b75a4cUL, 0xa5dd984dUL, 0x989ac446UL, + 0xaff00647UL, 0xf64e4045UL, 0xc1248244UL, 0x4432cd41UL, 0x73580f40UL, + 0x2ae64942UL, 0x1d8c8b43UL, 0x5068f154UL, 0x67023355UL, 0x3ebc7557UL, + 0x09d6b756UL, 0x8cc0f853UL, 0xbbaa3a52UL, 0xe2147c50UL, 0xd57ebe51UL, + 0xe839e25aUL, 0xdf53205bUL, 0x86ed6659UL, 0xb187a458UL, 0x3491eb5dUL, + 0x03fb295cUL, 0x5a456f5eUL, 0x6d2fad5fUL, 0x801b35e1UL, 0xb771f7e0UL, + 0xeecfb1e2UL, 0xd9a573e3UL, 0x5cb33ce6UL, 0x6bd9fee7UL, 0x3267b8e5UL, + 0x050d7ae4UL, 0x384a26efUL, 0x0f20e4eeUL, 0x569ea2ecUL, 0x61f460edUL, + 0xe4e22fe8UL, 0xd388ede9UL, 0x8a36abebUL, 0xbd5c69eaUL, 0xf0b813fdUL, + 0xc7d2d1fcUL, 0x9e6c97feUL, 0xa90655ffUL, 0x2c101afaUL, 0x1b7ad8fbUL, + 0x42c49ef9UL, 0x75ae5cf8UL, 0x48e900f3UL, 0x7f83c2f2UL, 0x263d84f0UL, + 0x115746f1UL, 0x944109f4UL, 0xa32bcbf5UL, 0xfa958df7UL, 0xcdff4ff6UL, + 0x605d78d9UL, 0x5737bad8UL, 0x0e89fcdaUL, 0x39e33edbUL, 0xbcf571deUL, + 0x8b9fb3dfUL, 0xd221f5ddUL, 0xe54b37dcUL, 0xd80c6bd7UL, 0xef66a9d6UL, + 0xb6d8efd4UL, 0x81b22dd5UL, 0x04a462d0UL, 0x33cea0d1UL, 0x6a70e6d3UL, + 0x5d1a24d2UL, 0x10fe5ec5UL, 0x27949cc4UL, 0x7e2adac6UL, 0x494018c7UL, + 0xcc5657c2UL, 0xfb3c95c3UL, 0xa282d3c1UL, 0x95e811c0UL, 0xa8af4dcbUL, + 0x9fc58fcaUL, 0xc67bc9c8UL, 0xf1110bc9UL, 0x740744ccUL, 0x436d86cdUL, + 0x1ad3c0cfUL, 0x2db902ceUL, 0x4096af91UL, 0x77fc6d90UL, 0x2e422b92UL, + 0x1928e993UL, 0x9c3ea696UL, 0xab546497UL, 0xf2ea2295UL, 0xc580e094UL, + 0xf8c7bc9fUL, 0xcfad7e9eUL, 0x9613389cUL, 0xa179fa9dUL, 0x246fb598UL, + 0x13057799UL, 0x4abb319bUL, 0x7dd1f39aUL, 0x3035898dUL, 0x075f4b8cUL, + 0x5ee10d8eUL, 0x698bcf8fUL, 0xec9d808aUL, 0xdbf7428bUL, 0x82490489UL, + 0xb523c688UL, 0x88649a83UL, 0xbf0e5882UL, 0xe6b01e80UL, 0xd1dadc81UL, + 0x54cc9384UL, 0x63a65185UL, 0x3a181787UL, 0x0d72d586UL, 0xa0d0e2a9UL, + 0x97ba20a8UL, 0xce0466aaUL, 0xf96ea4abUL, 0x7c78ebaeUL, 0x4b1229afUL, + 0x12ac6fadUL, 0x25c6adacUL, 0x1881f1a7UL, 0x2feb33a6UL, 0x765575a4UL, + 0x413fb7a5UL, 0xc429f8a0UL, 0xf3433aa1UL, 0xaafd7ca3UL, 0x9d97bea2UL, + 0xd073c4b5UL, 0xe71906b4UL, 0xbea740b6UL, 0x89cd82b7UL, 0x0cdbcdb2UL, + 0x3bb10fb3UL, 0x620f49b1UL, 0x55658bb0UL, 0x6822d7bbUL, 0x5f4815baUL, + 0x06f653b8UL, 0x319c91b9UL, 0xb48adebcUL, 0x83e01cbdUL, 0xda5e5abfUL, + 0xed3498beUL + }, + { + 0x00000000UL, 0x6567bcb8UL, 0x8bc809aaUL, 0xeeafb512UL, 0x5797628fUL, + 0x32f0de37UL, 0xdc5f6b25UL, 0xb938d79dUL, 0xef28b4c5UL, 0x8a4f087dUL, + 0x64e0bd6fUL, 0x018701d7UL, 0xb8bfd64aUL, 0xddd86af2UL, 0x3377dfe0UL, + 0x56106358UL, 0x9f571950UL, 0xfa30a5e8UL, 0x149f10faUL, 0x71f8ac42UL, + 0xc8c07bdfUL, 0xada7c767UL, 0x43087275UL, 0x266fcecdUL, 0x707fad95UL, + 0x1518112dUL, 0xfbb7a43fUL, 0x9ed01887UL, 0x27e8cf1aUL, 0x428f73a2UL, + 0xac20c6b0UL, 0xc9477a08UL, 0x3eaf32a0UL, 0x5bc88e18UL, 0xb5673b0aUL, + 0xd00087b2UL, 0x6938502fUL, 0x0c5fec97UL, 0xe2f05985UL, 0x8797e53dUL, + 0xd1878665UL, 0xb4e03addUL, 0x5a4f8fcfUL, 0x3f283377UL, 0x8610e4eaUL, + 0xe3775852UL, 0x0dd8ed40UL, 0x68bf51f8UL, 0xa1f82bf0UL, 0xc49f9748UL, + 0x2a30225aUL, 0x4f579ee2UL, 0xf66f497fUL, 0x9308f5c7UL, 0x7da740d5UL, + 0x18c0fc6dUL, 0x4ed09f35UL, 0x2bb7238dUL, 0xc518969fUL, 0xa07f2a27UL, + 0x1947fdbaUL, 0x7c204102UL, 0x928ff410UL, 0xf7e848a8UL, 0x3d58149bUL, + 0x583fa823UL, 0xb6901d31UL, 0xd3f7a189UL, 0x6acf7614UL, 0x0fa8caacUL, + 0xe1077fbeUL, 0x8460c306UL, 0xd270a05eUL, 0xb7171ce6UL, 0x59b8a9f4UL, + 0x3cdf154cUL, 0x85e7c2d1UL, 0xe0807e69UL, 0x0e2fcb7bUL, 0x6b4877c3UL, + 0xa20f0dcbUL, 0xc768b173UL, 0x29c70461UL, 0x4ca0b8d9UL, 0xf5986f44UL, + 0x90ffd3fcUL, 0x7e5066eeUL, 0x1b37da56UL, 0x4d27b90eUL, 0x284005b6UL, + 0xc6efb0a4UL, 0xa3880c1cUL, 0x1ab0db81UL, 0x7fd76739UL, 0x9178d22bUL, + 0xf41f6e93UL, 0x03f7263bUL, 0x66909a83UL, 0x883f2f91UL, 0xed589329UL, + 0x546044b4UL, 0x3107f80cUL, 0xdfa84d1eUL, 0xbacff1a6UL, 0xecdf92feUL, + 0x89b82e46UL, 0x67179b54UL, 0x027027ecUL, 0xbb48f071UL, 0xde2f4cc9UL, + 0x3080f9dbUL, 0x55e74563UL, 0x9ca03f6bUL, 0xf9c783d3UL, 0x176836c1UL, + 0x720f8a79UL, 0xcb375de4UL, 0xae50e15cUL, 0x40ff544eUL, 0x2598e8f6UL, + 0x73888baeUL, 0x16ef3716UL, 0xf8408204UL, 0x9d273ebcUL, 0x241fe921UL, + 0x41785599UL, 0xafd7e08bUL, 0xcab05c33UL, 0x3bb659edUL, 0x5ed1e555UL, + 0xb07e5047UL, 0xd519ecffUL, 0x6c213b62UL, 0x094687daUL, 0xe7e932c8UL, + 0x828e8e70UL, 0xd49eed28UL, 0xb1f95190UL, 0x5f56e482UL, 0x3a31583aUL, + 0x83098fa7UL, 0xe66e331fUL, 0x08c1860dUL, 0x6da63ab5UL, 0xa4e140bdUL, + 0xc186fc05UL, 0x2f294917UL, 0x4a4ef5afUL, 0xf3762232UL, 0x96119e8aUL, + 0x78be2b98UL, 0x1dd99720UL, 0x4bc9f478UL, 0x2eae48c0UL, 0xc001fdd2UL, + 0xa566416aUL, 0x1c5e96f7UL, 0x79392a4fUL, 0x97969f5dUL, 0xf2f123e5UL, + 0x05196b4dUL, 0x607ed7f5UL, 0x8ed162e7UL, 0xebb6de5fUL, 0x528e09c2UL, + 0x37e9b57aUL, 0xd9460068UL, 0xbc21bcd0UL, 0xea31df88UL, 0x8f566330UL, + 0x61f9d622UL, 0x049e6a9aUL, 0xbda6bd07UL, 0xd8c101bfUL, 0x366eb4adUL, + 0x53090815UL, 0x9a4e721dUL, 0xff29cea5UL, 0x11867bb7UL, 0x74e1c70fUL, + 0xcdd91092UL, 0xa8beac2aUL, 0x46111938UL, 0x2376a580UL, 0x7566c6d8UL, + 0x10017a60UL, 0xfeaecf72UL, 0x9bc973caUL, 0x22f1a457UL, 0x479618efUL, + 0xa939adfdUL, 0xcc5e1145UL, 0x06ee4d76UL, 0x6389f1ceUL, 0x8d2644dcUL, + 0xe841f864UL, 0x51792ff9UL, 0x341e9341UL, 0xdab12653UL, 0xbfd69aebUL, + 0xe9c6f9b3UL, 0x8ca1450bUL, 0x620ef019UL, 0x07694ca1UL, 0xbe519b3cUL, + 0xdb362784UL, 0x35999296UL, 0x50fe2e2eUL, 0x99b95426UL, 0xfcdee89eUL, + 0x12715d8cUL, 0x7716e134UL, 0xce2e36a9UL, 0xab498a11UL, 0x45e63f03UL, + 0x208183bbUL, 0x7691e0e3UL, 0x13f65c5bUL, 0xfd59e949UL, 0x983e55f1UL, + 0x2106826cUL, 0x44613ed4UL, 0xaace8bc6UL, 0xcfa9377eUL, 0x38417fd6UL, + 0x5d26c36eUL, 0xb389767cUL, 0xd6eecac4UL, 0x6fd61d59UL, 0x0ab1a1e1UL, + 0xe41e14f3UL, 0x8179a84bUL, 0xd769cb13UL, 0xb20e77abUL, 0x5ca1c2b9UL, + 0x39c67e01UL, 0x80fea99cUL, 0xe5991524UL, 0x0b36a036UL, 0x6e511c8eUL, + 0xa7166686UL, 0xc271da3eUL, 0x2cde6f2cUL, 0x49b9d394UL, 0xf0810409UL, + 0x95e6b8b1UL, 0x7b490da3UL, 0x1e2eb11bUL, 0x483ed243UL, 0x2d596efbUL, + 0xc3f6dbe9UL, 0xa6916751UL, 0x1fa9b0ccUL, 0x7ace0c74UL, 0x9461b966UL, + 0xf10605deUL +#endif + } +}; diff --git a/Foundation/src/deflate.c b/Foundation/src/deflate.c index 58091fd5c..38222c664 100644 --- a/Foundation/src/deflate.c +++ b/Foundation/src/deflate.c @@ -1,1736 +1,1736 @@ -/* deflate.c -- compress data using the deflation algorithm - * Copyright (C) 1995-2005 Jean-loup Gailly. - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -/* - * ALGORITHM - * - * The "deflation" process depends on being able to identify portions - * of the input text which are identical to earlier input (within a - * sliding window trailing behind the input currently being processed). - * - * The most straightforward technique turns out to be the fastest for - * most input files: try all possible matches and select the longest. - * The key feature of this algorithm is that insertions into the string - * dictionary are very simple and thus fast, and deletions are avoided - * completely. Insertions are performed at each input character, whereas - * string matches are performed only when the previous match ends. So it - * is preferable to spend more time in matches to allow very fast string - * insertions and avoid deletions. The matching algorithm for small - * strings is inspired from that of Rabin & Karp. A brute force approach - * is used to find longer strings when a small match has been found. - * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze - * (by Leonid Broukhis). - * A previous version of this file used a more sophisticated algorithm - * (by Fiala and Greene) which is guaranteed to run in linear amortized - * time, but has a larger average cost, uses more memory and is patented. - * However the F&G algorithm may be faster for some highly redundant - * files if the parameter max_chain_length (described below) is too large. - * - * ACKNOWLEDGEMENTS - * - * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and - * I found it in 'freeze' written by Leonid Broukhis. - * Thanks to many people for bug reports and testing. - * - * REFERENCES - * - * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification". - * Available in http://www.ietf.org/rfc/rfc1951.txt - * - * A description of the Rabin and Karp algorithm is given in the book - * "Algorithms" by R. Sedgewick, Addison-Wesley, p252. - * - * Fiala,E.R., and Greene,D.H. - * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595 - * - */ - -/* @(#) $Id: //poco/1.2/Foundation/src/deflate.c#1 $ */ - -#include "deflate.h" - -const char deflate_copyright[] = - " deflate 1.2.3 Copyright 1995-2005 Jean-loup Gailly "; -/* - If you use the zlib library in a product, an acknowledgment is welcome - in the documentation of your product. If for some reason you cannot - include such an acknowledgment, I would appreciate that you keep this - copyright string in the executable of your product. - */ - -/* =========================================================================== - * Function prototypes. - */ -typedef enum { - need_more, /* block not completed, need more input or more output */ - block_done, /* block flush performed */ - finish_started, /* finish started, need only more output at next deflate */ - finish_done /* finish done, accept no more input or output */ -} block_state; - -typedef block_state (*compress_func) OF((deflate_state *s, int flush)); -/* Compression function. Returns the block state after the call. */ - -local void fill_window OF((deflate_state *s)); -local block_state deflate_stored OF((deflate_state *s, int flush)); -local block_state deflate_fast OF((deflate_state *s, int flush)); -#ifndef FASTEST -local block_state deflate_slow OF((deflate_state *s, int flush)); -#endif -local void lm_init OF((deflate_state *s)); -local void putShortMSB OF((deflate_state *s, uInt b)); -local void flush_pending OF((z_streamp strm)); -local int read_buf OF((z_streamp strm, Bytef *buf, unsigned size)); -#ifndef FASTEST -#ifdef ASMV - void match_init OF((void)); /* asm code initialization */ - uInt longest_match OF((deflate_state *s, IPos cur_match)); -#else -local uInt longest_match OF((deflate_state *s, IPos cur_match)); -#endif -#endif -local uInt longest_match_fast OF((deflate_state *s, IPos cur_match)); - -#ifdef DEBUG -local void check_match OF((deflate_state *s, IPos start, IPos match, - int length)); -#endif - -/* =========================================================================== - * Local data - */ - -#define NIL 0 -/* Tail of hash chains */ - -#ifndef TOO_FAR -# define TOO_FAR 4096 -#endif -/* Matches of length 3 are discarded if their distance exceeds TOO_FAR */ - -#define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1) -/* Minimum amount of lookahead, except at the end of the input file. - * See deflate.c for comments about the MIN_MATCH+1. - */ - -/* Values for max_lazy_match, good_match and max_chain_length, depending on - * the desired pack level (0..9). The values given below have been tuned to - * exclude worst case performance for pathological files. Better values may be - * found for specific files. - */ -typedef struct config_s { - ush good_length; /* reduce lazy search above this match length */ - ush max_lazy; /* do not perform lazy search above this match length */ - ush nice_length; /* quit search above this match length */ - ush max_chain; - compress_func func; -} config; - -#ifdef FASTEST -local const config configuration_table[2] = { -/* good lazy nice chain */ -/* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */ -/* 1 */ {4, 4, 8, 4, deflate_fast}}; /* max speed, no lazy matches */ -#else -local const config configuration_table[10] = { -/* good lazy nice chain */ -/* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */ -/* 1 */ {4, 4, 8, 4, deflate_fast}, /* max speed, no lazy matches */ -/* 2 */ {4, 5, 16, 8, deflate_fast}, -/* 3 */ {4, 6, 32, 32, deflate_fast}, - -/* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */ -/* 5 */ {8, 16, 32, 32, deflate_slow}, -/* 6 */ {8, 16, 128, 128, deflate_slow}, -/* 7 */ {8, 32, 128, 256, deflate_slow}, -/* 8 */ {32, 128, 258, 1024, deflate_slow}, -/* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */ -#endif - -/* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4 - * For deflate_fast() (levels <= 3) good is ignored and lazy has a different - * meaning. - */ - -#define EQUAL 0 -/* result of memcmp for equal strings */ - -#ifndef NO_DUMMY_DECL -struct static_tree_desc_s {int dummy;}; /* for buggy compilers */ -#endif - -/* =========================================================================== - * Update a hash value with the given input byte - * IN assertion: all calls to to UPDATE_HASH are made with consecutive - * input characters, so that a running hash key can be computed from the - * previous key instead of complete recalculation each time. - */ -#define UPDATE_HASH(s,h,c) (h = (((h)<hash_shift) ^ (c)) & s->hash_mask) - - -/* =========================================================================== - * Insert string str in the dictionary and set match_head to the previous head - * of the hash chain (the most recent string with same hash key). Return - * the previous length of the hash chain. - * If this file is compiled with -DFASTEST, the compression level is forced - * to 1, and no hash chains are maintained. - * IN assertion: all calls to to INSERT_STRING are made with consecutive - * input characters and the first MIN_MATCH bytes of str are valid - * (except for the last MIN_MATCH-1 bytes of the input file). - */ -#ifdef FASTEST -#define INSERT_STRING(s, str, match_head) \ - (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \ - match_head = s->head[s->ins_h], \ - s->head[s->ins_h] = (Pos)(str)) -#else -#define INSERT_STRING(s, str, match_head) \ - (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \ - match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \ - s->head[s->ins_h] = (Pos)(str)) -#endif - -/* =========================================================================== - * Initialize the hash table (avoiding 64K overflow for 16 bit systems). - * prev[] will be initialized on the fly. - */ -#define CLEAR_HASH(s) \ - s->head[s->hash_size-1] = NIL; \ - zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head)); - -/* ========================================================================= */ -int ZEXPORT deflateInit_(strm, level, version, stream_size) - z_streamp strm; - int level; - const char *version; - int stream_size; -{ - return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, - Z_DEFAULT_STRATEGY, version, stream_size); - /* To do: ignore strm->next_in if we use it as window */ -} - -/* ========================================================================= */ -int ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy, - version, stream_size) - z_streamp strm; - int level; - int method; - int windowBits; - int memLevel; - int strategy; - const char *version; - int stream_size; -{ - deflate_state *s; - int wrap = 1; - static const char my_version[] = ZLIB_VERSION; - - ushf *overlay; - /* We overlay pending_buf and d_buf+l_buf. This works since the average - * output size for (length,distance) codes is <= 24 bits. - */ - - if (version == Z_NULL || version[0] != my_version[0] || - stream_size != sizeof(z_stream)) { - return Z_VERSION_ERROR; - } - if (strm == Z_NULL) return Z_STREAM_ERROR; - - strm->msg = Z_NULL; - if (strm->zalloc == (alloc_func)0) { - strm->zalloc = zcalloc; - strm->opaque = (voidpf)0; - } - if (strm->zfree == (free_func)0) strm->zfree = zcfree; - -#ifdef FASTEST - if (level != 0) level = 1; -#else - if (level == Z_DEFAULT_COMPRESSION) level = 6; -#endif - - if (windowBits < 0) { /* suppress zlib wrapper */ - wrap = 0; - windowBits = -windowBits; - } -#ifdef GZIP - else if (windowBits > 15) { - wrap = 2; /* write gzip wrapper instead */ - windowBits -= 16; - } -#endif - if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED || - windowBits < 8 || windowBits > 15 || level < 0 || level > 9 || - strategy < 0 || strategy > Z_FIXED) { - return Z_STREAM_ERROR; - } - if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */ - s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state)); - if (s == Z_NULL) return Z_MEM_ERROR; - strm->state = (struct internal_state FAR *)s; - s->strm = strm; - - s->wrap = wrap; - s->gzhead = Z_NULL; - s->w_bits = windowBits; - s->w_size = 1 << s->w_bits; - s->w_mask = s->w_size - 1; - - s->hash_bits = memLevel + 7; - s->hash_size = 1 << s->hash_bits; - s->hash_mask = s->hash_size - 1; - s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH); - - s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte)); - s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos)); - s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos)); - - s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */ - - overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2); - s->pending_buf = (uchf *) overlay; - s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L); - - if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL || - s->pending_buf == Z_NULL) { - s->status = FINISH_STATE; - strm->msg = (char*)ERR_MSG(Z_MEM_ERROR); - deflateEnd (strm); - return Z_MEM_ERROR; - } - s->d_buf = overlay + s->lit_bufsize/sizeof(ush); - s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize; - - s->level = level; - s->strategy = strategy; - s->method = (Byte)method; - - return deflateReset(strm); -} - -/* ========================================================================= */ -int ZEXPORT deflateSetDictionary (strm, dictionary, dictLength) - z_streamp strm; - const Bytef *dictionary; - uInt dictLength; -{ - deflate_state *s; - uInt length = dictLength; - uInt n; - IPos hash_head = 0; - - if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL || - strm->state->wrap == 2 || - (strm->state->wrap == 1 && strm->state->status != INIT_STATE)) - return Z_STREAM_ERROR; - - s = strm->state; - if (s->wrap) - strm->adler = adler32(strm->adler, dictionary, dictLength); - - if (length < MIN_MATCH) return Z_OK; - if (length > MAX_DIST(s)) { - length = MAX_DIST(s); - dictionary += dictLength - length; /* use the tail of the dictionary */ - } - zmemcpy(s->window, dictionary, length); - s->strstart = length; - s->block_start = (long)length; - - /* Insert all strings in the hash table (except for the last two bytes). - * s->lookahead stays null, so s->ins_h will be recomputed at the next - * call of fill_window. - */ - s->ins_h = s->window[0]; - UPDATE_HASH(s, s->ins_h, s->window[1]); - for (n = 0; n <= length - MIN_MATCH; n++) { - INSERT_STRING(s, n, hash_head); - } - if (hash_head) hash_head = 0; /* to make compiler happy */ - return Z_OK; -} - -/* ========================================================================= */ -int ZEXPORT deflateReset (strm) - z_streamp strm; -{ - deflate_state *s; - - if (strm == Z_NULL || strm->state == Z_NULL || - strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) { - return Z_STREAM_ERROR; - } - - strm->total_in = strm->total_out = 0; - strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */ - strm->data_type = Z_UNKNOWN; - - s = (deflate_state *)strm->state; - s->pending = 0; - s->pending_out = s->pending_buf; - - if (s->wrap < 0) { - s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */ - } - s->status = s->wrap ? INIT_STATE : BUSY_STATE; - strm->adler = -#ifdef GZIP - s->wrap == 2 ? crc32(0L, Z_NULL, 0) : -#endif - adler32(0L, Z_NULL, 0); - s->last_flush = Z_NO_FLUSH; - - _tr_init(s); - lm_init(s); - - return Z_OK; -} - -/* ========================================================================= */ -int ZEXPORT deflateSetHeader (strm, head) - z_streamp strm; - gz_headerp head; -{ - if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; - if (strm->state->wrap != 2) return Z_STREAM_ERROR; - strm->state->gzhead = head; - return Z_OK; -} - -/* ========================================================================= */ -int ZEXPORT deflatePrime (strm, bits, value) - z_streamp strm; - int bits; - int value; -{ - if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; - strm->state->bi_valid = bits; - strm->state->bi_buf = (ush)(value & ((1 << bits) - 1)); - return Z_OK; -} - -/* ========================================================================= */ -int ZEXPORT deflateParams(strm, level, strategy) - z_streamp strm; - int level; - int strategy; -{ - deflate_state *s; - compress_func func; - int err = Z_OK; - - if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; - s = strm->state; - -#ifdef FASTEST - if (level != 0) level = 1; -#else - if (level == Z_DEFAULT_COMPRESSION) level = 6; -#endif - if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) { - return Z_STREAM_ERROR; - } - func = configuration_table[s->level].func; - - if (func != configuration_table[level].func && strm->total_in != 0) { - /* Flush the last buffer: */ - err = deflate(strm, Z_PARTIAL_FLUSH); - } - if (s->level != level) { - s->level = level; - s->max_lazy_match = configuration_table[level].max_lazy; - s->good_match = configuration_table[level].good_length; - s->nice_match = configuration_table[level].nice_length; - s->max_chain_length = configuration_table[level].max_chain; - } - s->strategy = strategy; - return err; -} - -/* ========================================================================= */ -int ZEXPORT deflateTune(strm, good_length, max_lazy, nice_length, max_chain) - z_streamp strm; - int good_length; - int max_lazy; - int nice_length; - int max_chain; -{ - deflate_state *s; - - if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; - s = strm->state; - s->good_match = good_length; - s->max_lazy_match = max_lazy; - s->nice_match = nice_length; - s->max_chain_length = max_chain; - return Z_OK; -} - -/* ========================================================================= - * For the default windowBits of 15 and memLevel of 8, this function returns - * a close to exact, as well as small, upper bound on the compressed size. - * They are coded as constants here for a reason--if the #define's are - * changed, then this function needs to be changed as well. The return - * value for 15 and 8 only works for those exact settings. - * - * For any setting other than those defaults for windowBits and memLevel, - * the value returned is a conservative worst case for the maximum expansion - * resulting from using fixed blocks instead of stored blocks, which deflate - * can emit on compressed data for some combinations of the parameters. - * - * This function could be more sophisticated to provide closer upper bounds - * for every combination of windowBits and memLevel, as well as wrap. - * But even the conservative upper bound of about 14% expansion does not - * seem onerous for output buffer allocation. - */ -uLong ZEXPORT deflateBound(strm, sourceLen) - z_streamp strm; - uLong sourceLen; -{ - deflate_state *s; - uLong destLen; - - /* conservative upper bound */ - destLen = sourceLen + - ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 11; - - /* if can't get parameters, return conservative bound */ - if (strm == Z_NULL || strm->state == Z_NULL) - return destLen; - - /* if not default parameters, return conservative bound */ - s = strm->state; - if (s->w_bits != 15 || s->hash_bits != 8 + 7) - return destLen; - - /* default settings: return tight bound for that case */ - return compressBound(sourceLen); -} - -/* ========================================================================= - * Put a short in the pending buffer. The 16-bit value is put in MSB order. - * IN assertion: the stream state is correct and there is enough room in - * pending_buf. - */ -local void putShortMSB (s, b) - deflate_state *s; - uInt b; -{ - put_byte(s, (Byte)(b >> 8)); - put_byte(s, (Byte)(b & 0xff)); -} - -/* ========================================================================= - * Flush as much pending output as possible. All deflate() output goes - * through this function so some applications may wish to modify it - * to avoid allocating a large strm->next_out buffer and copying into it. - * (See also read_buf()). - */ -local void flush_pending(strm) - z_streamp strm; -{ - unsigned len = strm->state->pending; - - if (len > strm->avail_out) len = strm->avail_out; - if (len == 0) return; - - zmemcpy(strm->next_out, strm->state->pending_out, len); - strm->next_out += len; - strm->state->pending_out += len; - strm->total_out += len; - strm->avail_out -= len; - strm->state->pending -= len; - if (strm->state->pending == 0) { - strm->state->pending_out = strm->state->pending_buf; - } -} - -/* ========================================================================= */ -int ZEXPORT deflate (strm, flush) - z_streamp strm; - int flush; -{ - int old_flush; /* value of flush param for previous deflate call */ - deflate_state *s; - - if (strm == Z_NULL || strm->state == Z_NULL || - flush > Z_FINISH || flush < 0) { - return Z_STREAM_ERROR; - } - s = strm->state; - - if (strm->next_out == Z_NULL || - (strm->next_in == Z_NULL && strm->avail_in != 0) || - (s->status == FINISH_STATE && flush != Z_FINISH)) { - ERR_RETURN(strm, Z_STREAM_ERROR); - } - if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR); - - s->strm = strm; /* just in case */ - old_flush = s->last_flush; - s->last_flush = flush; - - /* Write the header */ - if (s->status == INIT_STATE) { -#ifdef GZIP - if (s->wrap == 2) { - strm->adler = crc32(0L, Z_NULL, 0); - put_byte(s, 31); - put_byte(s, 139); - put_byte(s, 8); - if (s->gzhead == NULL) { - put_byte(s, 0); - put_byte(s, 0); - put_byte(s, 0); - put_byte(s, 0); - put_byte(s, 0); - put_byte(s, s->level == 9 ? 2 : - (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ? - 4 : 0)); - put_byte(s, OS_CODE); - s->status = BUSY_STATE; - } - else { - put_byte(s, (s->gzhead->text ? 1 : 0) + - (s->gzhead->hcrc ? 2 : 0) + - (s->gzhead->extra == Z_NULL ? 0 : 4) + - (s->gzhead->name == Z_NULL ? 0 : 8) + - (s->gzhead->comment == Z_NULL ? 0 : 16) - ); - put_byte(s, (Byte)(s->gzhead->time & 0xff)); - put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff)); - put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff)); - put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff)); - put_byte(s, s->level == 9 ? 2 : - (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ? - 4 : 0)); - put_byte(s, s->gzhead->os & 0xff); - if (s->gzhead->extra != NULL) { - put_byte(s, s->gzhead->extra_len & 0xff); - put_byte(s, (s->gzhead->extra_len >> 8) & 0xff); - } - if (s->gzhead->hcrc) - strm->adler = crc32(strm->adler, s->pending_buf, - s->pending); - s->gzindex = 0; - s->status = EXTRA_STATE; - } - } - else -#endif - { - uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8; - uInt level_flags; - - if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2) - level_flags = 0; - else if (s->level < 6) - level_flags = 1; - else if (s->level == 6) - level_flags = 2; - else - level_flags = 3; - header |= (level_flags << 6); - if (s->strstart != 0) header |= PRESET_DICT; - header += 31 - (header % 31); - - s->status = BUSY_STATE; - putShortMSB(s, header); - - /* Save the adler32 of the preset dictionary: */ - if (s->strstart != 0) { - putShortMSB(s, (uInt)(strm->adler >> 16)); - putShortMSB(s, (uInt)(strm->adler & 0xffff)); - } - strm->adler = adler32(0L, Z_NULL, 0); - } - } -#ifdef GZIP - if (s->status == EXTRA_STATE) { - if (s->gzhead->extra != NULL) { - uInt beg = s->pending; /* start of bytes to update crc */ - - while (s->gzindex < (s->gzhead->extra_len & 0xffff)) { - if (s->pending == s->pending_buf_size) { - if (s->gzhead->hcrc && s->pending > beg) - strm->adler = crc32(strm->adler, s->pending_buf + beg, - s->pending - beg); - flush_pending(strm); - beg = s->pending; - if (s->pending == s->pending_buf_size) - break; - } - put_byte(s, s->gzhead->extra[s->gzindex]); - s->gzindex++; - } - if (s->gzhead->hcrc && s->pending > beg) - strm->adler = crc32(strm->adler, s->pending_buf + beg, - s->pending - beg); - if (s->gzindex == s->gzhead->extra_len) { - s->gzindex = 0; - s->status = NAME_STATE; - } - } - else - s->status = NAME_STATE; - } - if (s->status == NAME_STATE) { - if (s->gzhead->name != NULL) { - uInt beg = s->pending; /* start of bytes to update crc */ - int val; - - do { - if (s->pending == s->pending_buf_size) { - if (s->gzhead->hcrc && s->pending > beg) - strm->adler = crc32(strm->adler, s->pending_buf + beg, - s->pending - beg); - flush_pending(strm); - beg = s->pending; - if (s->pending == s->pending_buf_size) { - val = 1; - break; - } - } - val = s->gzhead->name[s->gzindex++]; - put_byte(s, val); - } while (val != 0); - if (s->gzhead->hcrc && s->pending > beg) - strm->adler = crc32(strm->adler, s->pending_buf + beg, - s->pending - beg); - if (val == 0) { - s->gzindex = 0; - s->status = COMMENT_STATE; - } - } - else - s->status = COMMENT_STATE; - } - if (s->status == COMMENT_STATE) { - if (s->gzhead->comment != NULL) { - uInt beg = s->pending; /* start of bytes to update crc */ - int val; - - do { - if (s->pending == s->pending_buf_size) { - if (s->gzhead->hcrc && s->pending > beg) - strm->adler = crc32(strm->adler, s->pending_buf + beg, - s->pending - beg); - flush_pending(strm); - beg = s->pending; - if (s->pending == s->pending_buf_size) { - val = 1; - break; - } - } - val = s->gzhead->comment[s->gzindex++]; - put_byte(s, val); - } while (val != 0); - if (s->gzhead->hcrc && s->pending > beg) - strm->adler = crc32(strm->adler, s->pending_buf + beg, - s->pending - beg); - if (val == 0) - s->status = HCRC_STATE; - } - else - s->status = HCRC_STATE; - } - if (s->status == HCRC_STATE) { - if (s->gzhead->hcrc) { - if (s->pending + 2 > s->pending_buf_size) - flush_pending(strm); - if (s->pending + 2 <= s->pending_buf_size) { - put_byte(s, (Byte)(strm->adler & 0xff)); - put_byte(s, (Byte)((strm->adler >> 8) & 0xff)); - strm->adler = crc32(0L, Z_NULL, 0); - s->status = BUSY_STATE; - } - } - else - s->status = BUSY_STATE; - } -#endif - - /* Flush as much pending output as possible */ - if (s->pending != 0) { - flush_pending(strm); - if (strm->avail_out == 0) { - /* Since avail_out is 0, deflate will be called again with - * more output space, but possibly with both pending and - * avail_in equal to zero. There won't be anything to do, - * but this is not an error situation so make sure we - * return OK instead of BUF_ERROR at next call of deflate: - */ - s->last_flush = -1; - return Z_OK; - } - - /* Make sure there is something to do and avoid duplicate consecutive - * flushes. For repeated and useless calls with Z_FINISH, we keep - * returning Z_STREAM_END instead of Z_BUF_ERROR. - */ - } else if (strm->avail_in == 0 && flush <= old_flush && - flush != Z_FINISH) { - ERR_RETURN(strm, Z_BUF_ERROR); - } - - /* User must not provide more input after the first FINISH: */ - if (s->status == FINISH_STATE && strm->avail_in != 0) { - ERR_RETURN(strm, Z_BUF_ERROR); - } - - /* Start a new block or continue the current one. - */ - if (strm->avail_in != 0 || s->lookahead != 0 || - (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) { - block_state bstate; - - bstate = (*(configuration_table[s->level].func))(s, flush); - - if (bstate == finish_started || bstate == finish_done) { - s->status = FINISH_STATE; - } - if (bstate == need_more || bstate == finish_started) { - if (strm->avail_out == 0) { - s->last_flush = -1; /* avoid BUF_ERROR next call, see above */ - } - return Z_OK; - /* If flush != Z_NO_FLUSH && avail_out == 0, the next call - * of deflate should use the same flush parameter to make sure - * that the flush is complete. So we don't have to output an - * empty block here, this will be done at next call. This also - * ensures that for a very small output buffer, we emit at most - * one empty block. - */ - } - if (bstate == block_done) { - if (flush == Z_PARTIAL_FLUSH) { - _tr_align(s); - } else { /* FULL_FLUSH or SYNC_FLUSH */ - _tr_stored_block(s, (char*)0, 0L, 0); - /* For a full flush, this empty block will be recognized - * as a special marker by inflate_sync(). - */ - if (flush == Z_FULL_FLUSH) { - CLEAR_HASH(s); /* forget history */ - } - } - flush_pending(strm); - if (strm->avail_out == 0) { - s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */ - return Z_OK; - } - } - } - Assert(strm->avail_out > 0, "bug2"); - - if (flush != Z_FINISH) return Z_OK; - if (s->wrap <= 0) return Z_STREAM_END; - - /* Write the trailer */ -#ifdef GZIP - if (s->wrap == 2) { - put_byte(s, (Byte)(strm->adler & 0xff)); - put_byte(s, (Byte)((strm->adler >> 8) & 0xff)); - put_byte(s, (Byte)((strm->adler >> 16) & 0xff)); - put_byte(s, (Byte)((strm->adler >> 24) & 0xff)); - put_byte(s, (Byte)(strm->total_in & 0xff)); - put_byte(s, (Byte)((strm->total_in >> 8) & 0xff)); - put_byte(s, (Byte)((strm->total_in >> 16) & 0xff)); - put_byte(s, (Byte)((strm->total_in >> 24) & 0xff)); - } - else -#endif - { - putShortMSB(s, (uInt)(strm->adler >> 16)); - putShortMSB(s, (uInt)(strm->adler & 0xffff)); - } - flush_pending(strm); - /* If avail_out is zero, the application will call deflate again - * to flush the rest. - */ - if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */ - return s->pending != 0 ? Z_OK : Z_STREAM_END; -} - -/* ========================================================================= */ -int ZEXPORT deflateEnd (strm) - z_streamp strm; -{ - int status; - - if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; - - status = strm->state->status; - if (status != INIT_STATE && - status != EXTRA_STATE && - status != NAME_STATE && - status != COMMENT_STATE && - status != HCRC_STATE && - status != BUSY_STATE && - status != FINISH_STATE) { - return Z_STREAM_ERROR; - } - - /* Deallocate in reverse order of allocations: */ - TRY_FREE(strm, strm->state->pending_buf); - TRY_FREE(strm, strm->state->head); - TRY_FREE(strm, strm->state->prev); - TRY_FREE(strm, strm->state->window); - - ZFREE(strm, strm->state); - strm->state = Z_NULL; - - return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK; -} - -/* ========================================================================= - * Copy the source state to the destination state. - * To simplify the source, this is not supported for 16-bit MSDOS (which - * doesn't have enough memory anyway to duplicate compression states). - */ -int ZEXPORT deflateCopy (dest, source) - z_streamp dest; - z_streamp source; -{ -#ifdef MAXSEG_64K - return Z_STREAM_ERROR; -#else - deflate_state *ds; - deflate_state *ss; - ushf *overlay; - - - if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) { - return Z_STREAM_ERROR; - } - - ss = source->state; - - zmemcpy(dest, source, sizeof(z_stream)); - - ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state)); - if (ds == Z_NULL) return Z_MEM_ERROR; - dest->state = (struct internal_state FAR *) ds; - zmemcpy(ds, ss, sizeof(deflate_state)); - ds->strm = dest; - - ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte)); - ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos)); - ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos)); - overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2); - ds->pending_buf = (uchf *) overlay; - - if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL || - ds->pending_buf == Z_NULL) { - deflateEnd (dest); - return Z_MEM_ERROR; - } - /* following zmemcpy do not work for 16-bit MSDOS */ - zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte)); - zmemcpy(ds->prev, ss->prev, ds->w_size * sizeof(Pos)); - zmemcpy(ds->head, ss->head, ds->hash_size * sizeof(Pos)); - zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size); - - ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf); - ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush); - ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize; - - ds->l_desc.dyn_tree = ds->dyn_ltree; - ds->d_desc.dyn_tree = ds->dyn_dtree; - ds->bl_desc.dyn_tree = ds->bl_tree; - - return Z_OK; -#endif /* MAXSEG_64K */ -} - -/* =========================================================================== - * Read a new buffer from the current input stream, update the adler32 - * and total number of bytes read. All deflate() input goes through - * this function so some applications may wish to modify it to avoid - * allocating a large strm->next_in buffer and copying from it. - * (See also flush_pending()). - */ -local int read_buf(strm, buf, size) - z_streamp strm; - Bytef *buf; - unsigned size; -{ - unsigned len = strm->avail_in; - - if (len > size) len = size; - if (len == 0) return 0; - - strm->avail_in -= len; - - if (strm->state->wrap == 1) { - strm->adler = adler32(strm->adler, strm->next_in, len); - } -#ifdef GZIP - else if (strm->state->wrap == 2) { - strm->adler = crc32(strm->adler, strm->next_in, len); - } -#endif - zmemcpy(buf, strm->next_in, len); - strm->next_in += len; - strm->total_in += len; - - return (int)len; -} - -/* =========================================================================== - * Initialize the "longest match" routines for a new zlib stream - */ -local void lm_init (s) - deflate_state *s; -{ - s->window_size = (ulg)2L*s->w_size; - - CLEAR_HASH(s); - - /* Set the default configuration parameters: - */ - s->max_lazy_match = configuration_table[s->level].max_lazy; - s->good_match = configuration_table[s->level].good_length; - s->nice_match = configuration_table[s->level].nice_length; - s->max_chain_length = configuration_table[s->level].max_chain; - - s->strstart = 0; - s->block_start = 0L; - s->lookahead = 0; - s->match_length = s->prev_length = MIN_MATCH-1; - s->match_available = 0; - s->ins_h = 0; -#ifndef FASTEST -#ifdef ASMV - match_init(); /* initialize the asm code */ -#endif -#endif -} - -#ifndef FASTEST -/* =========================================================================== - * Set match_start to the longest match starting at the given string and - * return its length. Matches shorter or equal to prev_length are discarded, - * in which case the result is equal to prev_length and match_start is - * garbage. - * IN assertions: cur_match is the head of the hash chain for the current - * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1 - * OUT assertion: the match length is not greater than s->lookahead. - */ -#ifndef ASMV -/* For 80x86 and 680x0, an optimized version will be provided in match.asm or - * match.S. The code will be functionally equivalent. - */ -local uInt longest_match(s, cur_match) - deflate_state *s; - IPos cur_match; /* current match */ -{ - unsigned chain_length = s->max_chain_length;/* max hash chain length */ - register Bytef *scan = s->window + s->strstart; /* current string */ - register Bytef *match; /* matched string */ - register int len; /* length of current match */ - int best_len = s->prev_length; /* best match length so far */ - int nice_match = s->nice_match; /* stop if match long enough */ - IPos limit = s->strstart > (IPos)MAX_DIST(s) ? - s->strstart - (IPos)MAX_DIST(s) : NIL; - /* Stop when cur_match becomes <= limit. To simplify the code, - * we prevent matches with the string of window index 0. - */ - Posf *prev = s->prev; - uInt wmask = s->w_mask; - -#ifdef UNALIGNED_OK - /* Compare two bytes at a time. Note: this is not always beneficial. - * Try with and without -DUNALIGNED_OK to check. - */ - register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1; - register ush scan_start = *(ushf*)scan; - register ush scan_end = *(ushf*)(scan+best_len-1); -#else - register Bytef *strend = s->window + s->strstart + MAX_MATCH; - register Byte scan_end1 = scan[best_len-1]; - register Byte scan_end = scan[best_len]; -#endif - - /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. - * It is easy to get rid of this optimization if necessary. - */ - Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); - - /* Do not waste too much time if we already have a good match: */ - if (s->prev_length >= s->good_match) { - chain_length >>= 2; - } - /* Do not look for matches beyond the end of the input. This is necessary - * to make deflate deterministic. - */ - if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead; - - Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); - - do { - Assert(cur_match < s->strstart, "no future"); - match = s->window + cur_match; - - /* Skip to next match if the match length cannot increase - * or if the match length is less than 2. Note that the checks below - * for insufficient lookahead only occur occasionally for performance - * reasons. Therefore uninitialized memory will be accessed, and - * conditional jumps will be made that depend on those values. - * However the length of the match is limited to the lookahead, so - * the output of deflate is not affected by the uninitialized values. - */ -#if (defined(UNALIGNED_OK) && MAX_MATCH == 258) - /* This code assumes sizeof(unsigned short) == 2. Do not use - * UNALIGNED_OK if your compiler uses a different size. - */ - if (*(ushf*)(match+best_len-1) != scan_end || - *(ushf*)match != scan_start) continue; - - /* It is not necessary to compare scan[2] and match[2] since they are - * always equal when the other bytes match, given that the hash keys - * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at - * strstart+3, +5, ... up to strstart+257. We check for insufficient - * lookahead only every 4th comparison; the 128th check will be made - * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is - * necessary to put more guard bytes at the end of the window, or - * to check more often for insufficient lookahead. - */ - Assert(scan[2] == match[2], "scan[2]?"); - scan++, match++; - do { - } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) && - *(ushf*)(scan+=2) == *(ushf*)(match+=2) && - *(ushf*)(scan+=2) == *(ushf*)(match+=2) && - *(ushf*)(scan+=2) == *(ushf*)(match+=2) && - scan < strend); - /* The funny "do {}" generates better code on most compilers */ - - /* Here, scan <= window+strstart+257 */ - Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); - if (*scan == *match) scan++; - - len = (MAX_MATCH - 1) - (int)(strend-scan); - scan = strend - (MAX_MATCH-1); - -#else /* UNALIGNED_OK */ - - if (match[best_len] != scan_end || - match[best_len-1] != scan_end1 || - *match != *scan || - *++match != scan[1]) continue; - - /* The check at best_len-1 can be removed because it will be made - * again later. (This heuristic is not always a win.) - * It is not necessary to compare scan[2] and match[2] since they - * are always equal when the other bytes match, given that - * the hash keys are equal and that HASH_BITS >= 8. - */ - scan += 2, match++; - Assert(*scan == *match, "match[2]?"); - - /* We check for insufficient lookahead only every 8th comparison; - * the 256th check will be made at strstart+258. - */ - do { - } while (*++scan == *++match && *++scan == *++match && - *++scan == *++match && *++scan == *++match && - *++scan == *++match && *++scan == *++match && - *++scan == *++match && *++scan == *++match && - scan < strend); - - Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); - - len = MAX_MATCH - (int)(strend - scan); - scan = strend - MAX_MATCH; - -#endif /* UNALIGNED_OK */ - - if (len > best_len) { - s->match_start = cur_match; - best_len = len; - if (len >= nice_match) break; -#ifdef UNALIGNED_OK - scan_end = *(ushf*)(scan+best_len-1); -#else - scan_end1 = scan[best_len-1]; - scan_end = scan[best_len]; -#endif - } - } while ((cur_match = prev[cur_match & wmask]) > limit - && --chain_length != 0); - - if ((uInt)best_len <= s->lookahead) return (uInt)best_len; - return s->lookahead; -} -#endif /* ASMV */ -#endif /* FASTEST */ - -/* --------------------------------------------------------------------------- - * Optimized version for level == 1 or strategy == Z_RLE only - */ -local uInt longest_match_fast(s, cur_match) - deflate_state *s; - IPos cur_match; /* current match */ -{ - register Bytef *scan = s->window + s->strstart; /* current string */ - register Bytef *match; /* matched string */ - register int len; /* length of current match */ - register Bytef *strend = s->window + s->strstart + MAX_MATCH; - - /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. - * It is easy to get rid of this optimization if necessary. - */ - Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); - - Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); - - Assert(cur_match < s->strstart, "no future"); - - match = s->window + cur_match; - - /* Return failure if the match length is less than 2: - */ - if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1; - - /* The check at best_len-1 can be removed because it will be made - * again later. (This heuristic is not always a win.) - * It is not necessary to compare scan[2] and match[2] since they - * are always equal when the other bytes match, given that - * the hash keys are equal and that HASH_BITS >= 8. - */ - scan += 2, match += 2; - Assert(*scan == *match, "match[2]?"); - - /* We check for insufficient lookahead only every 8th comparison; - * the 256th check will be made at strstart+258. - */ - do { - } while (*++scan == *++match && *++scan == *++match && - *++scan == *++match && *++scan == *++match && - *++scan == *++match && *++scan == *++match && - *++scan == *++match && *++scan == *++match && - scan < strend); - - Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); - - len = MAX_MATCH - (int)(strend - scan); - - if (len < MIN_MATCH) return MIN_MATCH - 1; - - s->match_start = cur_match; - return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead; -} - -#ifdef DEBUG -/* =========================================================================== - * Check that the match at match_start is indeed a match. - */ -local void check_match(s, start, match, length) - deflate_state *s; - IPos start, match; - int length; -{ - /* check that the match is indeed a match */ - if (zmemcmp(s->window + match, - s->window + start, length) != EQUAL) { - fprintf(stderr, " start %u, match %u, length %d\n", - start, match, length); - do { - fprintf(stderr, "%c%c", s->window[match++], s->window[start++]); - } while (--length != 0); - z_error("invalid match"); - } - if (z_verbose > 1) { - fprintf(stderr,"\\[%d,%d]", start-match, length); - do { putc(s->window[start++], stderr); } while (--length != 0); - } -} -#else -# define check_match(s, start, match, length) -#endif /* DEBUG */ - -/* =========================================================================== - * Fill the window when the lookahead becomes insufficient. - * Updates strstart and lookahead. - * - * IN assertion: lookahead < MIN_LOOKAHEAD - * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD - * At least one byte has been read, or avail_in == 0; reads are - * performed for at least two bytes (required for the zip translate_eol - * option -- not supported here). - */ -local void fill_window(s) - deflate_state *s; -{ - register unsigned n, m; - register Posf *p; - unsigned more; /* Amount of free space at the end of the window. */ - uInt wsize = s->w_size; - - do { - more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart); - - /* Deal with !@#$% 64K limit: */ - if (sizeof(int) <= 2) { - if (more == 0 && s->strstart == 0 && s->lookahead == 0) { - more = wsize; - - } else if (more == (unsigned)(-1)) { - /* Very unlikely, but possible on 16 bit machine if - * strstart == 0 && lookahead == 1 (input done a byte at time) - */ - more--; - } - } - - /* If the window is almost full and there is insufficient lookahead, - * move the upper half to the lower one to make room in the upper half. - */ - if (s->strstart >= wsize+MAX_DIST(s)) { - - zmemcpy(s->window, s->window+wsize, (unsigned)wsize); - s->match_start -= wsize; - s->strstart -= wsize; /* we now have strstart >= MAX_DIST */ - s->block_start -= (long) wsize; - - /* Slide the hash table (could be avoided with 32 bit values - at the expense of memory usage). We slide even when level == 0 - to keep the hash table consistent if we switch back to level > 0 - later. (Using level 0 permanently is not an optimal usage of - zlib, so we don't care about this pathological case.) - */ - /* %%% avoid this when Z_RLE */ - n = s->hash_size; - p = &s->head[n]; - do { - m = *--p; - *p = (Pos)(m >= wsize ? m-wsize : NIL); - } while (--n); - - n = wsize; -#ifndef FASTEST - p = &s->prev[n]; - do { - m = *--p; - *p = (Pos)(m >= wsize ? m-wsize : NIL); - /* If n is not on any hash chain, prev[n] is garbage but - * its value will never be used. - */ - } while (--n); -#endif - more += wsize; - } - if (s->strm->avail_in == 0) return; - - /* If there was no sliding: - * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && - * more == window_size - lookahead - strstart - * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) - * => more >= window_size - 2*WSIZE + 2 - * In the BIG_MEM or MMAP case (not yet supported), - * window_size == input_size + MIN_LOOKAHEAD && - * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD. - * Otherwise, window_size == 2*WSIZE so more >= 2. - * If there was sliding, more >= WSIZE. So in all cases, more >= 2. - */ - Assert(more >= 2, "more < 2"); - - n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more); - s->lookahead += n; - - /* Initialize the hash value now that we have some input: */ - if (s->lookahead >= MIN_MATCH) { - s->ins_h = s->window[s->strstart]; - UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]); -#if MIN_MATCH != 3 - Call UPDATE_HASH() MIN_MATCH-3 more times -#endif - } - /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage, - * but this is not important since only literal bytes will be emitted. - */ - - } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0); -} - -/* =========================================================================== - * Flush the current block, with given end-of-file flag. - * IN assertion: strstart is set to the end of the current match. - */ -#define FLUSH_BLOCK_ONLY(s, eof) { \ - _tr_flush_block(s, (s->block_start >= 0L ? \ - (charf *)&s->window[(unsigned)s->block_start] : \ - (charf *)Z_NULL), \ - (ulg)((long)s->strstart - s->block_start), \ - (eof)); \ - s->block_start = s->strstart; \ - flush_pending(s->strm); \ - Tracev((stderr,"[FLUSH]")); \ -} - -/* Same but force premature exit if necessary. */ -#define FLUSH_BLOCK(s, eof) { \ - FLUSH_BLOCK_ONLY(s, eof); \ - if (s->strm->avail_out == 0) return (eof) ? finish_started : need_more; \ -} - -/* =========================================================================== - * Copy without compression as much as possible from the input stream, return - * the current block state. - * This function does not insert new strings in the dictionary since - * uncompressible data is probably not useful. This function is used - * only for the level=0 compression option. - * NOTE: this function should be optimized to avoid extra copying from - * window to pending_buf. - */ -local block_state deflate_stored(s, flush) - deflate_state *s; - int flush; -{ - /* Stored blocks are limited to 0xffff bytes, pending_buf is limited - * to pending_buf_size, and each stored block has a 5 byte header: - */ - ulg max_block_size = 0xffff; - ulg max_start; - - if (max_block_size > s->pending_buf_size - 5) { - max_block_size = s->pending_buf_size - 5; - } - - /* Copy as much as possible from input to output: */ - for (;;) { - /* Fill the window as much as possible: */ - if (s->lookahead <= 1) { - - Assert(s->strstart < s->w_size+MAX_DIST(s) || - s->block_start >= (long)s->w_size, "slide too late"); - - fill_window(s); - if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more; - - if (s->lookahead == 0) break; /* flush the current block */ - } - Assert(s->block_start >= 0L, "block gone"); - - s->strstart += s->lookahead; - s->lookahead = 0; - - /* Emit a stored block if pending_buf will be full: */ - max_start = s->block_start + max_block_size; - if (s->strstart == 0 || (ulg)s->strstart >= max_start) { - /* strstart == 0 is possible when wraparound on 16-bit machine */ - s->lookahead = (uInt)(s->strstart - max_start); - s->strstart = (uInt)max_start; - FLUSH_BLOCK(s, 0); - } - /* Flush if we may have to slide, otherwise block_start may become - * negative and the data will be gone: - */ - if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) { - FLUSH_BLOCK(s, 0); - } - } - FLUSH_BLOCK(s, flush == Z_FINISH); - return flush == Z_FINISH ? finish_done : block_done; -} - -/* =========================================================================== - * Compress as much as possible from the input stream, return the current - * block state. - * This function does not perform lazy evaluation of matches and inserts - * new strings in the dictionary only for unmatched strings or for short - * matches. It is used only for the fast compression options. - */ -local block_state deflate_fast(s, flush) - deflate_state *s; - int flush; -{ - IPos hash_head = NIL; /* head of the hash chain */ - int bflush; /* set if current block must be flushed */ - - for (;;) { - /* Make sure that we always have enough lookahead, except - * at the end of the input file. We need MAX_MATCH bytes - * for the next match, plus MIN_MATCH bytes to insert the - * string following the next match. - */ - if (s->lookahead < MIN_LOOKAHEAD) { - fill_window(s); - if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) { - return need_more; - } - if (s->lookahead == 0) break; /* flush the current block */ - } - - /* Insert the string window[strstart .. strstart+2] in the - * dictionary, and set hash_head to the head of the hash chain: - */ - if (s->lookahead >= MIN_MATCH) { - INSERT_STRING(s, s->strstart, hash_head); - } - - /* Find the longest match, discarding those <= prev_length. - * At this point we have always match_length < MIN_MATCH - */ - if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) { - /* To simplify the code, we prevent matches with the string - * of window index 0 (in particular we have to avoid a match - * of the string with itself at the start of the input file). - */ -#ifdef FASTEST - if ((s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) || - (s->strategy == Z_RLE && s->strstart - hash_head == 1)) { - s->match_length = longest_match_fast (s, hash_head); - } -#else - if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) { - s->match_length = longest_match (s, hash_head); - } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) { - s->match_length = longest_match_fast (s, hash_head); - } -#endif - /* longest_match() or longest_match_fast() sets match_start */ - } - if (s->match_length >= MIN_MATCH) { - check_match(s, s->strstart, s->match_start, s->match_length); - - _tr_tally_dist(s, s->strstart - s->match_start, - s->match_length - MIN_MATCH, bflush); - - s->lookahead -= s->match_length; - - /* Insert new strings in the hash table only if the match length - * is not too large. This saves time but degrades compression. - */ -#ifndef FASTEST - if (s->match_length <= s->max_insert_length && - s->lookahead >= MIN_MATCH) { - s->match_length--; /* string at strstart already in table */ - do { - s->strstart++; - INSERT_STRING(s, s->strstart, hash_head); - /* strstart never exceeds WSIZE-MAX_MATCH, so there are - * always MIN_MATCH bytes ahead. - */ - } while (--s->match_length != 0); - s->strstart++; - } else -#endif - { - s->strstart += s->match_length; - s->match_length = 0; - s->ins_h = s->window[s->strstart]; - UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]); -#if MIN_MATCH != 3 - Call UPDATE_HASH() MIN_MATCH-3 more times -#endif - /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not - * matter since it will be recomputed at next deflate call. - */ - } - } else { - /* No match, output a literal byte */ - Tracevv((stderr,"%c", s->window[s->strstart])); - _tr_tally_lit (s, s->window[s->strstart], bflush); - s->lookahead--; - s->strstart++; - } - if (bflush) FLUSH_BLOCK(s, 0); - } - FLUSH_BLOCK(s, flush == Z_FINISH); - return flush == Z_FINISH ? finish_done : block_done; -} - -#ifndef FASTEST -/* =========================================================================== - * Same as above, but achieves better compression. We use a lazy - * evaluation for matches: a match is finally adopted only if there is - * no better match at the next window position. - */ -local block_state deflate_slow(s, flush) - deflate_state *s; - int flush; -{ - IPos hash_head = NIL; /* head of hash chain */ - int bflush; /* set if current block must be flushed */ - - /* Process the input block. */ - for (;;) { - /* Make sure that we always have enough lookahead, except - * at the end of the input file. We need MAX_MATCH bytes - * for the next match, plus MIN_MATCH bytes to insert the - * string following the next match. - */ - if (s->lookahead < MIN_LOOKAHEAD) { - fill_window(s); - if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) { - return need_more; - } - if (s->lookahead == 0) break; /* flush the current block */ - } - - /* Insert the string window[strstart .. strstart+2] in the - * dictionary, and set hash_head to the head of the hash chain: - */ - if (s->lookahead >= MIN_MATCH) { - INSERT_STRING(s, s->strstart, hash_head); - } - - /* Find the longest match, discarding those <= prev_length. - */ - s->prev_length = s->match_length, s->prev_match = s->match_start; - s->match_length = MIN_MATCH-1; - - if (hash_head != NIL && s->prev_length < s->max_lazy_match && - s->strstart - hash_head <= MAX_DIST(s)) { - /* To simplify the code, we prevent matches with the string - * of window index 0 (in particular we have to avoid a match - * of the string with itself at the start of the input file). - */ - if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) { - s->match_length = longest_match (s, hash_head); - } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) { - s->match_length = longest_match_fast (s, hash_head); - } - /* longest_match() or longest_match_fast() sets match_start */ - - if (s->match_length <= 5 && (s->strategy == Z_FILTERED -#if TOO_FAR <= 32767 - || (s->match_length == MIN_MATCH && - s->strstart - s->match_start > TOO_FAR) -#endif - )) { - - /* If prev_match is also MIN_MATCH, match_start is garbage - * but we will ignore the current match anyway. - */ - s->match_length = MIN_MATCH-1; - } - } - /* If there was a match at the previous step and the current - * match is not better, output the previous match: - */ - if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) { - uInt max_insert = s->strstart + s->lookahead - MIN_MATCH; - /* Do not insert strings in hash table beyond this. */ - - check_match(s, s->strstart-1, s->prev_match, s->prev_length); - - _tr_tally_dist(s, s->strstart -1 - s->prev_match, - s->prev_length - MIN_MATCH, bflush); - - /* Insert in hash table all strings up to the end of the match. - * strstart-1 and strstart are already inserted. If there is not - * enough lookahead, the last two strings are not inserted in - * the hash table. - */ - s->lookahead -= s->prev_length-1; - s->prev_length -= 2; - do { - if (++s->strstart <= max_insert) { - INSERT_STRING(s, s->strstart, hash_head); - } - } while (--s->prev_length != 0); - s->match_available = 0; - s->match_length = MIN_MATCH-1; - s->strstart++; - - if (bflush) FLUSH_BLOCK(s, 0); - - } else if (s->match_available) { - /* If there was no match at the previous position, output a - * single literal. If there was a match but the current match - * is longer, truncate the previous match to a single literal. - */ - Tracevv((stderr,"%c", s->window[s->strstart-1])); - _tr_tally_lit(s, s->window[s->strstart-1], bflush); - if (bflush) { - FLUSH_BLOCK_ONLY(s, 0); - } - s->strstart++; - s->lookahead--; - if (s->strm->avail_out == 0) return need_more; - } else { - /* There is no previous match to compare with, wait for - * the next step to decide. - */ - s->match_available = 1; - s->strstart++; - s->lookahead--; - } - } - Assert (flush != Z_NO_FLUSH, "no flush?"); - if (s->match_available) { - Tracevv((stderr,"%c", s->window[s->strstart-1])); - _tr_tally_lit(s, s->window[s->strstart-1], bflush); - s->match_available = 0; - } - FLUSH_BLOCK(s, flush == Z_FINISH); - return flush == Z_FINISH ? finish_done : block_done; -} -#endif /* FASTEST */ - -#if 0 -/* =========================================================================== - * For Z_RLE, simply look for runs of bytes, generate matches only of distance - * one. Do not maintain a hash table. (It will be regenerated if this run of - * deflate switches away from Z_RLE.) - */ -local block_state deflate_rle(s, flush) - deflate_state *s; - int flush; -{ - int bflush; /* set if current block must be flushed */ - uInt run; /* length of run */ - uInt max; /* maximum length of run */ - uInt prev; /* byte at distance one to match */ - Bytef *scan; /* scan for end of run */ - - for (;;) { - /* Make sure that we always have enough lookahead, except - * at the end of the input file. We need MAX_MATCH bytes - * for the longest encodable run. - */ - if (s->lookahead < MAX_MATCH) { - fill_window(s); - if (s->lookahead < MAX_MATCH && flush == Z_NO_FLUSH) { - return need_more; - } - if (s->lookahead == 0) break; /* flush the current block */ - } - - /* See how many times the previous byte repeats */ - run = 0; - if (s->strstart > 0) { /* if there is a previous byte, that is */ - max = s->lookahead < MAX_MATCH ? s->lookahead : MAX_MATCH; - scan = s->window + s->strstart - 1; - prev = *scan++; - do { - if (*scan++ != prev) - break; - } while (++run < max); - } - - /* Emit match if have run of MIN_MATCH or longer, else emit literal */ - if (run >= MIN_MATCH) { - check_match(s, s->strstart, s->strstart - 1, run); - _tr_tally_dist(s, 1, run - MIN_MATCH, bflush); - s->lookahead -= run; - s->strstart += run; - } else { - /* No match, output a literal byte */ - Tracevv((stderr,"%c", s->window[s->strstart])); - _tr_tally_lit (s, s->window[s->strstart], bflush); - s->lookahead--; - s->strstart++; - } - if (bflush) FLUSH_BLOCK(s, 0); - } - FLUSH_BLOCK(s, flush == Z_FINISH); - return flush == Z_FINISH ? finish_done : block_done; -} -#endif +/* deflate.c -- compress data using the deflation algorithm + * Copyright (C) 1995-2005 Jean-loup Gailly. + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* + * ALGORITHM + * + * The "deflation" process depends on being able to identify portions + * of the input text which are identical to earlier input (within a + * sliding window trailing behind the input currently being processed). + * + * The most straightforward technique turns out to be the fastest for + * most input files: try all possible matches and select the longest. + * The key feature of this algorithm is that insertions into the string + * dictionary are very simple and thus fast, and deletions are avoided + * completely. Insertions are performed at each input character, whereas + * string matches are performed only when the previous match ends. So it + * is preferable to spend more time in matches to allow very fast string + * insertions and avoid deletions. The matching algorithm for small + * strings is inspired from that of Rabin & Karp. A brute force approach + * is used to find longer strings when a small match has been found. + * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze + * (by Leonid Broukhis). + * A previous version of this file used a more sophisticated algorithm + * (by Fiala and Greene) which is guaranteed to run in linear amortized + * time, but has a larger average cost, uses more memory and is patented. + * However the F&G algorithm may be faster for some highly redundant + * files if the parameter max_chain_length (described below) is too large. + * + * ACKNOWLEDGEMENTS + * + * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and + * I found it in 'freeze' written by Leonid Broukhis. + * Thanks to many people for bug reports and testing. + * + * REFERENCES + * + * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification". + * Available in http://www.ietf.org/rfc/rfc1951.txt + * + * A description of the Rabin and Karp algorithm is given in the book + * "Algorithms" by R. Sedgewick, Addison-Wesley, p252. + * + * Fiala,E.R., and Greene,D.H. + * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595 + * + */ + +/* @(#) $Id: //poco/1.2/Foundation/src/deflate.c#1 $ */ + +#include "deflate.h" + +const char deflate_copyright[] = + " deflate 1.2.3 Copyright 1995-2005 Jean-loup Gailly "; +/* + If you use the zlib library in a product, an acknowledgment is welcome + in the documentation of your product. If for some reason you cannot + include such an acknowledgment, I would appreciate that you keep this + copyright string in the executable of your product. + */ + +/* =========================================================================== + * Function prototypes. + */ +typedef enum { + need_more, /* block not completed, need more input or more output */ + block_done, /* block flush performed */ + finish_started, /* finish started, need only more output at next deflate */ + finish_done /* finish done, accept no more input or output */ +} block_state; + +typedef block_state (*compress_func) OF((deflate_state *s, int flush)); +/* Compression function. Returns the block state after the call. */ + +local void fill_window OF((deflate_state *s)); +local block_state deflate_stored OF((deflate_state *s, int flush)); +local block_state deflate_fast OF((deflate_state *s, int flush)); +#ifndef FASTEST +local block_state deflate_slow OF((deflate_state *s, int flush)); +#endif +local void lm_init OF((deflate_state *s)); +local void putShortMSB OF((deflate_state *s, uInt b)); +local void flush_pending OF((z_streamp strm)); +local int read_buf OF((z_streamp strm, Bytef *buf, unsigned size)); +#ifndef FASTEST +#ifdef ASMV + void match_init OF((void)); /* asm code initialization */ + uInt longest_match OF((deflate_state *s, IPos cur_match)); +#else +local uInt longest_match OF((deflate_state *s, IPos cur_match)); +#endif +#endif +local uInt longest_match_fast OF((deflate_state *s, IPos cur_match)); + +#ifdef DEBUG +local void check_match OF((deflate_state *s, IPos start, IPos match, + int length)); +#endif + +/* =========================================================================== + * Local data + */ + +#define NIL 0 +/* Tail of hash chains */ + +#ifndef TOO_FAR +# define TOO_FAR 4096 +#endif +/* Matches of length 3 are discarded if their distance exceeds TOO_FAR */ + +#define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1) +/* Minimum amount of lookahead, except at the end of the input file. + * See deflate.c for comments about the MIN_MATCH+1. + */ + +/* Values for max_lazy_match, good_match and max_chain_length, depending on + * the desired pack level (0..9). The values given below have been tuned to + * exclude worst case performance for pathological files. Better values may be + * found for specific files. + */ +typedef struct config_s { + ush good_length; /* reduce lazy search above this match length */ + ush max_lazy; /* do not perform lazy search above this match length */ + ush nice_length; /* quit search above this match length */ + ush max_chain; + compress_func func; +} config; + +#ifdef FASTEST +local const config configuration_table[2] = { +/* good lazy nice chain */ +/* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */ +/* 1 */ {4, 4, 8, 4, deflate_fast}}; /* max speed, no lazy matches */ +#else +local const config configuration_table[10] = { +/* good lazy nice chain */ +/* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */ +/* 1 */ {4, 4, 8, 4, deflate_fast}, /* max speed, no lazy matches */ +/* 2 */ {4, 5, 16, 8, deflate_fast}, +/* 3 */ {4, 6, 32, 32, deflate_fast}, + +/* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */ +/* 5 */ {8, 16, 32, 32, deflate_slow}, +/* 6 */ {8, 16, 128, 128, deflate_slow}, +/* 7 */ {8, 32, 128, 256, deflate_slow}, +/* 8 */ {32, 128, 258, 1024, deflate_slow}, +/* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */ +#endif + +/* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4 + * For deflate_fast() (levels <= 3) good is ignored and lazy has a different + * meaning. + */ + +#define EQUAL 0 +/* result of memcmp for equal strings */ + +#ifndef NO_DUMMY_DECL +struct static_tree_desc_s {int dummy;}; /* for buggy compilers */ +#endif + +/* =========================================================================== + * Update a hash value with the given input byte + * IN assertion: all calls to to UPDATE_HASH are made with consecutive + * input characters, so that a running hash key can be computed from the + * previous key instead of complete recalculation each time. + */ +#define UPDATE_HASH(s,h,c) (h = (((h)<hash_shift) ^ (c)) & s->hash_mask) + + +/* =========================================================================== + * Insert string str in the dictionary and set match_head to the previous head + * of the hash chain (the most recent string with same hash key). Return + * the previous length of the hash chain. + * If this file is compiled with -DFASTEST, the compression level is forced + * to 1, and no hash chains are maintained. + * IN assertion: all calls to to INSERT_STRING are made with consecutive + * input characters and the first MIN_MATCH bytes of str are valid + * (except for the last MIN_MATCH-1 bytes of the input file). + */ +#ifdef FASTEST +#define INSERT_STRING(s, str, match_head) \ + (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \ + match_head = s->head[s->ins_h], \ + s->head[s->ins_h] = (Pos)(str)) +#else +#define INSERT_STRING(s, str, match_head) \ + (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \ + match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \ + s->head[s->ins_h] = (Pos)(str)) +#endif + +/* =========================================================================== + * Initialize the hash table (avoiding 64K overflow for 16 bit systems). + * prev[] will be initialized on the fly. + */ +#define CLEAR_HASH(s) \ + s->head[s->hash_size-1] = NIL; \ + zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head)); + +/* ========================================================================= */ +int ZEXPORT deflateInit_(strm, level, version, stream_size) + z_streamp strm; + int level; + const char *version; + int stream_size; +{ + return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, + Z_DEFAULT_STRATEGY, version, stream_size); + /* To do: ignore strm->next_in if we use it as window */ +} + +/* ========================================================================= */ +int ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy, + version, stream_size) + z_streamp strm; + int level; + int method; + int windowBits; + int memLevel; + int strategy; + const char *version; + int stream_size; +{ + deflate_state *s; + int wrap = 1; + static const char my_version[] = ZLIB_VERSION; + + ushf *overlay; + /* We overlay pending_buf and d_buf+l_buf. This works since the average + * output size for (length,distance) codes is <= 24 bits. + */ + + if (version == Z_NULL || version[0] != my_version[0] || + stream_size != sizeof(z_stream)) { + return Z_VERSION_ERROR; + } + if (strm == Z_NULL) return Z_STREAM_ERROR; + + strm->msg = Z_NULL; + if (strm->zalloc == (alloc_func)0) { + strm->zalloc = zcalloc; + strm->opaque = (voidpf)0; + } + if (strm->zfree == (free_func)0) strm->zfree = zcfree; + +#ifdef FASTEST + if (level != 0) level = 1; +#else + if (level == Z_DEFAULT_COMPRESSION) level = 6; +#endif + + if (windowBits < 0) { /* suppress zlib wrapper */ + wrap = 0; + windowBits = -windowBits; + } +#ifdef GZIP + else if (windowBits > 15) { + wrap = 2; /* write gzip wrapper instead */ + windowBits -= 16; + } +#endif + if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED || + windowBits < 8 || windowBits > 15 || level < 0 || level > 9 || + strategy < 0 || strategy > Z_FIXED) { + return Z_STREAM_ERROR; + } + if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */ + s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state)); + if (s == Z_NULL) return Z_MEM_ERROR; + strm->state = (struct internal_state FAR *)s; + s->strm = strm; + + s->wrap = wrap; + s->gzhead = Z_NULL; + s->w_bits = windowBits; + s->w_size = 1 << s->w_bits; + s->w_mask = s->w_size - 1; + + s->hash_bits = memLevel + 7; + s->hash_size = 1 << s->hash_bits; + s->hash_mask = s->hash_size - 1; + s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH); + + s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte)); + s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos)); + s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos)); + + s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */ + + overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2); + s->pending_buf = (uchf *) overlay; + s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L); + + if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL || + s->pending_buf == Z_NULL) { + s->status = FINISH_STATE; + strm->msg = (char*)ERR_MSG(Z_MEM_ERROR); + deflateEnd (strm); + return Z_MEM_ERROR; + } + s->d_buf = overlay + s->lit_bufsize/sizeof(ush); + s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize; + + s->level = level; + s->strategy = strategy; + s->method = (Byte)method; + + return deflateReset(strm); +} + +/* ========================================================================= */ +int ZEXPORT deflateSetDictionary (strm, dictionary, dictLength) + z_streamp strm; + const Bytef *dictionary; + uInt dictLength; +{ + deflate_state *s; + uInt length = dictLength; + uInt n; + IPos hash_head = 0; + + if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL || + strm->state->wrap == 2 || + (strm->state->wrap == 1 && strm->state->status != INIT_STATE)) + return Z_STREAM_ERROR; + + s = strm->state; + if (s->wrap) + strm->adler = adler32(strm->adler, dictionary, dictLength); + + if (length < MIN_MATCH) return Z_OK; + if (length > MAX_DIST(s)) { + length = MAX_DIST(s); + dictionary += dictLength - length; /* use the tail of the dictionary */ + } + zmemcpy(s->window, dictionary, length); + s->strstart = length; + s->block_start = (long)length; + + /* Insert all strings in the hash table (except for the last two bytes). + * s->lookahead stays null, so s->ins_h will be recomputed at the next + * call of fill_window. + */ + s->ins_h = s->window[0]; + UPDATE_HASH(s, s->ins_h, s->window[1]); + for (n = 0; n <= length - MIN_MATCH; n++) { + INSERT_STRING(s, n, hash_head); + } + if (hash_head) hash_head = 0; /* to make compiler happy */ + return Z_OK; +} + +/* ========================================================================= */ +int ZEXPORT deflateReset (strm) + z_streamp strm; +{ + deflate_state *s; + + if (strm == Z_NULL || strm->state == Z_NULL || + strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) { + return Z_STREAM_ERROR; + } + + strm->total_in = strm->total_out = 0; + strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */ + strm->data_type = Z_UNKNOWN; + + s = (deflate_state *)strm->state; + s->pending = 0; + s->pending_out = s->pending_buf; + + if (s->wrap < 0) { + s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */ + } + s->status = s->wrap ? INIT_STATE : BUSY_STATE; + strm->adler = +#ifdef GZIP + s->wrap == 2 ? crc32(0L, Z_NULL, 0) : +#endif + adler32(0L, Z_NULL, 0); + s->last_flush = Z_NO_FLUSH; + + _tr_init(s); + lm_init(s); + + return Z_OK; +} + +/* ========================================================================= */ +int ZEXPORT deflateSetHeader (strm, head) + z_streamp strm; + gz_headerp head; +{ + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; + if (strm->state->wrap != 2) return Z_STREAM_ERROR; + strm->state->gzhead = head; + return Z_OK; +} + +/* ========================================================================= */ +int ZEXPORT deflatePrime (strm, bits, value) + z_streamp strm; + int bits; + int value; +{ + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; + strm->state->bi_valid = bits; + strm->state->bi_buf = (ush)(value & ((1 << bits) - 1)); + return Z_OK; +} + +/* ========================================================================= */ +int ZEXPORT deflateParams(strm, level, strategy) + z_streamp strm; + int level; + int strategy; +{ + deflate_state *s; + compress_func func; + int err = Z_OK; + + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; + s = strm->state; + +#ifdef FASTEST + if (level != 0) level = 1; +#else + if (level == Z_DEFAULT_COMPRESSION) level = 6; +#endif + if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) { + return Z_STREAM_ERROR; + } + func = configuration_table[s->level].func; + + if (func != configuration_table[level].func && strm->total_in != 0) { + /* Flush the last buffer: */ + err = deflate(strm, Z_PARTIAL_FLUSH); + } + if (s->level != level) { + s->level = level; + s->max_lazy_match = configuration_table[level].max_lazy; + s->good_match = configuration_table[level].good_length; + s->nice_match = configuration_table[level].nice_length; + s->max_chain_length = configuration_table[level].max_chain; + } + s->strategy = strategy; + return err; +} + +/* ========================================================================= */ +int ZEXPORT deflateTune(strm, good_length, max_lazy, nice_length, max_chain) + z_streamp strm; + int good_length; + int max_lazy; + int nice_length; + int max_chain; +{ + deflate_state *s; + + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; + s = strm->state; + s->good_match = good_length; + s->max_lazy_match = max_lazy; + s->nice_match = nice_length; + s->max_chain_length = max_chain; + return Z_OK; +} + +/* ========================================================================= + * For the default windowBits of 15 and memLevel of 8, this function returns + * a close to exact, as well as small, upper bound on the compressed size. + * They are coded as constants here for a reason--if the #define's are + * changed, then this function needs to be changed as well. The return + * value for 15 and 8 only works for those exact settings. + * + * For any setting other than those defaults for windowBits and memLevel, + * the value returned is a conservative worst case for the maximum expansion + * resulting from using fixed blocks instead of stored blocks, which deflate + * can emit on compressed data for some combinations of the parameters. + * + * This function could be more sophisticated to provide closer upper bounds + * for every combination of windowBits and memLevel, as well as wrap. + * But even the conservative upper bound of about 14% expansion does not + * seem onerous for output buffer allocation. + */ +uLong ZEXPORT deflateBound(strm, sourceLen) + z_streamp strm; + uLong sourceLen; +{ + deflate_state *s; + uLong destLen; + + /* conservative upper bound */ + destLen = sourceLen + + ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 11; + + /* if can't get parameters, return conservative bound */ + if (strm == Z_NULL || strm->state == Z_NULL) + return destLen; + + /* if not default parameters, return conservative bound */ + s = strm->state; + if (s->w_bits != 15 || s->hash_bits != 8 + 7) + return destLen; + + /* default settings: return tight bound for that case */ + return compressBound(sourceLen); +} + +/* ========================================================================= + * Put a short in the pending buffer. The 16-bit value is put in MSB order. + * IN assertion: the stream state is correct and there is enough room in + * pending_buf. + */ +local void putShortMSB (s, b) + deflate_state *s; + uInt b; +{ + put_byte(s, (Byte)(b >> 8)); + put_byte(s, (Byte)(b & 0xff)); +} + +/* ========================================================================= + * Flush as much pending output as possible. All deflate() output goes + * through this function so some applications may wish to modify it + * to avoid allocating a large strm->next_out buffer and copying into it. + * (See also read_buf()). + */ +local void flush_pending(strm) + z_streamp strm; +{ + unsigned len = strm->state->pending; + + if (len > strm->avail_out) len = strm->avail_out; + if (len == 0) return; + + zmemcpy(strm->next_out, strm->state->pending_out, len); + strm->next_out += len; + strm->state->pending_out += len; + strm->total_out += len; + strm->avail_out -= len; + strm->state->pending -= len; + if (strm->state->pending == 0) { + strm->state->pending_out = strm->state->pending_buf; + } +} + +/* ========================================================================= */ +int ZEXPORT deflate (strm, flush) + z_streamp strm; + int flush; +{ + int old_flush; /* value of flush param for previous deflate call */ + deflate_state *s; + + if (strm == Z_NULL || strm->state == Z_NULL || + flush > Z_FINISH || flush < 0) { + return Z_STREAM_ERROR; + } + s = strm->state; + + if (strm->next_out == Z_NULL || + (strm->next_in == Z_NULL && strm->avail_in != 0) || + (s->status == FINISH_STATE && flush != Z_FINISH)) { + ERR_RETURN(strm, Z_STREAM_ERROR); + } + if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR); + + s->strm = strm; /* just in case */ + old_flush = s->last_flush; + s->last_flush = flush; + + /* Write the header */ + if (s->status == INIT_STATE) { +#ifdef GZIP + if (s->wrap == 2) { + strm->adler = crc32(0L, Z_NULL, 0); + put_byte(s, 31); + put_byte(s, 139); + put_byte(s, 8); + if (s->gzhead == NULL) { + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, s->level == 9 ? 2 : + (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ? + 4 : 0)); + put_byte(s, OS_CODE); + s->status = BUSY_STATE; + } + else { + put_byte(s, (s->gzhead->text ? 1 : 0) + + (s->gzhead->hcrc ? 2 : 0) + + (s->gzhead->extra == Z_NULL ? 0 : 4) + + (s->gzhead->name == Z_NULL ? 0 : 8) + + (s->gzhead->comment == Z_NULL ? 0 : 16) + ); + put_byte(s, (Byte)(s->gzhead->time & 0xff)); + put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff)); + put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff)); + put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff)); + put_byte(s, s->level == 9 ? 2 : + (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ? + 4 : 0)); + put_byte(s, s->gzhead->os & 0xff); + if (s->gzhead->extra != NULL) { + put_byte(s, s->gzhead->extra_len & 0xff); + put_byte(s, (s->gzhead->extra_len >> 8) & 0xff); + } + if (s->gzhead->hcrc) + strm->adler = crc32(strm->adler, s->pending_buf, + s->pending); + s->gzindex = 0; + s->status = EXTRA_STATE; + } + } + else +#endif + { + uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8; + uInt level_flags; + + if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2) + level_flags = 0; + else if (s->level < 6) + level_flags = 1; + else if (s->level == 6) + level_flags = 2; + else + level_flags = 3; + header |= (level_flags << 6); + if (s->strstart != 0) header |= PRESET_DICT; + header += 31 - (header % 31); + + s->status = BUSY_STATE; + putShortMSB(s, header); + + /* Save the adler32 of the preset dictionary: */ + if (s->strstart != 0) { + putShortMSB(s, (uInt)(strm->adler >> 16)); + putShortMSB(s, (uInt)(strm->adler & 0xffff)); + } + strm->adler = adler32(0L, Z_NULL, 0); + } + } +#ifdef GZIP + if (s->status == EXTRA_STATE) { + if (s->gzhead->extra != NULL) { + uInt beg = s->pending; /* start of bytes to update crc */ + + while (s->gzindex < (s->gzhead->extra_len & 0xffff)) { + if (s->pending == s->pending_buf_size) { + if (s->gzhead->hcrc && s->pending > beg) + strm->adler = crc32(strm->adler, s->pending_buf + beg, + s->pending - beg); + flush_pending(strm); + beg = s->pending; + if (s->pending == s->pending_buf_size) + break; + } + put_byte(s, s->gzhead->extra[s->gzindex]); + s->gzindex++; + } + if (s->gzhead->hcrc && s->pending > beg) + strm->adler = crc32(strm->adler, s->pending_buf + beg, + s->pending - beg); + if (s->gzindex == s->gzhead->extra_len) { + s->gzindex = 0; + s->status = NAME_STATE; + } + } + else + s->status = NAME_STATE; + } + if (s->status == NAME_STATE) { + if (s->gzhead->name != NULL) { + uInt beg = s->pending; /* start of bytes to update crc */ + int val; + + do { + if (s->pending == s->pending_buf_size) { + if (s->gzhead->hcrc && s->pending > beg) + strm->adler = crc32(strm->adler, s->pending_buf + beg, + s->pending - beg); + flush_pending(strm); + beg = s->pending; + if (s->pending == s->pending_buf_size) { + val = 1; + break; + } + } + val = s->gzhead->name[s->gzindex++]; + put_byte(s, val); + } while (val != 0); + if (s->gzhead->hcrc && s->pending > beg) + strm->adler = crc32(strm->adler, s->pending_buf + beg, + s->pending - beg); + if (val == 0) { + s->gzindex = 0; + s->status = COMMENT_STATE; + } + } + else + s->status = COMMENT_STATE; + } + if (s->status == COMMENT_STATE) { + if (s->gzhead->comment != NULL) { + uInt beg = s->pending; /* start of bytes to update crc */ + int val; + + do { + if (s->pending == s->pending_buf_size) { + if (s->gzhead->hcrc && s->pending > beg) + strm->adler = crc32(strm->adler, s->pending_buf + beg, + s->pending - beg); + flush_pending(strm); + beg = s->pending; + if (s->pending == s->pending_buf_size) { + val = 1; + break; + } + } + val = s->gzhead->comment[s->gzindex++]; + put_byte(s, val); + } while (val != 0); + if (s->gzhead->hcrc && s->pending > beg) + strm->adler = crc32(strm->adler, s->pending_buf + beg, + s->pending - beg); + if (val == 0) + s->status = HCRC_STATE; + } + else + s->status = HCRC_STATE; + } + if (s->status == HCRC_STATE) { + if (s->gzhead->hcrc) { + if (s->pending + 2 > s->pending_buf_size) + flush_pending(strm); + if (s->pending + 2 <= s->pending_buf_size) { + put_byte(s, (Byte)(strm->adler & 0xff)); + put_byte(s, (Byte)((strm->adler >> 8) & 0xff)); + strm->adler = crc32(0L, Z_NULL, 0); + s->status = BUSY_STATE; + } + } + else + s->status = BUSY_STATE; + } +#endif + + /* Flush as much pending output as possible */ + if (s->pending != 0) { + flush_pending(strm); + if (strm->avail_out == 0) { + /* Since avail_out is 0, deflate will be called again with + * more output space, but possibly with both pending and + * avail_in equal to zero. There won't be anything to do, + * but this is not an error situation so make sure we + * return OK instead of BUF_ERROR at next call of deflate: + */ + s->last_flush = -1; + return Z_OK; + } + + /* Make sure there is something to do and avoid duplicate consecutive + * flushes. For repeated and useless calls with Z_FINISH, we keep + * returning Z_STREAM_END instead of Z_BUF_ERROR. + */ + } else if (strm->avail_in == 0 && flush <= old_flush && + flush != Z_FINISH) { + ERR_RETURN(strm, Z_BUF_ERROR); + } + + /* User must not provide more input after the first FINISH: */ + if (s->status == FINISH_STATE && strm->avail_in != 0) { + ERR_RETURN(strm, Z_BUF_ERROR); + } + + /* Start a new block or continue the current one. + */ + if (strm->avail_in != 0 || s->lookahead != 0 || + (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) { + block_state bstate; + + bstate = (*(configuration_table[s->level].func))(s, flush); + + if (bstate == finish_started || bstate == finish_done) { + s->status = FINISH_STATE; + } + if (bstate == need_more || bstate == finish_started) { + if (strm->avail_out == 0) { + s->last_flush = -1; /* avoid BUF_ERROR next call, see above */ + } + return Z_OK; + /* If flush != Z_NO_FLUSH && avail_out == 0, the next call + * of deflate should use the same flush parameter to make sure + * that the flush is complete. So we don't have to output an + * empty block here, this will be done at next call. This also + * ensures that for a very small output buffer, we emit at most + * one empty block. + */ + } + if (bstate == block_done) { + if (flush == Z_PARTIAL_FLUSH) { + _tr_align(s); + } else { /* FULL_FLUSH or SYNC_FLUSH */ + _tr_stored_block(s, (char*)0, 0L, 0); + /* For a full flush, this empty block will be recognized + * as a special marker by inflate_sync(). + */ + if (flush == Z_FULL_FLUSH) { + CLEAR_HASH(s); /* forget history */ + } + } + flush_pending(strm); + if (strm->avail_out == 0) { + s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */ + return Z_OK; + } + } + } + Assert(strm->avail_out > 0, "bug2"); + + if (flush != Z_FINISH) return Z_OK; + if (s->wrap <= 0) return Z_STREAM_END; + + /* Write the trailer */ +#ifdef GZIP + if (s->wrap == 2) { + put_byte(s, (Byte)(strm->adler & 0xff)); + put_byte(s, (Byte)((strm->adler >> 8) & 0xff)); + put_byte(s, (Byte)((strm->adler >> 16) & 0xff)); + put_byte(s, (Byte)((strm->adler >> 24) & 0xff)); + put_byte(s, (Byte)(strm->total_in & 0xff)); + put_byte(s, (Byte)((strm->total_in >> 8) & 0xff)); + put_byte(s, (Byte)((strm->total_in >> 16) & 0xff)); + put_byte(s, (Byte)((strm->total_in >> 24) & 0xff)); + } + else +#endif + { + putShortMSB(s, (uInt)(strm->adler >> 16)); + putShortMSB(s, (uInt)(strm->adler & 0xffff)); + } + flush_pending(strm); + /* If avail_out is zero, the application will call deflate again + * to flush the rest. + */ + if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */ + return s->pending != 0 ? Z_OK : Z_STREAM_END; +} + +/* ========================================================================= */ +int ZEXPORT deflateEnd (strm) + z_streamp strm; +{ + int status; + + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; + + status = strm->state->status; + if (status != INIT_STATE && + status != EXTRA_STATE && + status != NAME_STATE && + status != COMMENT_STATE && + status != HCRC_STATE && + status != BUSY_STATE && + status != FINISH_STATE) { + return Z_STREAM_ERROR; + } + + /* Deallocate in reverse order of allocations: */ + TRY_FREE(strm, strm->state->pending_buf); + TRY_FREE(strm, strm->state->head); + TRY_FREE(strm, strm->state->prev); + TRY_FREE(strm, strm->state->window); + + ZFREE(strm, strm->state); + strm->state = Z_NULL; + + return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK; +} + +/* ========================================================================= + * Copy the source state to the destination state. + * To simplify the source, this is not supported for 16-bit MSDOS (which + * doesn't have enough memory anyway to duplicate compression states). + */ +int ZEXPORT deflateCopy (dest, source) + z_streamp dest; + z_streamp source; +{ +#ifdef MAXSEG_64K + return Z_STREAM_ERROR; +#else + deflate_state *ds; + deflate_state *ss; + ushf *overlay; + + + if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) { + return Z_STREAM_ERROR; + } + + ss = source->state; + + zmemcpy(dest, source, sizeof(z_stream)); + + ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state)); + if (ds == Z_NULL) return Z_MEM_ERROR; + dest->state = (struct internal_state FAR *) ds; + zmemcpy(ds, ss, sizeof(deflate_state)); + ds->strm = dest; + + ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte)); + ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos)); + ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos)); + overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2); + ds->pending_buf = (uchf *) overlay; + + if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL || + ds->pending_buf == Z_NULL) { + deflateEnd (dest); + return Z_MEM_ERROR; + } + /* following zmemcpy do not work for 16-bit MSDOS */ + zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte)); + zmemcpy(ds->prev, ss->prev, ds->w_size * sizeof(Pos)); + zmemcpy(ds->head, ss->head, ds->hash_size * sizeof(Pos)); + zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size); + + ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf); + ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush); + ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize; + + ds->l_desc.dyn_tree = ds->dyn_ltree; + ds->d_desc.dyn_tree = ds->dyn_dtree; + ds->bl_desc.dyn_tree = ds->bl_tree; + + return Z_OK; +#endif /* MAXSEG_64K */ +} + +/* =========================================================================== + * Read a new buffer from the current input stream, update the adler32 + * and total number of bytes read. All deflate() input goes through + * this function so some applications may wish to modify it to avoid + * allocating a large strm->next_in buffer and copying from it. + * (See also flush_pending()). + */ +local int read_buf(strm, buf, size) + z_streamp strm; + Bytef *buf; + unsigned size; +{ + unsigned len = strm->avail_in; + + if (len > size) len = size; + if (len == 0) return 0; + + strm->avail_in -= len; + + if (strm->state->wrap == 1) { + strm->adler = adler32(strm->adler, strm->next_in, len); + } +#ifdef GZIP + else if (strm->state->wrap == 2) { + strm->adler = crc32(strm->adler, strm->next_in, len); + } +#endif + zmemcpy(buf, strm->next_in, len); + strm->next_in += len; + strm->total_in += len; + + return (int)len; +} + +/* =========================================================================== + * Initialize the "longest match" routines for a new zlib stream + */ +local void lm_init (s) + deflate_state *s; +{ + s->window_size = (ulg)2L*s->w_size; + + CLEAR_HASH(s); + + /* Set the default configuration parameters: + */ + s->max_lazy_match = configuration_table[s->level].max_lazy; + s->good_match = configuration_table[s->level].good_length; + s->nice_match = configuration_table[s->level].nice_length; + s->max_chain_length = configuration_table[s->level].max_chain; + + s->strstart = 0; + s->block_start = 0L; + s->lookahead = 0; + s->match_length = s->prev_length = MIN_MATCH-1; + s->match_available = 0; + s->ins_h = 0; +#ifndef FASTEST +#ifdef ASMV + match_init(); /* initialize the asm code */ +#endif +#endif +} + +#ifndef FASTEST +/* =========================================================================== + * Set match_start to the longest match starting at the given string and + * return its length. Matches shorter or equal to prev_length are discarded, + * in which case the result is equal to prev_length and match_start is + * garbage. + * IN assertions: cur_match is the head of the hash chain for the current + * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1 + * OUT assertion: the match length is not greater than s->lookahead. + */ +#ifndef ASMV +/* For 80x86 and 680x0, an optimized version will be provided in match.asm or + * match.S. The code will be functionally equivalent. + */ +local uInt longest_match(s, cur_match) + deflate_state *s; + IPos cur_match; /* current match */ +{ + unsigned chain_length = s->max_chain_length;/* max hash chain length */ + register Bytef *scan = s->window + s->strstart; /* current string */ + register Bytef *match; /* matched string */ + register int len; /* length of current match */ + int best_len = s->prev_length; /* best match length so far */ + int nice_match = s->nice_match; /* stop if match long enough */ + IPos limit = s->strstart > (IPos)MAX_DIST(s) ? + s->strstart - (IPos)MAX_DIST(s) : NIL; + /* Stop when cur_match becomes <= limit. To simplify the code, + * we prevent matches with the string of window index 0. + */ + Posf *prev = s->prev; + uInt wmask = s->w_mask; + +#ifdef UNALIGNED_OK + /* Compare two bytes at a time. Note: this is not always beneficial. + * Try with and without -DUNALIGNED_OK to check. + */ + register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1; + register ush scan_start = *(ushf*)scan; + register ush scan_end = *(ushf*)(scan+best_len-1); +#else + register Bytef *strend = s->window + s->strstart + MAX_MATCH; + register Byte scan_end1 = scan[best_len-1]; + register Byte scan_end = scan[best_len]; +#endif + + /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. + * It is easy to get rid of this optimization if necessary. + */ + Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); + + /* Do not waste too much time if we already have a good match: */ + if (s->prev_length >= s->good_match) { + chain_length >>= 2; + } + /* Do not look for matches beyond the end of the input. This is necessary + * to make deflate deterministic. + */ + if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead; + + Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); + + do { + Assert(cur_match < s->strstart, "no future"); + match = s->window + cur_match; + + /* Skip to next match if the match length cannot increase + * or if the match length is less than 2. Note that the checks below + * for insufficient lookahead only occur occasionally for performance + * reasons. Therefore uninitialized memory will be accessed, and + * conditional jumps will be made that depend on those values. + * However the length of the match is limited to the lookahead, so + * the output of deflate is not affected by the uninitialized values. + */ +#if (defined(UNALIGNED_OK) && MAX_MATCH == 258) + /* This code assumes sizeof(unsigned short) == 2. Do not use + * UNALIGNED_OK if your compiler uses a different size. + */ + if (*(ushf*)(match+best_len-1) != scan_end || + *(ushf*)match != scan_start) continue; + + /* It is not necessary to compare scan[2] and match[2] since they are + * always equal when the other bytes match, given that the hash keys + * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at + * strstart+3, +5, ... up to strstart+257. We check for insufficient + * lookahead only every 4th comparison; the 128th check will be made + * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is + * necessary to put more guard bytes at the end of the window, or + * to check more often for insufficient lookahead. + */ + Assert(scan[2] == match[2], "scan[2]?"); + scan++, match++; + do { + } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) && + *(ushf*)(scan+=2) == *(ushf*)(match+=2) && + *(ushf*)(scan+=2) == *(ushf*)(match+=2) && + *(ushf*)(scan+=2) == *(ushf*)(match+=2) && + scan < strend); + /* The funny "do {}" generates better code on most compilers */ + + /* Here, scan <= window+strstart+257 */ + Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); + if (*scan == *match) scan++; + + len = (MAX_MATCH - 1) - (int)(strend-scan); + scan = strend - (MAX_MATCH-1); + +#else /* UNALIGNED_OK */ + + if (match[best_len] != scan_end || + match[best_len-1] != scan_end1 || + *match != *scan || + *++match != scan[1]) continue; + + /* The check at best_len-1 can be removed because it will be made + * again later. (This heuristic is not always a win.) + * It is not necessary to compare scan[2] and match[2] since they + * are always equal when the other bytes match, given that + * the hash keys are equal and that HASH_BITS >= 8. + */ + scan += 2, match++; + Assert(*scan == *match, "match[2]?"); + + /* We check for insufficient lookahead only every 8th comparison; + * the 256th check will be made at strstart+258. + */ + do { + } while (*++scan == *++match && *++scan == *++match && + *++scan == *++match && *++scan == *++match && + *++scan == *++match && *++scan == *++match && + *++scan == *++match && *++scan == *++match && + scan < strend); + + Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); + + len = MAX_MATCH - (int)(strend - scan); + scan = strend - MAX_MATCH; + +#endif /* UNALIGNED_OK */ + + if (len > best_len) { + s->match_start = cur_match; + best_len = len; + if (len >= nice_match) break; +#ifdef UNALIGNED_OK + scan_end = *(ushf*)(scan+best_len-1); +#else + scan_end1 = scan[best_len-1]; + scan_end = scan[best_len]; +#endif + } + } while ((cur_match = prev[cur_match & wmask]) > limit + && --chain_length != 0); + + if ((uInt)best_len <= s->lookahead) return (uInt)best_len; + return s->lookahead; +} +#endif /* ASMV */ +#endif /* FASTEST */ + +/* --------------------------------------------------------------------------- + * Optimized version for level == 1 or strategy == Z_RLE only + */ +local uInt longest_match_fast(s, cur_match) + deflate_state *s; + IPos cur_match; /* current match */ +{ + register Bytef *scan = s->window + s->strstart; /* current string */ + register Bytef *match; /* matched string */ + register int len; /* length of current match */ + register Bytef *strend = s->window + s->strstart + MAX_MATCH; + + /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. + * It is easy to get rid of this optimization if necessary. + */ + Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); + + Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); + + Assert(cur_match < s->strstart, "no future"); + + match = s->window + cur_match; + + /* Return failure if the match length is less than 2: + */ + if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1; + + /* The check at best_len-1 can be removed because it will be made + * again later. (This heuristic is not always a win.) + * It is not necessary to compare scan[2] and match[2] since they + * are always equal when the other bytes match, given that + * the hash keys are equal and that HASH_BITS >= 8. + */ + scan += 2, match += 2; + Assert(*scan == *match, "match[2]?"); + + /* We check for insufficient lookahead only every 8th comparison; + * the 256th check will be made at strstart+258. + */ + do { + } while (*++scan == *++match && *++scan == *++match && + *++scan == *++match && *++scan == *++match && + *++scan == *++match && *++scan == *++match && + *++scan == *++match && *++scan == *++match && + scan < strend); + + Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); + + len = MAX_MATCH - (int)(strend - scan); + + if (len < MIN_MATCH) return MIN_MATCH - 1; + + s->match_start = cur_match; + return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead; +} + +#ifdef DEBUG +/* =========================================================================== + * Check that the match at match_start is indeed a match. + */ +local void check_match(s, start, match, length) + deflate_state *s; + IPos start, match; + int length; +{ + /* check that the match is indeed a match */ + if (zmemcmp(s->window + match, + s->window + start, length) != EQUAL) { + fprintf(stderr, " start %u, match %u, length %d\n", + start, match, length); + do { + fprintf(stderr, "%c%c", s->window[match++], s->window[start++]); + } while (--length != 0); + z_error("invalid match"); + } + if (z_verbose > 1) { + fprintf(stderr,"\\[%d,%d]", start-match, length); + do { putc(s->window[start++], stderr); } while (--length != 0); + } +} +#else +# define check_match(s, start, match, length) +#endif /* DEBUG */ + +/* =========================================================================== + * Fill the window when the lookahead becomes insufficient. + * Updates strstart and lookahead. + * + * IN assertion: lookahead < MIN_LOOKAHEAD + * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD + * At least one byte has been read, or avail_in == 0; reads are + * performed for at least two bytes (required for the zip translate_eol + * option -- not supported here). + */ +local void fill_window(s) + deflate_state *s; +{ + register unsigned n, m; + register Posf *p; + unsigned more; /* Amount of free space at the end of the window. */ + uInt wsize = s->w_size; + + do { + more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart); + + /* Deal with !@#$% 64K limit: */ + if (sizeof(int) <= 2) { + if (more == 0 && s->strstart == 0 && s->lookahead == 0) { + more = wsize; + + } else if (more == (unsigned)(-1)) { + /* Very unlikely, but possible on 16 bit machine if + * strstart == 0 && lookahead == 1 (input done a byte at time) + */ + more--; + } + } + + /* If the window is almost full and there is insufficient lookahead, + * move the upper half to the lower one to make room in the upper half. + */ + if (s->strstart >= wsize+MAX_DIST(s)) { + + zmemcpy(s->window, s->window+wsize, (unsigned)wsize); + s->match_start -= wsize; + s->strstart -= wsize; /* we now have strstart >= MAX_DIST */ + s->block_start -= (long) wsize; + + /* Slide the hash table (could be avoided with 32 bit values + at the expense of memory usage). We slide even when level == 0 + to keep the hash table consistent if we switch back to level > 0 + later. (Using level 0 permanently is not an optimal usage of + zlib, so we don't care about this pathological case.) + */ + /* %%% avoid this when Z_RLE */ + n = s->hash_size; + p = &s->head[n]; + do { + m = *--p; + *p = (Pos)(m >= wsize ? m-wsize : NIL); + } while (--n); + + n = wsize; +#ifndef FASTEST + p = &s->prev[n]; + do { + m = *--p; + *p = (Pos)(m >= wsize ? m-wsize : NIL); + /* If n is not on any hash chain, prev[n] is garbage but + * its value will never be used. + */ + } while (--n); +#endif + more += wsize; + } + if (s->strm->avail_in == 0) return; + + /* If there was no sliding: + * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && + * more == window_size - lookahead - strstart + * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) + * => more >= window_size - 2*WSIZE + 2 + * In the BIG_MEM or MMAP case (not yet supported), + * window_size == input_size + MIN_LOOKAHEAD && + * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD. + * Otherwise, window_size == 2*WSIZE so more >= 2. + * If there was sliding, more >= WSIZE. So in all cases, more >= 2. + */ + Assert(more >= 2, "more < 2"); + + n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more); + s->lookahead += n; + + /* Initialize the hash value now that we have some input: */ + if (s->lookahead >= MIN_MATCH) { + s->ins_h = s->window[s->strstart]; + UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]); +#if MIN_MATCH != 3 + Call UPDATE_HASH() MIN_MATCH-3 more times +#endif + } + /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage, + * but this is not important since only literal bytes will be emitted. + */ + + } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0); +} + +/* =========================================================================== + * Flush the current block, with given end-of-file flag. + * IN assertion: strstart is set to the end of the current match. + */ +#define FLUSH_BLOCK_ONLY(s, eof) { \ + _tr_flush_block(s, (s->block_start >= 0L ? \ + (charf *)&s->window[(unsigned)s->block_start] : \ + (charf *)Z_NULL), \ + (ulg)((long)s->strstart - s->block_start), \ + (eof)); \ + s->block_start = s->strstart; \ + flush_pending(s->strm); \ + Tracev((stderr,"[FLUSH]")); \ +} + +/* Same but force premature exit if necessary. */ +#define FLUSH_BLOCK(s, eof) { \ + FLUSH_BLOCK_ONLY(s, eof); \ + if (s->strm->avail_out == 0) return (eof) ? finish_started : need_more; \ +} + +/* =========================================================================== + * Copy without compression as much as possible from the input stream, return + * the current block state. + * This function does not insert new strings in the dictionary since + * uncompressible data is probably not useful. This function is used + * only for the level=0 compression option. + * NOTE: this function should be optimized to avoid extra copying from + * window to pending_buf. + */ +local block_state deflate_stored(s, flush) + deflate_state *s; + int flush; +{ + /* Stored blocks are limited to 0xffff bytes, pending_buf is limited + * to pending_buf_size, and each stored block has a 5 byte header: + */ + ulg max_block_size = 0xffff; + ulg max_start; + + if (max_block_size > s->pending_buf_size - 5) { + max_block_size = s->pending_buf_size - 5; + } + + /* Copy as much as possible from input to output: */ + for (;;) { + /* Fill the window as much as possible: */ + if (s->lookahead <= 1) { + + Assert(s->strstart < s->w_size+MAX_DIST(s) || + s->block_start >= (long)s->w_size, "slide too late"); + + fill_window(s); + if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more; + + if (s->lookahead == 0) break; /* flush the current block */ + } + Assert(s->block_start >= 0L, "block gone"); + + s->strstart += s->lookahead; + s->lookahead = 0; + + /* Emit a stored block if pending_buf will be full: */ + max_start = s->block_start + max_block_size; + if (s->strstart == 0 || (ulg)s->strstart >= max_start) { + /* strstart == 0 is possible when wraparound on 16-bit machine */ + s->lookahead = (uInt)(s->strstart - max_start); + s->strstart = (uInt)max_start; + FLUSH_BLOCK(s, 0); + } + /* Flush if we may have to slide, otherwise block_start may become + * negative and the data will be gone: + */ + if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) { + FLUSH_BLOCK(s, 0); + } + } + FLUSH_BLOCK(s, flush == Z_FINISH); + return flush == Z_FINISH ? finish_done : block_done; +} + +/* =========================================================================== + * Compress as much as possible from the input stream, return the current + * block state. + * This function does not perform lazy evaluation of matches and inserts + * new strings in the dictionary only for unmatched strings or for short + * matches. It is used only for the fast compression options. + */ +local block_state deflate_fast(s, flush) + deflate_state *s; + int flush; +{ + IPos hash_head = NIL; /* head of the hash chain */ + int bflush; /* set if current block must be flushed */ + + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the next match, plus MIN_MATCH bytes to insert the + * string following the next match. + */ + if (s->lookahead < MIN_LOOKAHEAD) { + fill_window(s); + if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) { + return need_more; + } + if (s->lookahead == 0) break; /* flush the current block */ + } + + /* Insert the string window[strstart .. strstart+2] in the + * dictionary, and set hash_head to the head of the hash chain: + */ + if (s->lookahead >= MIN_MATCH) { + INSERT_STRING(s, s->strstart, hash_head); + } + + /* Find the longest match, discarding those <= prev_length. + * At this point we have always match_length < MIN_MATCH + */ + if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) { + /* To simplify the code, we prevent matches with the string + * of window index 0 (in particular we have to avoid a match + * of the string with itself at the start of the input file). + */ +#ifdef FASTEST + if ((s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) || + (s->strategy == Z_RLE && s->strstart - hash_head == 1)) { + s->match_length = longest_match_fast (s, hash_head); + } +#else + if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) { + s->match_length = longest_match (s, hash_head); + } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) { + s->match_length = longest_match_fast (s, hash_head); + } +#endif + /* longest_match() or longest_match_fast() sets match_start */ + } + if (s->match_length >= MIN_MATCH) { + check_match(s, s->strstart, s->match_start, s->match_length); + + _tr_tally_dist(s, s->strstart - s->match_start, + s->match_length - MIN_MATCH, bflush); + + s->lookahead -= s->match_length; + + /* Insert new strings in the hash table only if the match length + * is not too large. This saves time but degrades compression. + */ +#ifndef FASTEST + if (s->match_length <= s->max_insert_length && + s->lookahead >= MIN_MATCH) { + s->match_length--; /* string at strstart already in table */ + do { + s->strstart++; + INSERT_STRING(s, s->strstart, hash_head); + /* strstart never exceeds WSIZE-MAX_MATCH, so there are + * always MIN_MATCH bytes ahead. + */ + } while (--s->match_length != 0); + s->strstart++; + } else +#endif + { + s->strstart += s->match_length; + s->match_length = 0; + s->ins_h = s->window[s->strstart]; + UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]); +#if MIN_MATCH != 3 + Call UPDATE_HASH() MIN_MATCH-3 more times +#endif + /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not + * matter since it will be recomputed at next deflate call. + */ + } + } else { + /* No match, output a literal byte */ + Tracevv((stderr,"%c", s->window[s->strstart])); + _tr_tally_lit (s, s->window[s->strstart], bflush); + s->lookahead--; + s->strstart++; + } + if (bflush) FLUSH_BLOCK(s, 0); + } + FLUSH_BLOCK(s, flush == Z_FINISH); + return flush == Z_FINISH ? finish_done : block_done; +} + +#ifndef FASTEST +/* =========================================================================== + * Same as above, but achieves better compression. We use a lazy + * evaluation for matches: a match is finally adopted only if there is + * no better match at the next window position. + */ +local block_state deflate_slow(s, flush) + deflate_state *s; + int flush; +{ + IPos hash_head = NIL; /* head of hash chain */ + int bflush; /* set if current block must be flushed */ + + /* Process the input block. */ + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the next match, plus MIN_MATCH bytes to insert the + * string following the next match. + */ + if (s->lookahead < MIN_LOOKAHEAD) { + fill_window(s); + if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) { + return need_more; + } + if (s->lookahead == 0) break; /* flush the current block */ + } + + /* Insert the string window[strstart .. strstart+2] in the + * dictionary, and set hash_head to the head of the hash chain: + */ + if (s->lookahead >= MIN_MATCH) { + INSERT_STRING(s, s->strstart, hash_head); + } + + /* Find the longest match, discarding those <= prev_length. + */ + s->prev_length = s->match_length, s->prev_match = s->match_start; + s->match_length = MIN_MATCH-1; + + if (hash_head != NIL && s->prev_length < s->max_lazy_match && + s->strstart - hash_head <= MAX_DIST(s)) { + /* To simplify the code, we prevent matches with the string + * of window index 0 (in particular we have to avoid a match + * of the string with itself at the start of the input file). + */ + if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) { + s->match_length = longest_match (s, hash_head); + } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) { + s->match_length = longest_match_fast (s, hash_head); + } + /* longest_match() or longest_match_fast() sets match_start */ + + if (s->match_length <= 5 && (s->strategy == Z_FILTERED +#if TOO_FAR <= 32767 + || (s->match_length == MIN_MATCH && + s->strstart - s->match_start > TOO_FAR) +#endif + )) { + + /* If prev_match is also MIN_MATCH, match_start is garbage + * but we will ignore the current match anyway. + */ + s->match_length = MIN_MATCH-1; + } + } + /* If there was a match at the previous step and the current + * match is not better, output the previous match: + */ + if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) { + uInt max_insert = s->strstart + s->lookahead - MIN_MATCH; + /* Do not insert strings in hash table beyond this. */ + + check_match(s, s->strstart-1, s->prev_match, s->prev_length); + + _tr_tally_dist(s, s->strstart -1 - s->prev_match, + s->prev_length - MIN_MATCH, bflush); + + /* Insert in hash table all strings up to the end of the match. + * strstart-1 and strstart are already inserted. If there is not + * enough lookahead, the last two strings are not inserted in + * the hash table. + */ + s->lookahead -= s->prev_length-1; + s->prev_length -= 2; + do { + if (++s->strstart <= max_insert) { + INSERT_STRING(s, s->strstart, hash_head); + } + } while (--s->prev_length != 0); + s->match_available = 0; + s->match_length = MIN_MATCH-1; + s->strstart++; + + if (bflush) FLUSH_BLOCK(s, 0); + + } else if (s->match_available) { + /* If there was no match at the previous position, output a + * single literal. If there was a match but the current match + * is longer, truncate the previous match to a single literal. + */ + Tracevv((stderr,"%c", s->window[s->strstart-1])); + _tr_tally_lit(s, s->window[s->strstart-1], bflush); + if (bflush) { + FLUSH_BLOCK_ONLY(s, 0); + } + s->strstart++; + s->lookahead--; + if (s->strm->avail_out == 0) return need_more; + } else { + /* There is no previous match to compare with, wait for + * the next step to decide. + */ + s->match_available = 1; + s->strstart++; + s->lookahead--; + } + } + Assert (flush != Z_NO_FLUSH, "no flush?"); + if (s->match_available) { + Tracevv((stderr,"%c", s->window[s->strstart-1])); + _tr_tally_lit(s, s->window[s->strstart-1], bflush); + s->match_available = 0; + } + FLUSH_BLOCK(s, flush == Z_FINISH); + return flush == Z_FINISH ? finish_done : block_done; +} +#endif /* FASTEST */ + +#if 0 +/* =========================================================================== + * For Z_RLE, simply look for runs of bytes, generate matches only of distance + * one. Do not maintain a hash table. (It will be regenerated if this run of + * deflate switches away from Z_RLE.) + */ +local block_state deflate_rle(s, flush) + deflate_state *s; + int flush; +{ + int bflush; /* set if current block must be flushed */ + uInt run; /* length of run */ + uInt max; /* maximum length of run */ + uInt prev; /* byte at distance one to match */ + Bytef *scan; /* scan for end of run */ + + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the longest encodable run. + */ + if (s->lookahead < MAX_MATCH) { + fill_window(s); + if (s->lookahead < MAX_MATCH && flush == Z_NO_FLUSH) { + return need_more; + } + if (s->lookahead == 0) break; /* flush the current block */ + } + + /* See how many times the previous byte repeats */ + run = 0; + if (s->strstart > 0) { /* if there is a previous byte, that is */ + max = s->lookahead < MAX_MATCH ? s->lookahead : MAX_MATCH; + scan = s->window + s->strstart - 1; + prev = *scan++; + do { + if (*scan++ != prev) + break; + } while (++run < max); + } + + /* Emit match if have run of MIN_MATCH or longer, else emit literal */ + if (run >= MIN_MATCH) { + check_match(s, s->strstart, s->strstart - 1, run); + _tr_tally_dist(s, 1, run - MIN_MATCH, bflush); + s->lookahead -= run; + s->strstart += run; + } else { + /* No match, output a literal byte */ + Tracevv((stderr,"%c", s->window[s->strstart])); + _tr_tally_lit (s, s->window[s->strstart], bflush); + s->lookahead--; + s->strstart++; + } + if (bflush) FLUSH_BLOCK(s, 0); + } + FLUSH_BLOCK(s, flush == Z_FINISH); + return flush == Z_FINISH ? finish_done : block_done; +} +#endif diff --git a/Foundation/src/deflate.h b/Foundation/src/deflate.h index 493104dc1..83c1e1bcf 100644 --- a/Foundation/src/deflate.h +++ b/Foundation/src/deflate.h @@ -1,331 +1,331 @@ -/* deflate.h -- internal compression state - * Copyright (C) 1995-2004 Jean-loup Gailly - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -/* WARNING: this file should *not* be used by applications. It is - part of the implementation of the compression library and is - subject to change. Applications should only use zlib.h. - */ - -/* @(#) $Id: //poco/1.2/Foundation/src/deflate.h#1 $ */ - -#ifndef DEFLATE_H -#define DEFLATE_H - -#include "zutil.h" - -/* define NO_GZIP when compiling if you want to disable gzip header and - trailer creation by deflate(). NO_GZIP would be used to avoid linking in - the crc code when it is not needed. For shared libraries, gzip encoding - should be left enabled. */ -#ifndef NO_GZIP -# define GZIP -#endif - -/* =========================================================================== - * Internal compression state. - */ - -#define LENGTH_CODES 29 -/* number of length codes, not counting the special END_BLOCK code */ - -#define LITERALS 256 -/* number of literal bytes 0..255 */ - -#define L_CODES (LITERALS+1+LENGTH_CODES) -/* number of Literal or Length codes, including the END_BLOCK code */ - -#define D_CODES 30 -/* number of distance codes */ - -#define BL_CODES 19 -/* number of codes used to transfer the bit lengths */ - -#define HEAP_SIZE (2*L_CODES+1) -/* maximum heap size */ - -#define MAX_BITS 15 -/* All codes must not exceed MAX_BITS bits */ - -#define INIT_STATE 42 -#define EXTRA_STATE 69 -#define NAME_STATE 73 -#define COMMENT_STATE 91 -#define HCRC_STATE 103 -#define BUSY_STATE 113 -#define FINISH_STATE 666 -/* Stream status */ - - -/* Data structure describing a single value and its code string. */ -typedef struct ct_data_s { - union { - ush freq; /* frequency count */ - ush code; /* bit string */ - } fc; - union { - ush dad; /* father node in Huffman tree */ - ush len; /* length of bit string */ - } dl; -} FAR ct_data; - -#define Freq fc.freq -#define Code fc.code -#define Dad dl.dad -#define Len dl.len - -typedef struct static_tree_desc_s static_tree_desc; - -typedef struct tree_desc_s { - ct_data *dyn_tree; /* the dynamic tree */ - int max_code; /* largest code with non zero frequency */ - static_tree_desc *stat_desc; /* the corresponding static tree */ -} FAR tree_desc; - -typedef ush Pos; -typedef Pos FAR Posf; -typedef unsigned IPos; - -/* A Pos is an index in the character window. We use short instead of int to - * save space in the various tables. IPos is used only for parameter passing. - */ - -typedef struct internal_state { - z_streamp strm; /* pointer back to this zlib stream */ - int status; /* as the name implies */ - Bytef *pending_buf; /* output still pending */ - ulg pending_buf_size; /* size of pending_buf */ - Bytef *pending_out; /* next pending byte to output to the stream */ - uInt pending; /* nb of bytes in the pending buffer */ - int wrap; /* bit 0 true for zlib, bit 1 true for gzip */ - gz_headerp gzhead; /* gzip header information to write */ - uInt gzindex; /* where in extra, name, or comment */ - Byte method; /* STORED (for zip only) or DEFLATED */ - int last_flush; /* value of flush param for previous deflate call */ - - /* used by deflate.c: */ - - uInt w_size; /* LZ77 window size (32K by default) */ - uInt w_bits; /* log2(w_size) (8..16) */ - uInt w_mask; /* w_size - 1 */ - - Bytef *window; - /* Sliding window. Input bytes are read into the second half of the window, - * and move to the first half later to keep a dictionary of at least wSize - * bytes. With this organization, matches are limited to a distance of - * wSize-MAX_MATCH bytes, but this ensures that IO is always - * performed with a length multiple of the block size. Also, it limits - * the window size to 64K, which is quite useful on MSDOS. - * To do: use the user input buffer as sliding window. - */ - - ulg window_size; - /* Actual size of window: 2*wSize, except when the user input buffer - * is directly used as sliding window. - */ - - Posf *prev; - /* Link to older string with same hash index. To limit the size of this - * array to 64K, this link is maintained only for the last 32K strings. - * An index in this array is thus a window index modulo 32K. - */ - - Posf *head; /* Heads of the hash chains or NIL. */ - - uInt ins_h; /* hash index of string to be inserted */ - uInt hash_size; /* number of elements in hash table */ - uInt hash_bits; /* log2(hash_size) */ - uInt hash_mask; /* hash_size-1 */ - - uInt hash_shift; - /* Number of bits by which ins_h must be shifted at each input - * step. It must be such that after MIN_MATCH steps, the oldest - * byte no longer takes part in the hash key, that is: - * hash_shift * MIN_MATCH >= hash_bits - */ - - long block_start; - /* Window position at the beginning of the current output block. Gets - * negative when the window is moved backwards. - */ - - uInt match_length; /* length of best match */ - IPos prev_match; /* previous match */ - int match_available; /* set if previous match exists */ - uInt strstart; /* start of string to insert */ - uInt match_start; /* start of matching string */ - uInt lookahead; /* number of valid bytes ahead in window */ - - uInt prev_length; - /* Length of the best match at previous step. Matches not greater than this - * are discarded. This is used in the lazy match evaluation. - */ - - uInt max_chain_length; - /* To speed up deflation, hash chains are never searched beyond this - * length. A higher limit improves compression ratio but degrades the - * speed. - */ - - uInt max_lazy_match; - /* Attempt to find a better match only when the current match is strictly - * smaller than this value. This mechanism is used only for compression - * levels >= 4. - */ -# define max_insert_length max_lazy_match - /* Insert new strings in the hash table only if the match length is not - * greater than this length. This saves time but degrades compression. - * max_insert_length is used only for compression levels <= 3. - */ - - int level; /* compression level (1..9) */ - int strategy; /* favor or force Huffman coding*/ - - uInt good_match; - /* Use a faster search when the previous match is longer than this */ - - int nice_match; /* Stop searching when current match exceeds this */ - - /* used by trees.c: */ - /* Didn't use ct_data typedef below to supress compiler warning */ - struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */ - struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */ - struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */ - - struct tree_desc_s l_desc; /* desc. for literal tree */ - struct tree_desc_s d_desc; /* desc. for distance tree */ - struct tree_desc_s bl_desc; /* desc. for bit length tree */ - - ush bl_count[MAX_BITS+1]; - /* number of codes at each bit length for an optimal tree */ - - int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */ - int heap_len; /* number of elements in the heap */ - int heap_max; /* element of largest frequency */ - /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used. - * The same heap array is used to build all trees. - */ - - uch depth[2*L_CODES+1]; - /* Depth of each subtree used as tie breaker for trees of equal frequency - */ - - uchf *l_buf; /* buffer for literals or lengths */ - - uInt lit_bufsize; - /* Size of match buffer for literals/lengths. There are 4 reasons for - * limiting lit_bufsize to 64K: - * - frequencies can be kept in 16 bit counters - * - if compression is not successful for the first block, all input - * data is still in the window so we can still emit a stored block even - * when input comes from standard input. (This can also be done for - * all blocks if lit_bufsize is not greater than 32K.) - * - if compression is not successful for a file smaller than 64K, we can - * even emit a stored file instead of a stored block (saving 5 bytes). - * This is applicable only for zip (not gzip or zlib). - * - creating new Huffman trees less frequently may not provide fast - * adaptation to changes in the input data statistics. (Take for - * example a binary file with poorly compressible code followed by - * a highly compressible string table.) Smaller buffer sizes give - * fast adaptation but have of course the overhead of transmitting - * trees more frequently. - * - I can't count above 4 - */ - - uInt last_lit; /* running index in l_buf */ - - ushf *d_buf; - /* Buffer for distances. To simplify the code, d_buf and l_buf have - * the same number of elements. To use different lengths, an extra flag - * array would be necessary. - */ - - ulg opt_len; /* bit length of current block with optimal trees */ - ulg static_len; /* bit length of current block with static trees */ - uInt matches; /* number of string matches in current block */ - int last_eob_len; /* bit length of EOB code for last block */ - -#ifdef DEBUG - ulg compressed_len; /* total bit length of compressed file mod 2^32 */ - ulg bits_sent; /* bit length of compressed data sent mod 2^32 */ -#endif - - ush bi_buf; - /* Output buffer. bits are inserted starting at the bottom (least - * significant bits). - */ - int bi_valid; - /* Number of valid bits in bi_buf. All bits above the last valid bit - * are always zero. - */ - -} FAR deflate_state; - -/* Output a byte on the stream. - * IN assertion: there is enough room in pending_buf. - */ -#define put_byte(s, c) {s->pending_buf[s->pending++] = (c);} - - -#define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1) -/* Minimum amount of lookahead, except at the end of the input file. - * See deflate.c for comments about the MIN_MATCH+1. - */ - -#define MAX_DIST(s) ((s)->w_size-MIN_LOOKAHEAD) -/* In order to simplify the code, particularly on 16 bit machines, match - * distances are limited to MAX_DIST instead of WSIZE. - */ - - /* in trees.c */ -void _tr_init OF((deflate_state *s)); -int _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc)); -void _tr_flush_block OF((deflate_state *s, charf *buf, ulg stored_len, - int eof)); -void _tr_align OF((deflate_state *s)); -void _tr_stored_block OF((deflate_state *s, charf *buf, ulg stored_len, - int eof)); - -#define d_code(dist) \ - ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)]) -/* Mapping from a distance to a distance code. dist is the distance - 1 and - * must not have side effects. _dist_code[256] and _dist_code[257] are never - * used. - */ - -#ifndef DEBUG -/* Inline versions of _tr_tally for speed: */ - -#if defined(GEN_TREES_H) || !defined(STDC) - extern uch _length_code[]; - extern uch _dist_code[]; -#else - extern const uch _length_code[]; - extern const uch _dist_code[]; -#endif - -# define _tr_tally_lit(s, c, flush) \ - { uch cc = (c); \ - s->d_buf[s->last_lit] = 0; \ - s->l_buf[s->last_lit++] = cc; \ - s->dyn_ltree[cc].Freq++; \ - flush = (s->last_lit == s->lit_bufsize-1); \ - } -# define _tr_tally_dist(s, distance, length, flush) \ - { uch len = (length); \ - ush dist = (distance); \ - s->d_buf[s->last_lit] = dist; \ - s->l_buf[s->last_lit++] = len; \ - dist--; \ - s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \ - s->dyn_dtree[d_code(dist)].Freq++; \ - flush = (s->last_lit == s->lit_bufsize-1); \ - } -#else -# define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c) -# define _tr_tally_dist(s, distance, length, flush) \ - flush = _tr_tally(s, distance, length) -#endif - -#endif /* DEFLATE_H */ +/* deflate.h -- internal compression state + * Copyright (C) 1995-2004 Jean-loup Gailly + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* WARNING: this file should *not* be used by applications. It is + part of the implementation of the compression library and is + subject to change. Applications should only use zlib.h. + */ + +/* @(#) $Id: //poco/1.2/Foundation/src/deflate.h#1 $ */ + +#ifndef DEFLATE_H +#define DEFLATE_H + +#include "zutil.h" + +/* define NO_GZIP when compiling if you want to disable gzip header and + trailer creation by deflate(). NO_GZIP would be used to avoid linking in + the crc code when it is not needed. For shared libraries, gzip encoding + should be left enabled. */ +#ifndef NO_GZIP +# define GZIP +#endif + +/* =========================================================================== + * Internal compression state. + */ + +#define LENGTH_CODES 29 +/* number of length codes, not counting the special END_BLOCK code */ + +#define LITERALS 256 +/* number of literal bytes 0..255 */ + +#define L_CODES (LITERALS+1+LENGTH_CODES) +/* number of Literal or Length codes, including the END_BLOCK code */ + +#define D_CODES 30 +/* number of distance codes */ + +#define BL_CODES 19 +/* number of codes used to transfer the bit lengths */ + +#define HEAP_SIZE (2*L_CODES+1) +/* maximum heap size */ + +#define MAX_BITS 15 +/* All codes must not exceed MAX_BITS bits */ + +#define INIT_STATE 42 +#define EXTRA_STATE 69 +#define NAME_STATE 73 +#define COMMENT_STATE 91 +#define HCRC_STATE 103 +#define BUSY_STATE 113 +#define FINISH_STATE 666 +/* Stream status */ + + +/* Data structure describing a single value and its code string. */ +typedef struct ct_data_s { + union { + ush freq; /* frequency count */ + ush code; /* bit string */ + } fc; + union { + ush dad; /* father node in Huffman tree */ + ush len; /* length of bit string */ + } dl; +} FAR ct_data; + +#define Freq fc.freq +#define Code fc.code +#define Dad dl.dad +#define Len dl.len + +typedef struct static_tree_desc_s static_tree_desc; + +typedef struct tree_desc_s { + ct_data *dyn_tree; /* the dynamic tree */ + int max_code; /* largest code with non zero frequency */ + static_tree_desc *stat_desc; /* the corresponding static tree */ +} FAR tree_desc; + +typedef ush Pos; +typedef Pos FAR Posf; +typedef unsigned IPos; + +/* A Pos is an index in the character window. We use short instead of int to + * save space in the various tables. IPos is used only for parameter passing. + */ + +typedef struct internal_state { + z_streamp strm; /* pointer back to this zlib stream */ + int status; /* as the name implies */ + Bytef *pending_buf; /* output still pending */ + ulg pending_buf_size; /* size of pending_buf */ + Bytef *pending_out; /* next pending byte to output to the stream */ + uInt pending; /* nb of bytes in the pending buffer */ + int wrap; /* bit 0 true for zlib, bit 1 true for gzip */ + gz_headerp gzhead; /* gzip header information to write */ + uInt gzindex; /* where in extra, name, or comment */ + Byte method; /* STORED (for zip only) or DEFLATED */ + int last_flush; /* value of flush param for previous deflate call */ + + /* used by deflate.c: */ + + uInt w_size; /* LZ77 window size (32K by default) */ + uInt w_bits; /* log2(w_size) (8..16) */ + uInt w_mask; /* w_size - 1 */ + + Bytef *window; + /* Sliding window. Input bytes are read into the second half of the window, + * and move to the first half later to keep a dictionary of at least wSize + * bytes. With this organization, matches are limited to a distance of + * wSize-MAX_MATCH bytes, but this ensures that IO is always + * performed with a length multiple of the block size. Also, it limits + * the window size to 64K, which is quite useful on MSDOS. + * To do: use the user input buffer as sliding window. + */ + + ulg window_size; + /* Actual size of window: 2*wSize, except when the user input buffer + * is directly used as sliding window. + */ + + Posf *prev; + /* Link to older string with same hash index. To limit the size of this + * array to 64K, this link is maintained only for the last 32K strings. + * An index in this array is thus a window index modulo 32K. + */ + + Posf *head; /* Heads of the hash chains or NIL. */ + + uInt ins_h; /* hash index of string to be inserted */ + uInt hash_size; /* number of elements in hash table */ + uInt hash_bits; /* log2(hash_size) */ + uInt hash_mask; /* hash_size-1 */ + + uInt hash_shift; + /* Number of bits by which ins_h must be shifted at each input + * step. It must be such that after MIN_MATCH steps, the oldest + * byte no longer takes part in the hash key, that is: + * hash_shift * MIN_MATCH >= hash_bits + */ + + long block_start; + /* Window position at the beginning of the current output block. Gets + * negative when the window is moved backwards. + */ + + uInt match_length; /* length of best match */ + IPos prev_match; /* previous match */ + int match_available; /* set if previous match exists */ + uInt strstart; /* start of string to insert */ + uInt match_start; /* start of matching string */ + uInt lookahead; /* number of valid bytes ahead in window */ + + uInt prev_length; + /* Length of the best match at previous step. Matches not greater than this + * are discarded. This is used in the lazy match evaluation. + */ + + uInt max_chain_length; + /* To speed up deflation, hash chains are never searched beyond this + * length. A higher limit improves compression ratio but degrades the + * speed. + */ + + uInt max_lazy_match; + /* Attempt to find a better match only when the current match is strictly + * smaller than this value. This mechanism is used only for compression + * levels >= 4. + */ +# define max_insert_length max_lazy_match + /* Insert new strings in the hash table only if the match length is not + * greater than this length. This saves time but degrades compression. + * max_insert_length is used only for compression levels <= 3. + */ + + int level; /* compression level (1..9) */ + int strategy; /* favor or force Huffman coding*/ + + uInt good_match; + /* Use a faster search when the previous match is longer than this */ + + int nice_match; /* Stop searching when current match exceeds this */ + + /* used by trees.c: */ + /* Didn't use ct_data typedef below to supress compiler warning */ + struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */ + struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */ + struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */ + + struct tree_desc_s l_desc; /* desc. for literal tree */ + struct tree_desc_s d_desc; /* desc. for distance tree */ + struct tree_desc_s bl_desc; /* desc. for bit length tree */ + + ush bl_count[MAX_BITS+1]; + /* number of codes at each bit length for an optimal tree */ + + int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */ + int heap_len; /* number of elements in the heap */ + int heap_max; /* element of largest frequency */ + /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used. + * The same heap array is used to build all trees. + */ + + uch depth[2*L_CODES+1]; + /* Depth of each subtree used as tie breaker for trees of equal frequency + */ + + uchf *l_buf; /* buffer for literals or lengths */ + + uInt lit_bufsize; + /* Size of match buffer for literals/lengths. There are 4 reasons for + * limiting lit_bufsize to 64K: + * - frequencies can be kept in 16 bit counters + * - if compression is not successful for the first block, all input + * data is still in the window so we can still emit a stored block even + * when input comes from standard input. (This can also be done for + * all blocks if lit_bufsize is not greater than 32K.) + * - if compression is not successful for a file smaller than 64K, we can + * even emit a stored file instead of a stored block (saving 5 bytes). + * This is applicable only for zip (not gzip or zlib). + * - creating new Huffman trees less frequently may not provide fast + * adaptation to changes in the input data statistics. (Take for + * example a binary file with poorly compressible code followed by + * a highly compressible string table.) Smaller buffer sizes give + * fast adaptation but have of course the overhead of transmitting + * trees more frequently. + * - I can't count above 4 + */ + + uInt last_lit; /* running index in l_buf */ + + ushf *d_buf; + /* Buffer for distances. To simplify the code, d_buf and l_buf have + * the same number of elements. To use different lengths, an extra flag + * array would be necessary. + */ + + ulg opt_len; /* bit length of current block with optimal trees */ + ulg static_len; /* bit length of current block with static trees */ + uInt matches; /* number of string matches in current block */ + int last_eob_len; /* bit length of EOB code for last block */ + +#ifdef DEBUG + ulg compressed_len; /* total bit length of compressed file mod 2^32 */ + ulg bits_sent; /* bit length of compressed data sent mod 2^32 */ +#endif + + ush bi_buf; + /* Output buffer. bits are inserted starting at the bottom (least + * significant bits). + */ + int bi_valid; + /* Number of valid bits in bi_buf. All bits above the last valid bit + * are always zero. + */ + +} FAR deflate_state; + +/* Output a byte on the stream. + * IN assertion: there is enough room in pending_buf. + */ +#define put_byte(s, c) {s->pending_buf[s->pending++] = (c);} + + +#define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1) +/* Minimum amount of lookahead, except at the end of the input file. + * See deflate.c for comments about the MIN_MATCH+1. + */ + +#define MAX_DIST(s) ((s)->w_size-MIN_LOOKAHEAD) +/* In order to simplify the code, particularly on 16 bit machines, match + * distances are limited to MAX_DIST instead of WSIZE. + */ + + /* in trees.c */ +void _tr_init OF((deflate_state *s)); +int _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc)); +void _tr_flush_block OF((deflate_state *s, charf *buf, ulg stored_len, + int eof)); +void _tr_align OF((deflate_state *s)); +void _tr_stored_block OF((deflate_state *s, charf *buf, ulg stored_len, + int eof)); + +#define d_code(dist) \ + ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)]) +/* Mapping from a distance to a distance code. dist is the distance - 1 and + * must not have side effects. _dist_code[256] and _dist_code[257] are never + * used. + */ + +#ifndef DEBUG +/* Inline versions of _tr_tally for speed: */ + +#if defined(GEN_TREES_H) || !defined(STDC) + extern uch _length_code[]; + extern uch _dist_code[]; +#else + extern const uch _length_code[]; + extern const uch _dist_code[]; +#endif + +# define _tr_tally_lit(s, c, flush) \ + { uch cc = (c); \ + s->d_buf[s->last_lit] = 0; \ + s->l_buf[s->last_lit++] = cc; \ + s->dyn_ltree[cc].Freq++; \ + flush = (s->last_lit == s->lit_bufsize-1); \ + } +# define _tr_tally_dist(s, distance, length, flush) \ + { uch len = (length); \ + ush dist = (distance); \ + s->d_buf[s->last_lit] = dist; \ + s->l_buf[s->last_lit++] = len; \ + dist--; \ + s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \ + s->dyn_dtree[d_code(dist)].Freq++; \ + flush = (s->last_lit == s->lit_bufsize-1); \ + } +#else +# define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c) +# define _tr_tally_dist(s, distance, length, flush) \ + flush = _tr_tally(s, distance, length) +#endif + +#endif /* DEFLATE_H */ diff --git a/Foundation/src/get.c b/Foundation/src/get.c index bf1c9f9a3..418c6b888 100644 --- a/Foundation/src/get.c +++ b/Foundation/src/get.c @@ -1,357 +1,357 @@ -/************************************************* -* Perl-Compatible Regular Expressions * -*************************************************/ - -/* -This is a library of functions to support regular expressions whose syntax -and semantics are as close as possible to those of the Perl 5 language. See -the file Tech.Notes for some information on the internals. - -Written by: Philip Hazel - - Copyright (c) 1997-2003 University of Cambridge - ------------------------------------------------------------------------------ -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - * 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. - - * Neither the name of the University of Cambridge nor the names of its - contributors may be used to endorse or promote products derived from - this software without specific prior written permission. - -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. ------------------------------------------------------------------------------ -*/ - -/* This module contains some convenience functions for extracting substrings -from the subject string after a regex match has succeeded. The original idea -for these functions came from Scott Wimer. */ - - -/* Include the internals header, which itself includes Standard C headers plus -the external pcre header. */ - -#include "pcreinternal.h" - - -/************************************************* -* Find number for named string * -*************************************************/ - -/* This function is used by the two extraction functions below, as well -as being generally available. - -Arguments: - code the compiled regex - stringname the name whose number is required - -Returns: the number of the named parentheses, or a negative number - (PCRE_ERROR_NOSUBSTRING) if not found -*/ - -int -pcre_get_stringnumber(const pcre *code, const char *stringname) -{ -int rc; -int entrysize; -int top, bot; -uschar *nametable; - -if ((rc = pcre_fullinfo(code, NULL, PCRE_INFO_NAMECOUNT, &top)) != 0) - return rc; -if (top <= 0) return PCRE_ERROR_NOSUBSTRING; - -if ((rc = pcre_fullinfo(code, NULL, PCRE_INFO_NAMEENTRYSIZE, &entrysize)) != 0) - return rc; -if ((rc = pcre_fullinfo(code, NULL, PCRE_INFO_NAMETABLE, &nametable)) != 0) - return rc; - -bot = 0; -while (top > bot) - { - int mid = (top + bot) / 2; - uschar *entry = nametable + entrysize*mid; - int c = strcmp(stringname, (char *)(entry + 2)); - if (c == 0) return (entry[0] << 8) + entry[1]; - if (c > 0) bot = mid + 1; else top = mid; - } - -return PCRE_ERROR_NOSUBSTRING; -} - - - -/************************************************* -* Copy captured string to given buffer * -*************************************************/ - -/* This function copies a single captured substring into a given buffer. -Note that we use memcpy() rather than strncpy() in case there are binary zeros -in the string. - -Arguments: - subject the subject string that was matched - ovector pointer to the offsets table - stringcount the number of substrings that were captured - (i.e. the yield of the pcre_exec call, unless - that was zero, in which case it should be 1/3 - of the offset table size) - stringnumber the number of the required substring - buffer where to put the substring - size the size of the buffer - -Returns: if successful: - the length of the copied string, not including the zero - that is put on the end; can be zero - if not successful: - PCRE_ERROR_NOMEMORY (-6) buffer too small - PCRE_ERROR_NOSUBSTRING (-7) no such captured substring -*/ - -int -pcre_copy_substring(const char *subject, int *ovector, int stringcount, - int stringnumber, char *buffer, int size) -{ -int yield; -if (stringnumber < 0 || stringnumber >= stringcount) - return PCRE_ERROR_NOSUBSTRING; -stringnumber *= 2; -yield = ovector[stringnumber+1] - ovector[stringnumber]; -if (size < yield + 1) return PCRE_ERROR_NOMEMORY; -memcpy(buffer, subject + ovector[stringnumber], yield); -buffer[yield] = 0; -return yield; -} - - - -/************************************************* -* Copy named captured string to given buffer * -*************************************************/ - -/* This function copies a single captured substring into a given buffer, -identifying it by name. - -Arguments: - code the compiled regex - subject the subject string that was matched - ovector pointer to the offsets table - stringcount the number of substrings that were captured - (i.e. the yield of the pcre_exec call, unless - that was zero, in which case it should be 1/3 - of the offset table size) - stringname the name of the required substring - buffer where to put the substring - size the size of the buffer - -Returns: if successful: - the length of the copied string, not including the zero - that is put on the end; can be zero - if not successful: - PCRE_ERROR_NOMEMORY (-6) buffer too small - PCRE_ERROR_NOSUBSTRING (-7) no such captured substring -*/ - -int -pcre_copy_named_substring(const pcre *code, const char *subject, int *ovector, - int stringcount, const char *stringname, char *buffer, int size) -{ -int n = pcre_get_stringnumber(code, stringname); -if (n <= 0) return n; -return pcre_copy_substring(subject, ovector, stringcount, n, buffer, size); -} - - - -/************************************************* -* Copy all captured strings to new store * -*************************************************/ - -/* This function gets one chunk of store and builds a list of pointers and all -of the captured substrings in it. A NULL pointer is put on the end of the list. - -Arguments: - subject the subject string that was matched - ovector pointer to the offsets table - stringcount the number of substrings that were captured - (i.e. the yield of the pcre_exec call, unless - that was zero, in which case it should be 1/3 - of the offset table size) - listptr set to point to the list of pointers - -Returns: if successful: 0 - if not successful: - PCRE_ERROR_NOMEMORY (-6) failed to get store -*/ - -int -pcre_get_substring_list(const char *subject, int *ovector, int stringcount, - const char ***listptr) -{ -int i; -int size = sizeof(char *); -int double_count = stringcount * 2; -char **stringlist; -char *p; - -for (i = 0; i < double_count; i += 2) - size += sizeof(char *) + ovector[i+1] - ovector[i] + 1; - -stringlist = (char **)(pcre_malloc)(size); -if (stringlist == NULL) return PCRE_ERROR_NOMEMORY; - -*listptr = (const char **)stringlist; -p = (char *)(stringlist + stringcount + 1); - -for (i = 0; i < double_count; i += 2) - { - int len = ovector[i+1] - ovector[i]; - memcpy(p, subject + ovector[i], len); - *stringlist++ = p; - p += len; - *p++ = 0; - } - -*stringlist = NULL; -return 0; -} - - - -/************************************************* -* Free store obtained by get_substring_list * -*************************************************/ - -/* This function exists for the benefit of people calling PCRE from non-C -programs that can call its functions, but not free() or (pcre_free)() directly. - -Argument: the result of a previous pcre_get_substring_list() -Returns: nothing -*/ - -void -pcre_free_substring_list(const char **pointer) -{ -(pcre_free)((void *)pointer); -} - - - -/************************************************* -* Copy captured string to new store * -*************************************************/ - -/* This function copies a single captured substring into a piece of new -store - -Arguments: - subject the subject string that was matched - ovector pointer to the offsets table - stringcount the number of substrings that were captured - (i.e. the yield of the pcre_exec call, unless - that was zero, in which case it should be 1/3 - of the offset table size) - stringnumber the number of the required substring - stringptr where to put a pointer to the substring - -Returns: if successful: - the length of the string, not including the zero that - is put on the end; can be zero - if not successful: - PCRE_ERROR_NOMEMORY (-6) failed to get store - PCRE_ERROR_NOSUBSTRING (-7) substring not present -*/ - -int -pcre_get_substring(const char *subject, int *ovector, int stringcount, - int stringnumber, const char **stringptr) -{ -int yield; -char *substring; -if (stringnumber < 0 || stringnumber >= stringcount) - return PCRE_ERROR_NOSUBSTRING; -stringnumber *= 2; -yield = ovector[stringnumber+1] - ovector[stringnumber]; -substring = (char *)(pcre_malloc)(yield + 1); -if (substring == NULL) return PCRE_ERROR_NOMEMORY; -memcpy(substring, subject + ovector[stringnumber], yield); -substring[yield] = 0; -*stringptr = substring; -return yield; -} - - - -/************************************************* -* Copy named captured string to new store * -*************************************************/ - -/* This function copies a single captured substring, identified by name, into -new store. - -Arguments: - code the compiled regex - subject the subject string that was matched - ovector pointer to the offsets table - stringcount the number of substrings that were captured - (i.e. the yield of the pcre_exec call, unless - that was zero, in which case it should be 1/3 - of the offset table size) - stringname the name of the required substring - stringptr where to put the pointer - -Returns: if successful: - the length of the copied string, not including the zero - that is put on the end; can be zero - if not successful: - PCRE_ERROR_NOMEMORY (-6) couldn't get memory - PCRE_ERROR_NOSUBSTRING (-7) no such captured substring -*/ - -int -pcre_get_named_substring(const pcre *code, const char *subject, int *ovector, - int stringcount, const char *stringname, const char **stringptr) -{ -int n = pcre_get_stringnumber(code, stringname); -if (n <= 0) return n; -return pcre_get_substring(subject, ovector, stringcount, n, stringptr); -} - - - - -/************************************************* -* Free store obtained by get_substring * -*************************************************/ - -/* This function exists for the benefit of people calling PCRE from non-C -programs that can call its functions, but not free() or (pcre_free)() directly. - -Argument: the result of a previous pcre_get_substring() -Returns: nothing -*/ - -void -pcre_free_substring(const char *pointer) -{ -(pcre_free)((void *)pointer); -} - -/* End of get.c */ +/************************************************* +* Perl-Compatible Regular Expressions * +*************************************************/ + +/* +This is a library of functions to support regular expressions whose syntax +and semantics are as close as possible to those of the Perl 5 language. See +the file Tech.Notes for some information on the internals. + +Written by: Philip Hazel + + Copyright (c) 1997-2003 University of Cambridge + +----------------------------------------------------------------------------- +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + * 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. + + * Neither the name of the University of Cambridge nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +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. +----------------------------------------------------------------------------- +*/ + +/* This module contains some convenience functions for extracting substrings +from the subject string after a regex match has succeeded. The original idea +for these functions came from Scott Wimer. */ + + +/* Include the internals header, which itself includes Standard C headers plus +the external pcre header. */ + +#include "pcreinternal.h" + + +/************************************************* +* Find number for named string * +*************************************************/ + +/* This function is used by the two extraction functions below, as well +as being generally available. + +Arguments: + code the compiled regex + stringname the name whose number is required + +Returns: the number of the named parentheses, or a negative number + (PCRE_ERROR_NOSUBSTRING) if not found +*/ + +int +pcre_get_stringnumber(const pcre *code, const char *stringname) +{ +int rc; +int entrysize; +int top, bot; +uschar *nametable; + +if ((rc = pcre_fullinfo(code, NULL, PCRE_INFO_NAMECOUNT, &top)) != 0) + return rc; +if (top <= 0) return PCRE_ERROR_NOSUBSTRING; + +if ((rc = pcre_fullinfo(code, NULL, PCRE_INFO_NAMEENTRYSIZE, &entrysize)) != 0) + return rc; +if ((rc = pcre_fullinfo(code, NULL, PCRE_INFO_NAMETABLE, &nametable)) != 0) + return rc; + +bot = 0; +while (top > bot) + { + int mid = (top + bot) / 2; + uschar *entry = nametable + entrysize*mid; + int c = strcmp(stringname, (char *)(entry + 2)); + if (c == 0) return (entry[0] << 8) + entry[1]; + if (c > 0) bot = mid + 1; else top = mid; + } + +return PCRE_ERROR_NOSUBSTRING; +} + + + +/************************************************* +* Copy captured string to given buffer * +*************************************************/ + +/* This function copies a single captured substring into a given buffer. +Note that we use memcpy() rather than strncpy() in case there are binary zeros +in the string. + +Arguments: + subject the subject string that was matched + ovector pointer to the offsets table + stringcount the number of substrings that were captured + (i.e. the yield of the pcre_exec call, unless + that was zero, in which case it should be 1/3 + of the offset table size) + stringnumber the number of the required substring + buffer where to put the substring + size the size of the buffer + +Returns: if successful: + the length of the copied string, not including the zero + that is put on the end; can be zero + if not successful: + PCRE_ERROR_NOMEMORY (-6) buffer too small + PCRE_ERROR_NOSUBSTRING (-7) no such captured substring +*/ + +int +pcre_copy_substring(const char *subject, int *ovector, int stringcount, + int stringnumber, char *buffer, int size) +{ +int yield; +if (stringnumber < 0 || stringnumber >= stringcount) + return PCRE_ERROR_NOSUBSTRING; +stringnumber *= 2; +yield = ovector[stringnumber+1] - ovector[stringnumber]; +if (size < yield + 1) return PCRE_ERROR_NOMEMORY; +memcpy(buffer, subject + ovector[stringnumber], yield); +buffer[yield] = 0; +return yield; +} + + + +/************************************************* +* Copy named captured string to given buffer * +*************************************************/ + +/* This function copies a single captured substring into a given buffer, +identifying it by name. + +Arguments: + code the compiled regex + subject the subject string that was matched + ovector pointer to the offsets table + stringcount the number of substrings that were captured + (i.e. the yield of the pcre_exec call, unless + that was zero, in which case it should be 1/3 + of the offset table size) + stringname the name of the required substring + buffer where to put the substring + size the size of the buffer + +Returns: if successful: + the length of the copied string, not including the zero + that is put on the end; can be zero + if not successful: + PCRE_ERROR_NOMEMORY (-6) buffer too small + PCRE_ERROR_NOSUBSTRING (-7) no such captured substring +*/ + +int +pcre_copy_named_substring(const pcre *code, const char *subject, int *ovector, + int stringcount, const char *stringname, char *buffer, int size) +{ +int n = pcre_get_stringnumber(code, stringname); +if (n <= 0) return n; +return pcre_copy_substring(subject, ovector, stringcount, n, buffer, size); +} + + + +/************************************************* +* Copy all captured strings to new store * +*************************************************/ + +/* This function gets one chunk of store and builds a list of pointers and all +of the captured substrings in it. A NULL pointer is put on the end of the list. + +Arguments: + subject the subject string that was matched + ovector pointer to the offsets table + stringcount the number of substrings that were captured + (i.e. the yield of the pcre_exec call, unless + that was zero, in which case it should be 1/3 + of the offset table size) + listptr set to point to the list of pointers + +Returns: if successful: 0 + if not successful: + PCRE_ERROR_NOMEMORY (-6) failed to get store +*/ + +int +pcre_get_substring_list(const char *subject, int *ovector, int stringcount, + const char ***listptr) +{ +int i; +int size = sizeof(char *); +int double_count = stringcount * 2; +char **stringlist; +char *p; + +for (i = 0; i < double_count; i += 2) + size += sizeof(char *) + ovector[i+1] - ovector[i] + 1; + +stringlist = (char **)(pcre_malloc)(size); +if (stringlist == NULL) return PCRE_ERROR_NOMEMORY; + +*listptr = (const char **)stringlist; +p = (char *)(stringlist + stringcount + 1); + +for (i = 0; i < double_count; i += 2) + { + int len = ovector[i+1] - ovector[i]; + memcpy(p, subject + ovector[i], len); + *stringlist++ = p; + p += len; + *p++ = 0; + } + +*stringlist = NULL; +return 0; +} + + + +/************************************************* +* Free store obtained by get_substring_list * +*************************************************/ + +/* This function exists for the benefit of people calling PCRE from non-C +programs that can call its functions, but not free() or (pcre_free)() directly. + +Argument: the result of a previous pcre_get_substring_list() +Returns: nothing +*/ + +void +pcre_free_substring_list(const char **pointer) +{ +(pcre_free)((void *)pointer); +} + + + +/************************************************* +* Copy captured string to new store * +*************************************************/ + +/* This function copies a single captured substring into a piece of new +store + +Arguments: + subject the subject string that was matched + ovector pointer to the offsets table + stringcount the number of substrings that were captured + (i.e. the yield of the pcre_exec call, unless + that was zero, in which case it should be 1/3 + of the offset table size) + stringnumber the number of the required substring + stringptr where to put a pointer to the substring + +Returns: if successful: + the length of the string, not including the zero that + is put on the end; can be zero + if not successful: + PCRE_ERROR_NOMEMORY (-6) failed to get store + PCRE_ERROR_NOSUBSTRING (-7) substring not present +*/ + +int +pcre_get_substring(const char *subject, int *ovector, int stringcount, + int stringnumber, const char **stringptr) +{ +int yield; +char *substring; +if (stringnumber < 0 || stringnumber >= stringcount) + return PCRE_ERROR_NOSUBSTRING; +stringnumber *= 2; +yield = ovector[stringnumber+1] - ovector[stringnumber]; +substring = (char *)(pcre_malloc)(yield + 1); +if (substring == NULL) return PCRE_ERROR_NOMEMORY; +memcpy(substring, subject + ovector[stringnumber], yield); +substring[yield] = 0; +*stringptr = substring; +return yield; +} + + + +/************************************************* +* Copy named captured string to new store * +*************************************************/ + +/* This function copies a single captured substring, identified by name, into +new store. + +Arguments: + code the compiled regex + subject the subject string that was matched + ovector pointer to the offsets table + stringcount the number of substrings that were captured + (i.e. the yield of the pcre_exec call, unless + that was zero, in which case it should be 1/3 + of the offset table size) + stringname the name of the required substring + stringptr where to put the pointer + +Returns: if successful: + the length of the copied string, not including the zero + that is put on the end; can be zero + if not successful: + PCRE_ERROR_NOMEMORY (-6) couldn't get memory + PCRE_ERROR_NOSUBSTRING (-7) no such captured substring +*/ + +int +pcre_get_named_substring(const pcre *code, const char *subject, int *ovector, + int stringcount, const char *stringname, const char **stringptr) +{ +int n = pcre_get_stringnumber(code, stringname); +if (n <= 0) return n; +return pcre_get_substring(subject, ovector, stringcount, n, stringptr); +} + + + + +/************************************************* +* Free store obtained by get_substring * +*************************************************/ + +/* This function exists for the benefit of people calling PCRE from non-C +programs that can call its functions, but not free() or (pcre_free)() directly. + +Argument: the result of a previous pcre_get_substring() +Returns: nothing +*/ + +void +pcre_free_substring(const char *pointer) +{ +(pcre_free)((void *)pointer); +} + +/* End of get.c */ diff --git a/Foundation/src/gzio.c b/Foundation/src/gzio.c index 27db80189..8ee01c05c 100644 --- a/Foundation/src/gzio.c +++ b/Foundation/src/gzio.c @@ -1,1026 +1,1026 @@ -/* gzio.c -- IO on .gz files - * Copyright (C) 1995-2005 Jean-loup Gailly. - * For conditions of distribution and use, see copyright notice in zlib.h - * - * Compile this file with -DNO_GZCOMPRESS to avoid the compression code. - */ - -/* @(#) $Id: //poco/1.2/Foundation/src/gzio.c#1 $ */ - -#include - -#include "zutil.h" - -#ifdef NO_DEFLATE /* for compatibility with old definition */ -# define NO_GZCOMPRESS -#endif - -#ifndef NO_DUMMY_DECL -struct internal_state {int dummy;}; /* for buggy compilers */ -#endif - -#ifndef Z_BUFSIZE -# ifdef MAXSEG_64K -# define Z_BUFSIZE 4096 /* minimize memory usage for 16-bit DOS */ -# else -# define Z_BUFSIZE 16384 -# endif -#endif -#ifndef Z_PRINTF_BUFSIZE -# define Z_PRINTF_BUFSIZE 4096 -#endif - -#ifdef __MVS__ -# pragma map (fdopen , "\174\174FDOPEN") - FILE *fdopen(int, const char *); -#endif - -#ifndef STDC -extern voidp malloc OF((uInt size)); -extern void free OF((voidpf ptr)); -#endif - -#define ALLOC(size) malloc(size) -#define TRYFREE(p) {if (p) free(p);} - -static int const gz_magic[2] = {0x1f, 0x8b}; /* gzip magic header */ - -/* gzip flag byte */ -#define ASCII_FLAG 0x01 /* bit 0 set: file probably ascii text */ -#define HEAD_CRC 0x02 /* bit 1 set: header CRC present */ -#define EXTRA_FIELD 0x04 /* bit 2 set: extra field present */ -#define ORIG_NAME 0x08 /* bit 3 set: original file name present */ -#define COMMENT 0x10 /* bit 4 set: file comment present */ -#define RESERVED 0xE0 /* bits 5..7: reserved */ - -typedef struct gz_stream { - z_stream stream; - int z_err; /* error code for last stream operation */ - int z_eof; /* set if end of input file */ - FILE *file; /* .gz file */ - Byte *inbuf; /* input buffer */ - Byte *outbuf; /* output buffer */ - uLong crc; /* crc32 of uncompressed data */ - char *msg; /* error message */ - char *path; /* path name for debugging only */ - int transparent; /* 1 if input file is not a .gz file */ - char mode; /* 'w' or 'r' */ - z_off_t start; /* start of compressed data in file (header skipped) */ - z_off_t in; /* bytes into deflate or inflate */ - z_off_t out; /* bytes out of deflate or inflate */ - int back; /* one character push-back */ - int last; /* true if push-back is last character */ -} gz_stream; - - -local gzFile gz_open OF((const char *path, const char *mode, int fd)); -local int do_flush OF((gzFile file, int flush)); -local int get_byte OF((gz_stream *s)); -local void check_header OF((gz_stream *s)); -local int destroy OF((gz_stream *s)); -local void putLong OF((FILE *file, uLong x)); -local uLong getLong OF((gz_stream *s)); - -/* =========================================================================== - Opens a gzip (.gz) file for reading or writing. The mode parameter - is as in fopen ("rb" or "wb"). The file is given either by file descriptor - or path name (if fd == -1). - gz_open returns NULL if the file could not be opened or if there was - insufficient memory to allocate the (de)compression state; errno - can be checked to distinguish the two cases (if errno is zero, the - zlib error is Z_MEM_ERROR). -*/ -local gzFile gz_open (path, mode, fd) - const char *path; - const char *mode; - int fd; -{ - int err; - int level = Z_DEFAULT_COMPRESSION; /* compression level */ - int strategy = Z_DEFAULT_STRATEGY; /* compression strategy */ - char *p = (char*)mode; - gz_stream *s; - char fmode[80]; /* copy of mode, without the compression level */ - char *m = fmode; - - if (!path || !mode) return Z_NULL; - - s = (gz_stream *)ALLOC(sizeof(gz_stream)); - if (!s) return Z_NULL; - - s->stream.zalloc = (alloc_func)0; - s->stream.zfree = (free_func)0; - s->stream.opaque = (voidpf)0; - s->stream.next_in = s->inbuf = Z_NULL; - s->stream.next_out = s->outbuf = Z_NULL; - s->stream.avail_in = s->stream.avail_out = 0; - s->file = NULL; - s->z_err = Z_OK; - s->z_eof = 0; - s->in = 0; - s->out = 0; - s->back = EOF; - s->crc = crc32(0L, Z_NULL, 0); - s->msg = NULL; - s->transparent = 0; - - s->path = (char*)ALLOC(strlen(path)+1); - if (s->path == NULL) { - return destroy(s), (gzFile)Z_NULL; - } - strcpy(s->path, path); /* do this early for debugging */ - - s->mode = '\0'; - do { - if (*p == 'r') s->mode = 'r'; - if (*p == 'w' || *p == 'a') s->mode = 'w'; - if (*p >= '0' && *p <= '9') { - level = *p - '0'; - } else if (*p == 'f') { - strategy = Z_FILTERED; - } else if (*p == 'h') { - strategy = Z_HUFFMAN_ONLY; - } else if (*p == 'R') { - strategy = Z_RLE; - } else { - *m++ = *p; /* copy the mode */ - } - } while (*p++ && m != fmode + sizeof(fmode)); - if (s->mode == '\0') return destroy(s), (gzFile)Z_NULL; - - if (s->mode == 'w') { -#ifdef NO_GZCOMPRESS - err = Z_STREAM_ERROR; -#else - err = deflateInit2(&(s->stream), level, - Z_DEFLATED, -MAX_WBITS, DEF_MEM_LEVEL, strategy); - /* windowBits is passed < 0 to suppress zlib header */ - - s->stream.next_out = s->outbuf = (Byte*)ALLOC(Z_BUFSIZE); -#endif - if (err != Z_OK || s->outbuf == Z_NULL) { - return destroy(s), (gzFile)Z_NULL; - } - } else { - s->stream.next_in = s->inbuf = (Byte*)ALLOC(Z_BUFSIZE); - - err = inflateInit2(&(s->stream), -MAX_WBITS); - /* windowBits is passed < 0 to tell that there is no zlib header. - * Note that in this case inflate *requires* an extra "dummy" byte - * after the compressed stream in order to complete decompression and - * return Z_STREAM_END. Here the gzip CRC32 ensures that 4 bytes are - * present after the compressed stream. - */ - if (err != Z_OK || s->inbuf == Z_NULL) { - return destroy(s), (gzFile)Z_NULL; - } - } - s->stream.avail_out = Z_BUFSIZE; - - errno = 0; - s->file = fd < 0 ? F_OPEN(path, fmode) : (FILE*)fdopen(fd, fmode); - - if (s->file == NULL) { - return destroy(s), (gzFile)Z_NULL; - } - if (s->mode == 'w') { - /* Write a very simple .gz header: - */ - fprintf(s->file, "%c%c%c%c%c%c%c%c%c%c", gz_magic[0], gz_magic[1], - Z_DEFLATED, 0 /*flags*/, 0,0,0,0 /*time*/, 0 /*xflags*/, OS_CODE); - s->start = 10L; - /* We use 10L instead of ftell(s->file) to because ftell causes an - * fflush on some systems. This version of the library doesn't use - * start anyway in write mode, so this initialization is not - * necessary. - */ - } else { - check_header(s); /* skip the .gz header */ - s->start = ftell(s->file) - s->stream.avail_in; - } - - return (gzFile)s; -} - -/* =========================================================================== - Opens a gzip (.gz) file for reading or writing. -*/ -gzFile ZEXPORT gzopen (path, mode) - const char *path; - const char *mode; -{ - return gz_open (path, mode, -1); -} - -/* =========================================================================== - Associate a gzFile with the file descriptor fd. fd is not dup'ed here - to mimic the behavio(u)r of fdopen. -*/ -gzFile ZEXPORT gzdopen (fd, mode) - int fd; - const char *mode; -{ - char name[46]; /* allow for up to 128-bit integers */ - - if (fd < 0) return (gzFile)Z_NULL; - sprintf(name, "", fd); /* for debugging */ - - return gz_open (name, mode, fd); -} - -/* =========================================================================== - * Update the compression level and strategy - */ -int ZEXPORT gzsetparams (file, level, strategy) - gzFile file; - int level; - int strategy; -{ - gz_stream *s = (gz_stream*)file; - - if (s == NULL || s->mode != 'w') return Z_STREAM_ERROR; - - /* Make room to allow flushing */ - if (s->stream.avail_out == 0) { - - s->stream.next_out = s->outbuf; - if (fwrite(s->outbuf, 1, Z_BUFSIZE, s->file) != Z_BUFSIZE) { - s->z_err = Z_ERRNO; - } - s->stream.avail_out = Z_BUFSIZE; - } - - return deflateParams (&(s->stream), level, strategy); -} - -/* =========================================================================== - Read a byte from a gz_stream; update next_in and avail_in. Return EOF - for end of file. - IN assertion: the stream s has been sucessfully opened for reading. -*/ -local int get_byte(s) - gz_stream *s; -{ - if (s->z_eof) return EOF; - if (s->stream.avail_in == 0) { - errno = 0; - s->stream.avail_in = (uInt)fread(s->inbuf, 1, Z_BUFSIZE, s->file); - if (s->stream.avail_in == 0) { - s->z_eof = 1; - if (ferror(s->file)) s->z_err = Z_ERRNO; - return EOF; - } - s->stream.next_in = s->inbuf; - } - s->stream.avail_in--; - return *(s->stream.next_in)++; -} - -/* =========================================================================== - Check the gzip header of a gz_stream opened for reading. Set the stream - mode to transparent if the gzip magic header is not present; set s->err - to Z_DATA_ERROR if the magic header is present but the rest of the header - is incorrect. - IN assertion: the stream s has already been created sucessfully; - s->stream.avail_in is zero for the first time, but may be non-zero - for concatenated .gz files. -*/ -local void check_header(s) - gz_stream *s; -{ - int method; /* method byte */ - int flags; /* flags byte */ - uInt len; - int c; - - /* Assure two bytes in the buffer so we can peek ahead -- handle case - where first byte of header is at the end of the buffer after the last - gzip segment */ - len = s->stream.avail_in; - if (len < 2) { - if (len) s->inbuf[0] = s->stream.next_in[0]; - errno = 0; - len = (uInt)fread(s->inbuf + len, 1, Z_BUFSIZE >> len, s->file); - if (len == 0 && ferror(s->file)) s->z_err = Z_ERRNO; - s->stream.avail_in += len; - s->stream.next_in = s->inbuf; - if (s->stream.avail_in < 2) { - s->transparent = s->stream.avail_in; - return; - } - } - - /* Peek ahead to check the gzip magic header */ - if (s->stream.next_in[0] != gz_magic[0] || - s->stream.next_in[1] != gz_magic[1]) { - s->transparent = 1; - return; - } - s->stream.avail_in -= 2; - s->stream.next_in += 2; - - /* Check the rest of the gzip header */ - method = get_byte(s); - flags = get_byte(s); - if (method != Z_DEFLATED || (flags & RESERVED) != 0) { - s->z_err = Z_DATA_ERROR; - return; - } - - /* Discard time, xflags and OS code: */ - for (len = 0; len < 6; len++) (void)get_byte(s); - - if ((flags & EXTRA_FIELD) != 0) { /* skip the extra field */ - len = (uInt)get_byte(s); - len += ((uInt)get_byte(s))<<8; - /* len is garbage if EOF but the loop below will quit anyway */ - while (len-- != 0 && get_byte(s) != EOF) ; - } - if ((flags & ORIG_NAME) != 0) { /* skip the original file name */ - while ((c = get_byte(s)) != 0 && c != EOF) ; - } - if ((flags & COMMENT) != 0) { /* skip the .gz file comment */ - while ((c = get_byte(s)) != 0 && c != EOF) ; - } - if ((flags & HEAD_CRC) != 0) { /* skip the header crc */ - for (len = 0; len < 2; len++) (void)get_byte(s); - } - s->z_err = s->z_eof ? Z_DATA_ERROR : Z_OK; -} - - /* =========================================================================== - * Cleanup then free the given gz_stream. Return a zlib error code. - Try freeing in the reverse order of allocations. - */ -local int destroy (s) - gz_stream *s; -{ - int err = Z_OK; - - if (!s) return Z_STREAM_ERROR; - - TRYFREE(s->msg); - - if (s->stream.state != NULL) { - if (s->mode == 'w') { -#ifdef NO_GZCOMPRESS - err = Z_STREAM_ERROR; -#else - err = deflateEnd(&(s->stream)); -#endif - } else if (s->mode == 'r') { - err = inflateEnd(&(s->stream)); - } - } - if (s->file != NULL && fclose(s->file)) { -#ifdef ESPIPE - if (errno != ESPIPE) /* fclose is broken for pipes in HP/UX */ -#endif - err = Z_ERRNO; - } - if (s->z_err < 0) err = s->z_err; - - TRYFREE(s->inbuf); - TRYFREE(s->outbuf); - TRYFREE(s->path); - TRYFREE(s); - return err; -} - -/* =========================================================================== - Reads the given number of uncompressed bytes from the compressed file. - gzread returns the number of bytes actually read (0 for end of file). -*/ -int ZEXPORT gzread (file, buf, len) - gzFile file; - voidp buf; - unsigned len; -{ - gz_stream *s = (gz_stream*)file; - Bytef *start = (Bytef*)buf; /* starting point for crc computation */ - Byte *next_out; /* == stream.next_out but not forced far (for MSDOS) */ - - if (s == NULL || s->mode != 'r') return Z_STREAM_ERROR; - - if (s->z_err == Z_DATA_ERROR || s->z_err == Z_ERRNO) return -1; - if (s->z_err == Z_STREAM_END) return 0; /* EOF */ - - next_out = (Byte*)buf; - s->stream.next_out = (Bytef*)buf; - s->stream.avail_out = len; - - if (s->stream.avail_out && s->back != EOF) { - *next_out++ = s->back; - s->stream.next_out++; - s->stream.avail_out--; - s->back = EOF; - s->out++; - start++; - if (s->last) { - s->z_err = Z_STREAM_END; - return 1; - } - } - - while (s->stream.avail_out != 0) { - - if (s->transparent) { - /* Copy first the lookahead bytes: */ - uInt n = s->stream.avail_in; - if (n > s->stream.avail_out) n = s->stream.avail_out; - if (n > 0) { - zmemcpy(s->stream.next_out, s->stream.next_in, n); - next_out += n; - s->stream.next_out = next_out; - s->stream.next_in += n; - s->stream.avail_out -= n; - s->stream.avail_in -= n; - } - if (s->stream.avail_out > 0) { - s->stream.avail_out -= - (uInt)fread(next_out, 1, s->stream.avail_out, s->file); - } - len -= s->stream.avail_out; - s->in += len; - s->out += len; - if (len == 0) s->z_eof = 1; - return (int)len; - } - if (s->stream.avail_in == 0 && !s->z_eof) { - - errno = 0; - s->stream.avail_in = (uInt)fread(s->inbuf, 1, Z_BUFSIZE, s->file); - if (s->stream.avail_in == 0) { - s->z_eof = 1; - if (ferror(s->file)) { - s->z_err = Z_ERRNO; - break; - } - } - s->stream.next_in = s->inbuf; - } - s->in += s->stream.avail_in; - s->out += s->stream.avail_out; - s->z_err = inflate(&(s->stream), Z_NO_FLUSH); - s->in -= s->stream.avail_in; - s->out -= s->stream.avail_out; - - if (s->z_err == Z_STREAM_END) { - /* Check CRC and original size */ - s->crc = crc32(s->crc, start, (uInt)(s->stream.next_out - start)); - start = s->stream.next_out; - - if (getLong(s) != s->crc) { - s->z_err = Z_DATA_ERROR; - } else { - (void)getLong(s); - /* The uncompressed length returned by above getlong() may be - * different from s->out in case of concatenated .gz files. - * Check for such files: - */ - check_header(s); - if (s->z_err == Z_OK) { - inflateReset(&(s->stream)); - s->crc = crc32(0L, Z_NULL, 0); - } - } - } - if (s->z_err != Z_OK || s->z_eof) break; - } - s->crc = crc32(s->crc, start, (uInt)(s->stream.next_out - start)); - - if (len == s->stream.avail_out && - (s->z_err == Z_DATA_ERROR || s->z_err == Z_ERRNO)) - return -1; - return (int)(len - s->stream.avail_out); -} - - -/* =========================================================================== - Reads one byte from the compressed file. gzgetc returns this byte - or -1 in case of end of file or error. -*/ -int ZEXPORT gzgetc(file) - gzFile file; -{ - unsigned char c; - - return gzread(file, &c, 1) == 1 ? c : -1; -} - - -/* =========================================================================== - Push one byte back onto the stream. -*/ -int ZEXPORT gzungetc(c, file) - int c; - gzFile file; -{ - gz_stream *s = (gz_stream*)file; - - if (s == NULL || s->mode != 'r' || c == EOF || s->back != EOF) return EOF; - s->back = c; - s->out--; - s->last = (s->z_err == Z_STREAM_END); - if (s->last) s->z_err = Z_OK; - s->z_eof = 0; - return c; -} - - -/* =========================================================================== - Reads bytes from the compressed file until len-1 characters are - read, or a newline character is read and transferred to buf, or an - end-of-file condition is encountered. The string is then terminated - with a null character. - gzgets returns buf, or Z_NULL in case of error. - - The current implementation is not optimized at all. -*/ -char * ZEXPORT gzgets(file, buf, len) - gzFile file; - char *buf; - int len; -{ - char *b = buf; - if (buf == Z_NULL || len <= 0) return Z_NULL; - - while (--len > 0 && gzread(file, buf, 1) == 1 && *buf++ != '\n') ; - *buf = '\0'; - return b == buf && len > 0 ? Z_NULL : b; -} - - -#ifndef NO_GZCOMPRESS -/* =========================================================================== - Writes the given number of uncompressed bytes into the compressed file. - gzwrite returns the number of bytes actually written (0 in case of error). -*/ -int ZEXPORT gzwrite (file, buf, len) - gzFile file; - voidpc buf; - unsigned len; -{ - gz_stream *s = (gz_stream*)file; - - if (s == NULL || s->mode != 'w') return Z_STREAM_ERROR; - - s->stream.next_in = (Bytef*)buf; - s->stream.avail_in = len; - - while (s->stream.avail_in != 0) { - - if (s->stream.avail_out == 0) { - - s->stream.next_out = s->outbuf; - if (fwrite(s->outbuf, 1, Z_BUFSIZE, s->file) != Z_BUFSIZE) { - s->z_err = Z_ERRNO; - break; - } - s->stream.avail_out = Z_BUFSIZE; - } - s->in += s->stream.avail_in; - s->out += s->stream.avail_out; - s->z_err = deflate(&(s->stream), Z_NO_FLUSH); - s->in -= s->stream.avail_in; - s->out -= s->stream.avail_out; - if (s->z_err != Z_OK) break; - } - s->crc = crc32(s->crc, (const Bytef *)buf, len); - - return (int)(len - s->stream.avail_in); -} - - -/* =========================================================================== - Converts, formats, and writes the args to the compressed file under - control of the format string, as in fprintf. gzprintf returns the number of - uncompressed bytes actually written (0 in case of error). -*/ -#ifdef STDC -#include - -int ZEXPORTVA gzprintf (gzFile file, const char *format, /* args */ ...) -{ - char buf[Z_PRINTF_BUFSIZE]; - va_list va; - int len; - - buf[sizeof(buf) - 1] = 0; - va_start(va, format); -#ifdef NO_vsnprintf -# ifdef HAS_vsprintf_void - (void)vsprintf(buf, format, va); - va_end(va); - for (len = 0; len < sizeof(buf); len++) - if (buf[len] == 0) break; -# else - len = vsprintf(buf, format, va); - va_end(va); -# endif -#else -# ifdef HAS_vsnprintf_void - (void)vsnprintf(buf, sizeof(buf), format, va); - va_end(va); - len = strlen(buf); -# else - len = vsnprintf(buf, sizeof(buf), format, va); - va_end(va); -# endif -#endif - if (len <= 0 || len >= (int)sizeof(buf) || buf[sizeof(buf) - 1] != 0) - return 0; - return gzwrite(file, buf, (unsigned)len); -} -#else /* not ANSI C */ - -int ZEXPORTVA gzprintf (file, format, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, - a11, a12, a13, a14, a15, a16, a17, a18, a19, a20) - gzFile file; - const char *format; - int a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, - a11, a12, a13, a14, a15, a16, a17, a18, a19, a20; -{ - char buf[Z_PRINTF_BUFSIZE]; - int len; - - buf[sizeof(buf) - 1] = 0; -#ifdef NO_snprintf -# ifdef HAS_sprintf_void - sprintf(buf, format, a1, a2, a3, a4, a5, a6, a7, a8, - a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20); - for (len = 0; len < sizeof(buf); len++) - if (buf[len] == 0) break; -# else - len = sprintf(buf, format, a1, a2, a3, a4, a5, a6, a7, a8, - a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20); -# endif -#else -# ifdef HAS_snprintf_void - snprintf(buf, sizeof(buf), format, a1, a2, a3, a4, a5, a6, a7, a8, - a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20); - len = strlen(buf); -# else - len = snprintf(buf, sizeof(buf), format, a1, a2, a3, a4, a5, a6, a7, a8, - a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20); -# endif -#endif - if (len <= 0 || len >= sizeof(buf) || buf[sizeof(buf) - 1] != 0) - return 0; - return gzwrite(file, buf, len); -} -#endif - -/* =========================================================================== - Writes c, converted to an unsigned char, into the compressed file. - gzputc returns the value that was written, or -1 in case of error. -*/ -int ZEXPORT gzputc(file, c) - gzFile file; - int c; -{ - unsigned char cc = (unsigned char) c; /* required for big endian systems */ - - return gzwrite(file, &cc, 1) == 1 ? (int)cc : -1; -} - - -/* =========================================================================== - Writes the given null-terminated string to the compressed file, excluding - the terminating null character. - gzputs returns the number of characters written, or -1 in case of error. -*/ -int ZEXPORT gzputs(file, s) - gzFile file; - const char *s; -{ - return gzwrite(file, (char*)s, (unsigned)strlen(s)); -} - - -/* =========================================================================== - Flushes all pending output into the compressed file. The parameter - flush is as in the deflate() function. -*/ -local int do_flush (file, flush) - gzFile file; - int flush; -{ - uInt len; - int done = 0; - gz_stream *s = (gz_stream*)file; - - if (s == NULL || s->mode != 'w') return Z_STREAM_ERROR; - - s->stream.avail_in = 0; /* should be zero already anyway */ - - for (;;) { - len = Z_BUFSIZE - s->stream.avail_out; - - if (len != 0) { - if ((uInt)fwrite(s->outbuf, 1, len, s->file) != len) { - s->z_err = Z_ERRNO; - return Z_ERRNO; - } - s->stream.next_out = s->outbuf; - s->stream.avail_out = Z_BUFSIZE; - } - if (done) break; - s->out += s->stream.avail_out; - s->z_err = deflate(&(s->stream), flush); - s->out -= s->stream.avail_out; - - /* Ignore the second of two consecutive flushes: */ - if (len == 0 && s->z_err == Z_BUF_ERROR) s->z_err = Z_OK; - - /* deflate has finished flushing only when it hasn't used up - * all the available space in the output buffer: - */ - done = (s->stream.avail_out != 0 || s->z_err == Z_STREAM_END); - - if (s->z_err != Z_OK && s->z_err != Z_STREAM_END) break; - } - return s->z_err == Z_STREAM_END ? Z_OK : s->z_err; -} - -int ZEXPORT gzflush (file, flush) - gzFile file; - int flush; -{ - gz_stream *s = (gz_stream*)file; - int err = do_flush (file, flush); - - if (err) return err; - fflush(s->file); - return s->z_err == Z_STREAM_END ? Z_OK : s->z_err; -} -#endif /* NO_GZCOMPRESS */ - -/* =========================================================================== - Sets the starting position for the next gzread or gzwrite on the given - compressed file. The offset represents a number of bytes in the - gzseek returns the resulting offset location as measured in bytes from - the beginning of the uncompressed stream, or -1 in case of error. - SEEK_END is not implemented, returns error. - In this version of the library, gzseek can be extremely slow. -*/ -z_off_t ZEXPORT gzseek (file, offset, whence) - gzFile file; - z_off_t offset; - int whence; -{ - gz_stream *s = (gz_stream*)file; - - if (s == NULL || whence == SEEK_END || - s->z_err == Z_ERRNO || s->z_err == Z_DATA_ERROR) { - return -1L; - } - - if (s->mode == 'w') { -#ifdef NO_GZCOMPRESS - return -1L; -#else - if (whence == SEEK_SET) { - offset -= s->in; - } - if (offset < 0) return -1L; - - /* At this point, offset is the number of zero bytes to write. */ - if (s->inbuf == Z_NULL) { - s->inbuf = (Byte*)ALLOC(Z_BUFSIZE); /* for seeking */ - if (s->inbuf == Z_NULL) return -1L; - zmemzero(s->inbuf, Z_BUFSIZE); - } - while (offset > 0) { - uInt size = Z_BUFSIZE; - if (offset < Z_BUFSIZE) size = (uInt)offset; - - size = gzwrite(file, s->inbuf, size); - if (size == 0) return -1L; - - offset -= size; - } - return s->in; -#endif - } - /* Rest of function is for reading only */ - - /* compute absolute position */ - if (whence == SEEK_CUR) { - offset += s->out; - } - if (offset < 0) return -1L; - - if (s->transparent) { - /* map to fseek */ - s->back = EOF; - s->stream.avail_in = 0; - s->stream.next_in = s->inbuf; - if (fseek(s->file, offset, SEEK_SET) < 0) return -1L; - - s->in = s->out = offset; - return offset; - } - - /* For a negative seek, rewind and use positive seek */ - if (offset >= s->out) { - offset -= s->out; - } else if (gzrewind(file) < 0) { - return -1L; - } - /* offset is now the number of bytes to skip. */ - - if (offset != 0 && s->outbuf == Z_NULL) { - s->outbuf = (Byte*)ALLOC(Z_BUFSIZE); - if (s->outbuf == Z_NULL) return -1L; - } - if (offset && s->back != EOF) { - s->back = EOF; - s->out++; - offset--; - if (s->last) s->z_err = Z_STREAM_END; - } - while (offset > 0) { - int size = Z_BUFSIZE; - if (offset < Z_BUFSIZE) size = (int)offset; - - size = gzread(file, s->outbuf, (uInt)size); - if (size <= 0) return -1L; - offset -= size; - } - return s->out; -} - -/* =========================================================================== - Rewinds input file. -*/ -int ZEXPORT gzrewind (file) - gzFile file; -{ - gz_stream *s = (gz_stream*)file; - - if (s == NULL || s->mode != 'r') return -1; - - s->z_err = Z_OK; - s->z_eof = 0; - s->back = EOF; - s->stream.avail_in = 0; - s->stream.next_in = s->inbuf; - s->crc = crc32(0L, Z_NULL, 0); - if (!s->transparent) (void)inflateReset(&s->stream); - s->in = 0; - s->out = 0; - return fseek(s->file, s->start, SEEK_SET); -} - -/* =========================================================================== - Returns the starting position for the next gzread or gzwrite on the - given compressed file. This position represents a number of bytes in the - uncompressed data stream. -*/ -z_off_t ZEXPORT gztell (file) - gzFile file; -{ - return gzseek(file, 0L, SEEK_CUR); -} - -/* =========================================================================== - Returns 1 when EOF has previously been detected reading the given - input stream, otherwise zero. -*/ -int ZEXPORT gzeof (file) - gzFile file; -{ - gz_stream *s = (gz_stream*)file; - - /* With concatenated compressed files that can have embedded - * crc trailers, z_eof is no longer the only/best indicator of EOF - * on a gz_stream. Handle end-of-stream error explicitly here. - */ - if (s == NULL || s->mode != 'r') return 0; - if (s->z_eof) return 1; - return s->z_err == Z_STREAM_END; -} - -/* =========================================================================== - Returns 1 if reading and doing so transparently, otherwise zero. -*/ -int ZEXPORT gzdirect (file) - gzFile file; -{ - gz_stream *s = (gz_stream*)file; - - if (s == NULL || s->mode != 'r') return 0; - return s->transparent; -} - -/* =========================================================================== - Outputs a long in LSB order to the given file -*/ -local void putLong (file, x) - FILE *file; - uLong x; -{ - int n; - for (n = 0; n < 4; n++) { - fputc((int)(x & 0xff), file); - x >>= 8; - } -} - -/* =========================================================================== - Reads a long in LSB order from the given gz_stream. Sets z_err in case - of error. -*/ -local uLong getLong (s) - gz_stream *s; -{ - uLong x = (uLong)get_byte(s); - int c; - - x += ((uLong)get_byte(s))<<8; - x += ((uLong)get_byte(s))<<16; - c = get_byte(s); - if (c == EOF) s->z_err = Z_DATA_ERROR; - x += ((uLong)c)<<24; - return x; -} - -/* =========================================================================== - Flushes all pending output if necessary, closes the compressed file - and deallocates all the (de)compression state. -*/ -int ZEXPORT gzclose (file) - gzFile file; -{ - gz_stream *s = (gz_stream*)file; - - if (s == NULL) return Z_STREAM_ERROR; - - if (s->mode == 'w') { -#ifdef NO_GZCOMPRESS - return Z_STREAM_ERROR; -#else - if (do_flush (file, Z_FINISH) != Z_OK) - return destroy((gz_stream*)file); - - putLong (s->file, s->crc); - putLong (s->file, (uLong)(s->in & 0xffffffff)); -#endif - } - return destroy((gz_stream*)file); -} - -#ifdef STDC -# define zstrerror(errnum) strerror(errnum) -#else -# define zstrerror(errnum) "" -#endif - -/* =========================================================================== - Returns the error message for the last error which occurred on the - given compressed file. errnum is set to zlib error number. If an - error occurred in the file system and not in the compression library, - errnum is set to Z_ERRNO and the application may consult errno - to get the exact error code. -*/ -const char * ZEXPORT gzerror (file, errnum) - gzFile file; - int *errnum; -{ - char *m; - gz_stream *s = (gz_stream*)file; - - if (s == NULL) { - *errnum = Z_STREAM_ERROR; - return (const char*)ERR_MSG(Z_STREAM_ERROR); - } - *errnum = s->z_err; - if (*errnum == Z_OK) return (const char*)""; - - m = (char*)(*errnum == Z_ERRNO ? zstrerror(errno) : s->stream.msg); - - if (m == NULL || *m == '\0') m = (char*)ERR_MSG(s->z_err); - - TRYFREE(s->msg); - s->msg = (char*)ALLOC(strlen(s->path) + strlen(m) + 3); - if (s->msg == Z_NULL) return (const char*)ERR_MSG(Z_MEM_ERROR); - strcpy(s->msg, s->path); - strcat(s->msg, ": "); - strcat(s->msg, m); - return (const char*)s->msg; -} - -/* =========================================================================== - Clear the error and end-of-file flags, and do the same for the real file. -*/ -void ZEXPORT gzclearerr (file) - gzFile file; -{ - gz_stream *s = (gz_stream*)file; - - if (s == NULL) return; - if (s->z_err != Z_STREAM_END) s->z_err = Z_OK; - s->z_eof = 0; - clearerr(s->file); -} +/* gzio.c -- IO on .gz files + * Copyright (C) 1995-2005 Jean-loup Gailly. + * For conditions of distribution and use, see copyright notice in zlib.h + * + * Compile this file with -DNO_GZCOMPRESS to avoid the compression code. + */ + +/* @(#) $Id: //poco/1.2/Foundation/src/gzio.c#1 $ */ + +#include + +#include "zutil.h" + +#ifdef NO_DEFLATE /* for compatibility with old definition */ +# define NO_GZCOMPRESS +#endif + +#ifndef NO_DUMMY_DECL +struct internal_state {int dummy;}; /* for buggy compilers */ +#endif + +#ifndef Z_BUFSIZE +# ifdef MAXSEG_64K +# define Z_BUFSIZE 4096 /* minimize memory usage for 16-bit DOS */ +# else +# define Z_BUFSIZE 16384 +# endif +#endif +#ifndef Z_PRINTF_BUFSIZE +# define Z_PRINTF_BUFSIZE 4096 +#endif + +#ifdef __MVS__ +# pragma map (fdopen , "\174\174FDOPEN") + FILE *fdopen(int, const char *); +#endif + +#ifndef STDC +extern voidp malloc OF((uInt size)); +extern void free OF((voidpf ptr)); +#endif + +#define ALLOC(size) malloc(size) +#define TRYFREE(p) {if (p) free(p);} + +static int const gz_magic[2] = {0x1f, 0x8b}; /* gzip magic header */ + +/* gzip flag byte */ +#define ASCII_FLAG 0x01 /* bit 0 set: file probably ascii text */ +#define HEAD_CRC 0x02 /* bit 1 set: header CRC present */ +#define EXTRA_FIELD 0x04 /* bit 2 set: extra field present */ +#define ORIG_NAME 0x08 /* bit 3 set: original file name present */ +#define COMMENT 0x10 /* bit 4 set: file comment present */ +#define RESERVED 0xE0 /* bits 5..7: reserved */ + +typedef struct gz_stream { + z_stream stream; + int z_err; /* error code for last stream operation */ + int z_eof; /* set if end of input file */ + FILE *file; /* .gz file */ + Byte *inbuf; /* input buffer */ + Byte *outbuf; /* output buffer */ + uLong crc; /* crc32 of uncompressed data */ + char *msg; /* error message */ + char *path; /* path name for debugging only */ + int transparent; /* 1 if input file is not a .gz file */ + char mode; /* 'w' or 'r' */ + z_off_t start; /* start of compressed data in file (header skipped) */ + z_off_t in; /* bytes into deflate or inflate */ + z_off_t out; /* bytes out of deflate or inflate */ + int back; /* one character push-back */ + int last; /* true if push-back is last character */ +} gz_stream; + + +local gzFile gz_open OF((const char *path, const char *mode, int fd)); +local int do_flush OF((gzFile file, int flush)); +local int get_byte OF((gz_stream *s)); +local void check_header OF((gz_stream *s)); +local int destroy OF((gz_stream *s)); +local void putLong OF((FILE *file, uLong x)); +local uLong getLong OF((gz_stream *s)); + +/* =========================================================================== + Opens a gzip (.gz) file for reading or writing. The mode parameter + is as in fopen ("rb" or "wb"). The file is given either by file descriptor + or path name (if fd == -1). + gz_open returns NULL if the file could not be opened or if there was + insufficient memory to allocate the (de)compression state; errno + can be checked to distinguish the two cases (if errno is zero, the + zlib error is Z_MEM_ERROR). +*/ +local gzFile gz_open (path, mode, fd) + const char *path; + const char *mode; + int fd; +{ + int err; + int level = Z_DEFAULT_COMPRESSION; /* compression level */ + int strategy = Z_DEFAULT_STRATEGY; /* compression strategy */ + char *p = (char*)mode; + gz_stream *s; + char fmode[80]; /* copy of mode, without the compression level */ + char *m = fmode; + + if (!path || !mode) return Z_NULL; + + s = (gz_stream *)ALLOC(sizeof(gz_stream)); + if (!s) return Z_NULL; + + s->stream.zalloc = (alloc_func)0; + s->stream.zfree = (free_func)0; + s->stream.opaque = (voidpf)0; + s->stream.next_in = s->inbuf = Z_NULL; + s->stream.next_out = s->outbuf = Z_NULL; + s->stream.avail_in = s->stream.avail_out = 0; + s->file = NULL; + s->z_err = Z_OK; + s->z_eof = 0; + s->in = 0; + s->out = 0; + s->back = EOF; + s->crc = crc32(0L, Z_NULL, 0); + s->msg = NULL; + s->transparent = 0; + + s->path = (char*)ALLOC(strlen(path)+1); + if (s->path == NULL) { + return destroy(s), (gzFile)Z_NULL; + } + strcpy(s->path, path); /* do this early for debugging */ + + s->mode = '\0'; + do { + if (*p == 'r') s->mode = 'r'; + if (*p == 'w' || *p == 'a') s->mode = 'w'; + if (*p >= '0' && *p <= '9') { + level = *p - '0'; + } else if (*p == 'f') { + strategy = Z_FILTERED; + } else if (*p == 'h') { + strategy = Z_HUFFMAN_ONLY; + } else if (*p == 'R') { + strategy = Z_RLE; + } else { + *m++ = *p; /* copy the mode */ + } + } while (*p++ && m != fmode + sizeof(fmode)); + if (s->mode == '\0') return destroy(s), (gzFile)Z_NULL; + + if (s->mode == 'w') { +#ifdef NO_GZCOMPRESS + err = Z_STREAM_ERROR; +#else + err = deflateInit2(&(s->stream), level, + Z_DEFLATED, -MAX_WBITS, DEF_MEM_LEVEL, strategy); + /* windowBits is passed < 0 to suppress zlib header */ + + s->stream.next_out = s->outbuf = (Byte*)ALLOC(Z_BUFSIZE); +#endif + if (err != Z_OK || s->outbuf == Z_NULL) { + return destroy(s), (gzFile)Z_NULL; + } + } else { + s->stream.next_in = s->inbuf = (Byte*)ALLOC(Z_BUFSIZE); + + err = inflateInit2(&(s->stream), -MAX_WBITS); + /* windowBits is passed < 0 to tell that there is no zlib header. + * Note that in this case inflate *requires* an extra "dummy" byte + * after the compressed stream in order to complete decompression and + * return Z_STREAM_END. Here the gzip CRC32 ensures that 4 bytes are + * present after the compressed stream. + */ + if (err != Z_OK || s->inbuf == Z_NULL) { + return destroy(s), (gzFile)Z_NULL; + } + } + s->stream.avail_out = Z_BUFSIZE; + + errno = 0; + s->file = fd < 0 ? F_OPEN(path, fmode) : (FILE*)fdopen(fd, fmode); + + if (s->file == NULL) { + return destroy(s), (gzFile)Z_NULL; + } + if (s->mode == 'w') { + /* Write a very simple .gz header: + */ + fprintf(s->file, "%c%c%c%c%c%c%c%c%c%c", gz_magic[0], gz_magic[1], + Z_DEFLATED, 0 /*flags*/, 0,0,0,0 /*time*/, 0 /*xflags*/, OS_CODE); + s->start = 10L; + /* We use 10L instead of ftell(s->file) to because ftell causes an + * fflush on some systems. This version of the library doesn't use + * start anyway in write mode, so this initialization is not + * necessary. + */ + } else { + check_header(s); /* skip the .gz header */ + s->start = ftell(s->file) - s->stream.avail_in; + } + + return (gzFile)s; +} + +/* =========================================================================== + Opens a gzip (.gz) file for reading or writing. +*/ +gzFile ZEXPORT gzopen (path, mode) + const char *path; + const char *mode; +{ + return gz_open (path, mode, -1); +} + +/* =========================================================================== + Associate a gzFile with the file descriptor fd. fd is not dup'ed here + to mimic the behavio(u)r of fdopen. +*/ +gzFile ZEXPORT gzdopen (fd, mode) + int fd; + const char *mode; +{ + char name[46]; /* allow for up to 128-bit integers */ + + if (fd < 0) return (gzFile)Z_NULL; + sprintf(name, "", fd); /* for debugging */ + + return gz_open (name, mode, fd); +} + +/* =========================================================================== + * Update the compression level and strategy + */ +int ZEXPORT gzsetparams (file, level, strategy) + gzFile file; + int level; + int strategy; +{ + gz_stream *s = (gz_stream*)file; + + if (s == NULL || s->mode != 'w') return Z_STREAM_ERROR; + + /* Make room to allow flushing */ + if (s->stream.avail_out == 0) { + + s->stream.next_out = s->outbuf; + if (fwrite(s->outbuf, 1, Z_BUFSIZE, s->file) != Z_BUFSIZE) { + s->z_err = Z_ERRNO; + } + s->stream.avail_out = Z_BUFSIZE; + } + + return deflateParams (&(s->stream), level, strategy); +} + +/* =========================================================================== + Read a byte from a gz_stream; update next_in and avail_in. Return EOF + for end of file. + IN assertion: the stream s has been sucessfully opened for reading. +*/ +local int get_byte(s) + gz_stream *s; +{ + if (s->z_eof) return EOF; + if (s->stream.avail_in == 0) { + errno = 0; + s->stream.avail_in = (uInt)fread(s->inbuf, 1, Z_BUFSIZE, s->file); + if (s->stream.avail_in == 0) { + s->z_eof = 1; + if (ferror(s->file)) s->z_err = Z_ERRNO; + return EOF; + } + s->stream.next_in = s->inbuf; + } + s->stream.avail_in--; + return *(s->stream.next_in)++; +} + +/* =========================================================================== + Check the gzip header of a gz_stream opened for reading. Set the stream + mode to transparent if the gzip magic header is not present; set s->err + to Z_DATA_ERROR if the magic header is present but the rest of the header + is incorrect. + IN assertion: the stream s has already been created sucessfully; + s->stream.avail_in is zero for the first time, but may be non-zero + for concatenated .gz files. +*/ +local void check_header(s) + gz_stream *s; +{ + int method; /* method byte */ + int flags; /* flags byte */ + uInt len; + int c; + + /* Assure two bytes in the buffer so we can peek ahead -- handle case + where first byte of header is at the end of the buffer after the last + gzip segment */ + len = s->stream.avail_in; + if (len < 2) { + if (len) s->inbuf[0] = s->stream.next_in[0]; + errno = 0; + len = (uInt)fread(s->inbuf + len, 1, Z_BUFSIZE >> len, s->file); + if (len == 0 && ferror(s->file)) s->z_err = Z_ERRNO; + s->stream.avail_in += len; + s->stream.next_in = s->inbuf; + if (s->stream.avail_in < 2) { + s->transparent = s->stream.avail_in; + return; + } + } + + /* Peek ahead to check the gzip magic header */ + if (s->stream.next_in[0] != gz_magic[0] || + s->stream.next_in[1] != gz_magic[1]) { + s->transparent = 1; + return; + } + s->stream.avail_in -= 2; + s->stream.next_in += 2; + + /* Check the rest of the gzip header */ + method = get_byte(s); + flags = get_byte(s); + if (method != Z_DEFLATED || (flags & RESERVED) != 0) { + s->z_err = Z_DATA_ERROR; + return; + } + + /* Discard time, xflags and OS code: */ + for (len = 0; len < 6; len++) (void)get_byte(s); + + if ((flags & EXTRA_FIELD) != 0) { /* skip the extra field */ + len = (uInt)get_byte(s); + len += ((uInt)get_byte(s))<<8; + /* len is garbage if EOF but the loop below will quit anyway */ + while (len-- != 0 && get_byte(s) != EOF) ; + } + if ((flags & ORIG_NAME) != 0) { /* skip the original file name */ + while ((c = get_byte(s)) != 0 && c != EOF) ; + } + if ((flags & COMMENT) != 0) { /* skip the .gz file comment */ + while ((c = get_byte(s)) != 0 && c != EOF) ; + } + if ((flags & HEAD_CRC) != 0) { /* skip the header crc */ + for (len = 0; len < 2; len++) (void)get_byte(s); + } + s->z_err = s->z_eof ? Z_DATA_ERROR : Z_OK; +} + + /* =========================================================================== + * Cleanup then free the given gz_stream. Return a zlib error code. + Try freeing in the reverse order of allocations. + */ +local int destroy (s) + gz_stream *s; +{ + int err = Z_OK; + + if (!s) return Z_STREAM_ERROR; + + TRYFREE(s->msg); + + if (s->stream.state != NULL) { + if (s->mode == 'w') { +#ifdef NO_GZCOMPRESS + err = Z_STREAM_ERROR; +#else + err = deflateEnd(&(s->stream)); +#endif + } else if (s->mode == 'r') { + err = inflateEnd(&(s->stream)); + } + } + if (s->file != NULL && fclose(s->file)) { +#ifdef ESPIPE + if (errno != ESPIPE) /* fclose is broken for pipes in HP/UX */ +#endif + err = Z_ERRNO; + } + if (s->z_err < 0) err = s->z_err; + + TRYFREE(s->inbuf); + TRYFREE(s->outbuf); + TRYFREE(s->path); + TRYFREE(s); + return err; +} + +/* =========================================================================== + Reads the given number of uncompressed bytes from the compressed file. + gzread returns the number of bytes actually read (0 for end of file). +*/ +int ZEXPORT gzread (file, buf, len) + gzFile file; + voidp buf; + unsigned len; +{ + gz_stream *s = (gz_stream*)file; + Bytef *start = (Bytef*)buf; /* starting point for crc computation */ + Byte *next_out; /* == stream.next_out but not forced far (for MSDOS) */ + + if (s == NULL || s->mode != 'r') return Z_STREAM_ERROR; + + if (s->z_err == Z_DATA_ERROR || s->z_err == Z_ERRNO) return -1; + if (s->z_err == Z_STREAM_END) return 0; /* EOF */ + + next_out = (Byte*)buf; + s->stream.next_out = (Bytef*)buf; + s->stream.avail_out = len; + + if (s->stream.avail_out && s->back != EOF) { + *next_out++ = s->back; + s->stream.next_out++; + s->stream.avail_out--; + s->back = EOF; + s->out++; + start++; + if (s->last) { + s->z_err = Z_STREAM_END; + return 1; + } + } + + while (s->stream.avail_out != 0) { + + if (s->transparent) { + /* Copy first the lookahead bytes: */ + uInt n = s->stream.avail_in; + if (n > s->stream.avail_out) n = s->stream.avail_out; + if (n > 0) { + zmemcpy(s->stream.next_out, s->stream.next_in, n); + next_out += n; + s->stream.next_out = next_out; + s->stream.next_in += n; + s->stream.avail_out -= n; + s->stream.avail_in -= n; + } + if (s->stream.avail_out > 0) { + s->stream.avail_out -= + (uInt)fread(next_out, 1, s->stream.avail_out, s->file); + } + len -= s->stream.avail_out; + s->in += len; + s->out += len; + if (len == 0) s->z_eof = 1; + return (int)len; + } + if (s->stream.avail_in == 0 && !s->z_eof) { + + errno = 0; + s->stream.avail_in = (uInt)fread(s->inbuf, 1, Z_BUFSIZE, s->file); + if (s->stream.avail_in == 0) { + s->z_eof = 1; + if (ferror(s->file)) { + s->z_err = Z_ERRNO; + break; + } + } + s->stream.next_in = s->inbuf; + } + s->in += s->stream.avail_in; + s->out += s->stream.avail_out; + s->z_err = inflate(&(s->stream), Z_NO_FLUSH); + s->in -= s->stream.avail_in; + s->out -= s->stream.avail_out; + + if (s->z_err == Z_STREAM_END) { + /* Check CRC and original size */ + s->crc = crc32(s->crc, start, (uInt)(s->stream.next_out - start)); + start = s->stream.next_out; + + if (getLong(s) != s->crc) { + s->z_err = Z_DATA_ERROR; + } else { + (void)getLong(s); + /* The uncompressed length returned by above getlong() may be + * different from s->out in case of concatenated .gz files. + * Check for such files: + */ + check_header(s); + if (s->z_err == Z_OK) { + inflateReset(&(s->stream)); + s->crc = crc32(0L, Z_NULL, 0); + } + } + } + if (s->z_err != Z_OK || s->z_eof) break; + } + s->crc = crc32(s->crc, start, (uInt)(s->stream.next_out - start)); + + if (len == s->stream.avail_out && + (s->z_err == Z_DATA_ERROR || s->z_err == Z_ERRNO)) + return -1; + return (int)(len - s->stream.avail_out); +} + + +/* =========================================================================== + Reads one byte from the compressed file. gzgetc returns this byte + or -1 in case of end of file or error. +*/ +int ZEXPORT gzgetc(file) + gzFile file; +{ + unsigned char c; + + return gzread(file, &c, 1) == 1 ? c : -1; +} + + +/* =========================================================================== + Push one byte back onto the stream. +*/ +int ZEXPORT gzungetc(c, file) + int c; + gzFile file; +{ + gz_stream *s = (gz_stream*)file; + + if (s == NULL || s->mode != 'r' || c == EOF || s->back != EOF) return EOF; + s->back = c; + s->out--; + s->last = (s->z_err == Z_STREAM_END); + if (s->last) s->z_err = Z_OK; + s->z_eof = 0; + return c; +} + + +/* =========================================================================== + Reads bytes from the compressed file until len-1 characters are + read, or a newline character is read and transferred to buf, or an + end-of-file condition is encountered. The string is then terminated + with a null character. + gzgets returns buf, or Z_NULL in case of error. + + The current implementation is not optimized at all. +*/ +char * ZEXPORT gzgets(file, buf, len) + gzFile file; + char *buf; + int len; +{ + char *b = buf; + if (buf == Z_NULL || len <= 0) return Z_NULL; + + while (--len > 0 && gzread(file, buf, 1) == 1 && *buf++ != '\n') ; + *buf = '\0'; + return b == buf && len > 0 ? Z_NULL : b; +} + + +#ifndef NO_GZCOMPRESS +/* =========================================================================== + Writes the given number of uncompressed bytes into the compressed file. + gzwrite returns the number of bytes actually written (0 in case of error). +*/ +int ZEXPORT gzwrite (file, buf, len) + gzFile file; + voidpc buf; + unsigned len; +{ + gz_stream *s = (gz_stream*)file; + + if (s == NULL || s->mode != 'w') return Z_STREAM_ERROR; + + s->stream.next_in = (Bytef*)buf; + s->stream.avail_in = len; + + while (s->stream.avail_in != 0) { + + if (s->stream.avail_out == 0) { + + s->stream.next_out = s->outbuf; + if (fwrite(s->outbuf, 1, Z_BUFSIZE, s->file) != Z_BUFSIZE) { + s->z_err = Z_ERRNO; + break; + } + s->stream.avail_out = Z_BUFSIZE; + } + s->in += s->stream.avail_in; + s->out += s->stream.avail_out; + s->z_err = deflate(&(s->stream), Z_NO_FLUSH); + s->in -= s->stream.avail_in; + s->out -= s->stream.avail_out; + if (s->z_err != Z_OK) break; + } + s->crc = crc32(s->crc, (const Bytef *)buf, len); + + return (int)(len - s->stream.avail_in); +} + + +/* =========================================================================== + Converts, formats, and writes the args to the compressed file under + control of the format string, as in fprintf. gzprintf returns the number of + uncompressed bytes actually written (0 in case of error). +*/ +#ifdef STDC +#include + +int ZEXPORTVA gzprintf (gzFile file, const char *format, /* args */ ...) +{ + char buf[Z_PRINTF_BUFSIZE]; + va_list va; + int len; + + buf[sizeof(buf) - 1] = 0; + va_start(va, format); +#ifdef NO_vsnprintf +# ifdef HAS_vsprintf_void + (void)vsprintf(buf, format, va); + va_end(va); + for (len = 0; len < sizeof(buf); len++) + if (buf[len] == 0) break; +# else + len = vsprintf(buf, format, va); + va_end(va); +# endif +#else +# ifdef HAS_vsnprintf_void + (void)vsnprintf(buf, sizeof(buf), format, va); + va_end(va); + len = strlen(buf); +# else + len = vsnprintf(buf, sizeof(buf), format, va); + va_end(va); +# endif +#endif + if (len <= 0 || len >= (int)sizeof(buf) || buf[sizeof(buf) - 1] != 0) + return 0; + return gzwrite(file, buf, (unsigned)len); +} +#else /* not ANSI C */ + +int ZEXPORTVA gzprintf (file, format, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, + a11, a12, a13, a14, a15, a16, a17, a18, a19, a20) + gzFile file; + const char *format; + int a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, + a11, a12, a13, a14, a15, a16, a17, a18, a19, a20; +{ + char buf[Z_PRINTF_BUFSIZE]; + int len; + + buf[sizeof(buf) - 1] = 0; +#ifdef NO_snprintf +# ifdef HAS_sprintf_void + sprintf(buf, format, a1, a2, a3, a4, a5, a6, a7, a8, + a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20); + for (len = 0; len < sizeof(buf); len++) + if (buf[len] == 0) break; +# else + len = sprintf(buf, format, a1, a2, a3, a4, a5, a6, a7, a8, + a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20); +# endif +#else +# ifdef HAS_snprintf_void + snprintf(buf, sizeof(buf), format, a1, a2, a3, a4, a5, a6, a7, a8, + a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20); + len = strlen(buf); +# else + len = snprintf(buf, sizeof(buf), format, a1, a2, a3, a4, a5, a6, a7, a8, + a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20); +# endif +#endif + if (len <= 0 || len >= sizeof(buf) || buf[sizeof(buf) - 1] != 0) + return 0; + return gzwrite(file, buf, len); +} +#endif + +/* =========================================================================== + Writes c, converted to an unsigned char, into the compressed file. + gzputc returns the value that was written, or -1 in case of error. +*/ +int ZEXPORT gzputc(file, c) + gzFile file; + int c; +{ + unsigned char cc = (unsigned char) c; /* required for big endian systems */ + + return gzwrite(file, &cc, 1) == 1 ? (int)cc : -1; +} + + +/* =========================================================================== + Writes the given null-terminated string to the compressed file, excluding + the terminating null character. + gzputs returns the number of characters written, or -1 in case of error. +*/ +int ZEXPORT gzputs(file, s) + gzFile file; + const char *s; +{ + return gzwrite(file, (char*)s, (unsigned)strlen(s)); +} + + +/* =========================================================================== + Flushes all pending output into the compressed file. The parameter + flush is as in the deflate() function. +*/ +local int do_flush (file, flush) + gzFile file; + int flush; +{ + uInt len; + int done = 0; + gz_stream *s = (gz_stream*)file; + + if (s == NULL || s->mode != 'w') return Z_STREAM_ERROR; + + s->stream.avail_in = 0; /* should be zero already anyway */ + + for (;;) { + len = Z_BUFSIZE - s->stream.avail_out; + + if (len != 0) { + if ((uInt)fwrite(s->outbuf, 1, len, s->file) != len) { + s->z_err = Z_ERRNO; + return Z_ERRNO; + } + s->stream.next_out = s->outbuf; + s->stream.avail_out = Z_BUFSIZE; + } + if (done) break; + s->out += s->stream.avail_out; + s->z_err = deflate(&(s->stream), flush); + s->out -= s->stream.avail_out; + + /* Ignore the second of two consecutive flushes: */ + if (len == 0 && s->z_err == Z_BUF_ERROR) s->z_err = Z_OK; + + /* deflate has finished flushing only when it hasn't used up + * all the available space in the output buffer: + */ + done = (s->stream.avail_out != 0 || s->z_err == Z_STREAM_END); + + if (s->z_err != Z_OK && s->z_err != Z_STREAM_END) break; + } + return s->z_err == Z_STREAM_END ? Z_OK : s->z_err; +} + +int ZEXPORT gzflush (file, flush) + gzFile file; + int flush; +{ + gz_stream *s = (gz_stream*)file; + int err = do_flush (file, flush); + + if (err) return err; + fflush(s->file); + return s->z_err == Z_STREAM_END ? Z_OK : s->z_err; +} +#endif /* NO_GZCOMPRESS */ + +/* =========================================================================== + Sets the starting position for the next gzread or gzwrite on the given + compressed file. The offset represents a number of bytes in the + gzseek returns the resulting offset location as measured in bytes from + the beginning of the uncompressed stream, or -1 in case of error. + SEEK_END is not implemented, returns error. + In this version of the library, gzseek can be extremely slow. +*/ +z_off_t ZEXPORT gzseek (file, offset, whence) + gzFile file; + z_off_t offset; + int whence; +{ + gz_stream *s = (gz_stream*)file; + + if (s == NULL || whence == SEEK_END || + s->z_err == Z_ERRNO || s->z_err == Z_DATA_ERROR) { + return -1L; + } + + if (s->mode == 'w') { +#ifdef NO_GZCOMPRESS + return -1L; +#else + if (whence == SEEK_SET) { + offset -= s->in; + } + if (offset < 0) return -1L; + + /* At this point, offset is the number of zero bytes to write. */ + if (s->inbuf == Z_NULL) { + s->inbuf = (Byte*)ALLOC(Z_BUFSIZE); /* for seeking */ + if (s->inbuf == Z_NULL) return -1L; + zmemzero(s->inbuf, Z_BUFSIZE); + } + while (offset > 0) { + uInt size = Z_BUFSIZE; + if (offset < Z_BUFSIZE) size = (uInt)offset; + + size = gzwrite(file, s->inbuf, size); + if (size == 0) return -1L; + + offset -= size; + } + return s->in; +#endif + } + /* Rest of function is for reading only */ + + /* compute absolute position */ + if (whence == SEEK_CUR) { + offset += s->out; + } + if (offset < 0) return -1L; + + if (s->transparent) { + /* map to fseek */ + s->back = EOF; + s->stream.avail_in = 0; + s->stream.next_in = s->inbuf; + if (fseek(s->file, offset, SEEK_SET) < 0) return -1L; + + s->in = s->out = offset; + return offset; + } + + /* For a negative seek, rewind and use positive seek */ + if (offset >= s->out) { + offset -= s->out; + } else if (gzrewind(file) < 0) { + return -1L; + } + /* offset is now the number of bytes to skip. */ + + if (offset != 0 && s->outbuf == Z_NULL) { + s->outbuf = (Byte*)ALLOC(Z_BUFSIZE); + if (s->outbuf == Z_NULL) return -1L; + } + if (offset && s->back != EOF) { + s->back = EOF; + s->out++; + offset--; + if (s->last) s->z_err = Z_STREAM_END; + } + while (offset > 0) { + int size = Z_BUFSIZE; + if (offset < Z_BUFSIZE) size = (int)offset; + + size = gzread(file, s->outbuf, (uInt)size); + if (size <= 0) return -1L; + offset -= size; + } + return s->out; +} + +/* =========================================================================== + Rewinds input file. +*/ +int ZEXPORT gzrewind (file) + gzFile file; +{ + gz_stream *s = (gz_stream*)file; + + if (s == NULL || s->mode != 'r') return -1; + + s->z_err = Z_OK; + s->z_eof = 0; + s->back = EOF; + s->stream.avail_in = 0; + s->stream.next_in = s->inbuf; + s->crc = crc32(0L, Z_NULL, 0); + if (!s->transparent) (void)inflateReset(&s->stream); + s->in = 0; + s->out = 0; + return fseek(s->file, s->start, SEEK_SET); +} + +/* =========================================================================== + Returns the starting position for the next gzread or gzwrite on the + given compressed file. This position represents a number of bytes in the + uncompressed data stream. +*/ +z_off_t ZEXPORT gztell (file) + gzFile file; +{ + return gzseek(file, 0L, SEEK_CUR); +} + +/* =========================================================================== + Returns 1 when EOF has previously been detected reading the given + input stream, otherwise zero. +*/ +int ZEXPORT gzeof (file) + gzFile file; +{ + gz_stream *s = (gz_stream*)file; + + /* With concatenated compressed files that can have embedded + * crc trailers, z_eof is no longer the only/best indicator of EOF + * on a gz_stream. Handle end-of-stream error explicitly here. + */ + if (s == NULL || s->mode != 'r') return 0; + if (s->z_eof) return 1; + return s->z_err == Z_STREAM_END; +} + +/* =========================================================================== + Returns 1 if reading and doing so transparently, otherwise zero. +*/ +int ZEXPORT gzdirect (file) + gzFile file; +{ + gz_stream *s = (gz_stream*)file; + + if (s == NULL || s->mode != 'r') return 0; + return s->transparent; +} + +/* =========================================================================== + Outputs a long in LSB order to the given file +*/ +local void putLong (file, x) + FILE *file; + uLong x; +{ + int n; + for (n = 0; n < 4; n++) { + fputc((int)(x & 0xff), file); + x >>= 8; + } +} + +/* =========================================================================== + Reads a long in LSB order from the given gz_stream. Sets z_err in case + of error. +*/ +local uLong getLong (s) + gz_stream *s; +{ + uLong x = (uLong)get_byte(s); + int c; + + x += ((uLong)get_byte(s))<<8; + x += ((uLong)get_byte(s))<<16; + c = get_byte(s); + if (c == EOF) s->z_err = Z_DATA_ERROR; + x += ((uLong)c)<<24; + return x; +} + +/* =========================================================================== + Flushes all pending output if necessary, closes the compressed file + and deallocates all the (de)compression state. +*/ +int ZEXPORT gzclose (file) + gzFile file; +{ + gz_stream *s = (gz_stream*)file; + + if (s == NULL) return Z_STREAM_ERROR; + + if (s->mode == 'w') { +#ifdef NO_GZCOMPRESS + return Z_STREAM_ERROR; +#else + if (do_flush (file, Z_FINISH) != Z_OK) + return destroy((gz_stream*)file); + + putLong (s->file, s->crc); + putLong (s->file, (uLong)(s->in & 0xffffffff)); +#endif + } + return destroy((gz_stream*)file); +} + +#ifdef STDC +# define zstrerror(errnum) strerror(errnum) +#else +# define zstrerror(errnum) "" +#endif + +/* =========================================================================== + Returns the error message for the last error which occurred on the + given compressed file. errnum is set to zlib error number. If an + error occurred in the file system and not in the compression library, + errnum is set to Z_ERRNO and the application may consult errno + to get the exact error code. +*/ +const char * ZEXPORT gzerror (file, errnum) + gzFile file; + int *errnum; +{ + char *m; + gz_stream *s = (gz_stream*)file; + + if (s == NULL) { + *errnum = Z_STREAM_ERROR; + return (const char*)ERR_MSG(Z_STREAM_ERROR); + } + *errnum = s->z_err; + if (*errnum == Z_OK) return (const char*)""; + + m = (char*)(*errnum == Z_ERRNO ? zstrerror(errno) : s->stream.msg); + + if (m == NULL || *m == '\0') m = (char*)ERR_MSG(s->z_err); + + TRYFREE(s->msg); + s->msg = (char*)ALLOC(strlen(s->path) + strlen(m) + 3); + if (s->msg == Z_NULL) return (const char*)ERR_MSG(Z_MEM_ERROR); + strcpy(s->msg, s->path); + strcat(s->msg, ": "); + strcat(s->msg, m); + return (const char*)s->msg; +} + +/* =========================================================================== + Clear the error and end-of-file flags, and do the same for the real file. +*/ +void ZEXPORT gzclearerr (file) + gzFile file; +{ + gz_stream *s = (gz_stream*)file; + + if (s == NULL) return; + if (s->z_err != Z_STREAM_END) s->z_err = Z_OK; + s->z_eof = 0; + clearerr(s->file); +} diff --git a/Foundation/src/infback.c b/Foundation/src/infback.c index 1e03e1bab..455dbc9ee 100644 --- a/Foundation/src/infback.c +++ b/Foundation/src/infback.c @@ -1,623 +1,623 @@ -/* infback.c -- inflate using a call-back interface - * Copyright (C) 1995-2005 Mark Adler - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -/* - This code is largely copied from inflate.c. Normally either infback.o or - inflate.o would be linked into an application--not both. The interface - with inffast.c is retained so that optimized assembler-coded versions of - inflate_fast() can be used with either inflate.c or infback.c. - */ - -#include "zutil.h" -#include "inftrees.h" -#include "inflate.h" -#include "inffast.h" - -/* function prototypes */ -local void fixedtables OF((struct inflate_state FAR *state)); - -/* - strm provides memory allocation functions in zalloc and zfree, or - Z_NULL to use the library memory allocation functions. - - windowBits is in the range 8..15, and window is a user-supplied - window and output buffer that is 2**windowBits bytes. - */ -int ZEXPORT inflateBackInit_(strm, windowBits, window, version, stream_size) -z_streamp strm; -int windowBits; -unsigned char FAR *window; -const char *version; -int stream_size; -{ - struct inflate_state FAR *state; - - if (version == Z_NULL || version[0] != ZLIB_VERSION[0] || - stream_size != (int)(sizeof(z_stream))) - return Z_VERSION_ERROR; - if (strm == Z_NULL || window == Z_NULL || - windowBits < 8 || windowBits > 15) - return Z_STREAM_ERROR; - strm->msg = Z_NULL; /* in case we return an error */ - if (strm->zalloc == (alloc_func)0) { - strm->zalloc = zcalloc; - strm->opaque = (voidpf)0; - } - if (strm->zfree == (free_func)0) strm->zfree = zcfree; - state = (struct inflate_state FAR *)ZALLOC(strm, 1, - sizeof(struct inflate_state)); - if (state == Z_NULL) return Z_MEM_ERROR; - Tracev((stderr, "inflate: allocated\n")); - strm->state = (struct internal_state FAR *)state; - state->dmax = 32768U; - state->wbits = windowBits; - state->wsize = 1U << windowBits; - state->window = window; - state->write = 0; - state->whave = 0; - return Z_OK; -} - -/* - Return state with length and distance decoding tables and index sizes set to - fixed code decoding. Normally this returns fixed tables from inffixed.h. - If BUILDFIXED is defined, then instead this routine builds the tables the - first time it's called, and returns those tables the first time and - thereafter. This reduces the size of the code by about 2K bytes, in - exchange for a little execution time. However, BUILDFIXED should not be - used for threaded applications, since the rewriting of the tables and virgin - may not be thread-safe. - */ -local void fixedtables(state) -struct inflate_state FAR *state; -{ -#ifdef BUILDFIXED - static int virgin = 1; - static code *lenfix, *distfix; - static code fixed[544]; - - /* build fixed huffman tables if first call (may not be thread safe) */ - if (virgin) { - unsigned sym, bits; - static code *next; - - /* literal/length table */ - sym = 0; - while (sym < 144) state->lens[sym++] = 8; - while (sym < 256) state->lens[sym++] = 9; - while (sym < 280) state->lens[sym++] = 7; - while (sym < 288) state->lens[sym++] = 8; - next = fixed; - lenfix = next; - bits = 9; - inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work); - - /* distance table */ - sym = 0; - while (sym < 32) state->lens[sym++] = 5; - distfix = next; - bits = 5; - inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work); - - /* do this just once */ - virgin = 0; - } -#else /* !BUILDFIXED */ -# include "inffixed.h" -#endif /* BUILDFIXED */ - state->lencode = lenfix; - state->lenbits = 9; - state->distcode = distfix; - state->distbits = 5; -} - -/* Macros for inflateBack(): */ - -/* Load returned state from inflate_fast() */ -#define LOAD() \ - do { \ - put = strm->next_out; \ - left = strm->avail_out; \ - next = strm->next_in; \ - have = strm->avail_in; \ - hold = state->hold; \ - bits = state->bits; \ - } while (0) - -/* Set state from registers for inflate_fast() */ -#define RESTORE() \ - do { \ - strm->next_out = put; \ - strm->avail_out = left; \ - strm->next_in = next; \ - strm->avail_in = have; \ - state->hold = hold; \ - state->bits = bits; \ - } while (0) - -/* Clear the input bit accumulator */ -#define INITBITS() \ - do { \ - hold = 0; \ - bits = 0; \ - } while (0) - -/* Assure that some input is available. If input is requested, but denied, - then return a Z_BUF_ERROR from inflateBack(). */ -#define PULL() \ - do { \ - if (have == 0) { \ - have = in(in_desc, &next); \ - if (have == 0) { \ - next = Z_NULL; \ - ret = Z_BUF_ERROR; \ - goto inf_leave; \ - } \ - } \ - } while (0) - -/* Get a byte of input into the bit accumulator, or return from inflateBack() - with an error if there is no input available. */ -#define PULLBYTE() \ - do { \ - PULL(); \ - have--; \ - hold += (unsigned long)(*next++) << bits; \ - bits += 8; \ - } while (0) - -/* Assure that there are at least n bits in the bit accumulator. If there is - not enough available input to do that, then return from inflateBack() with - an error. */ -#define NEEDBITS(n) \ - do { \ - while (bits < (unsigned)(n)) \ - PULLBYTE(); \ - } while (0) - -/* Return the low n bits of the bit accumulator (n < 16) */ -#define BITS(n) \ - ((unsigned)hold & ((1U << (n)) - 1)) - -/* Remove n bits from the bit accumulator */ -#define DROPBITS(n) \ - do { \ - hold >>= (n); \ - bits -= (unsigned)(n); \ - } while (0) - -/* Remove zero to seven bits as needed to go to a byte boundary */ -#define BYTEBITS() \ - do { \ - hold >>= bits & 7; \ - bits -= bits & 7; \ - } while (0) - -/* Assure that some output space is available, by writing out the window - if it's full. If the write fails, return from inflateBack() with a - Z_BUF_ERROR. */ -#define ROOM() \ - do { \ - if (left == 0) { \ - put = state->window; \ - left = state->wsize; \ - state->whave = left; \ - if (out(out_desc, put, left)) { \ - ret = Z_BUF_ERROR; \ - goto inf_leave; \ - } \ - } \ - } while (0) - -/* - strm provides the memory allocation functions and window buffer on input, - and provides information on the unused input on return. For Z_DATA_ERROR - returns, strm will also provide an error message. - - in() and out() are the call-back input and output functions. When - inflateBack() needs more input, it calls in(). When inflateBack() has - filled the window with output, or when it completes with data in the - window, it calls out() to write out the data. The application must not - change the provided input until in() is called again or inflateBack() - returns. The application must not change the window/output buffer until - inflateBack() returns. - - in() and out() are called with a descriptor parameter provided in the - inflateBack() call. This parameter can be a structure that provides the - information required to do the read or write, as well as accumulated - information on the input and output such as totals and check values. - - in() should return zero on failure. out() should return non-zero on - failure. If either in() or out() fails, than inflateBack() returns a - Z_BUF_ERROR. strm->next_in can be checked for Z_NULL to see whether it - was in() or out() that caused in the error. Otherwise, inflateBack() - returns Z_STREAM_END on success, Z_DATA_ERROR for an deflate format - error, or Z_MEM_ERROR if it could not allocate memory for the state. - inflateBack() can also return Z_STREAM_ERROR if the input parameters - are not correct, i.e. strm is Z_NULL or the state was not initialized. - */ -int ZEXPORT inflateBack(strm, in, in_desc, out, out_desc) -z_streamp strm; -in_func in; -void FAR *in_desc; -out_func out; -void FAR *out_desc; -{ - struct inflate_state FAR *state; - unsigned char FAR *next; /* next input */ - unsigned char FAR *put; /* next output */ - unsigned have, left; /* available input and output */ - unsigned long hold; /* bit buffer */ - unsigned bits; /* bits in bit buffer */ - unsigned copy; /* number of stored or match bytes to copy */ - unsigned char FAR *from; /* where to copy match bytes from */ - code this; /* current decoding table entry */ - code last; /* parent table entry */ - unsigned len; /* length to copy for repeats, bits to drop */ - int ret; /* return code */ - static const unsigned short order[19] = /* permutation of code lengths */ - {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; - - /* Check that the strm exists and that the state was initialized */ - if (strm == Z_NULL || strm->state == Z_NULL) - return Z_STREAM_ERROR; - state = (struct inflate_state FAR *)strm->state; - - /* Reset the state */ - strm->msg = Z_NULL; - state->mode = TYPE; - state->last = 0; - state->whave = 0; - next = strm->next_in; - have = next != Z_NULL ? strm->avail_in : 0; - hold = 0; - bits = 0; - put = state->window; - left = state->wsize; - - /* Inflate until end of block marked as last */ - for (;;) - switch (state->mode) { - case TYPE: - /* determine and dispatch block type */ - if (state->last) { - BYTEBITS(); - state->mode = DONE; - break; - } - NEEDBITS(3); - state->last = BITS(1); - DROPBITS(1); - switch (BITS(2)) { - case 0: /* stored block */ - Tracev((stderr, "inflate: stored block%s\n", - state->last ? " (last)" : "")); - state->mode = STORED; - break; - case 1: /* fixed block */ - fixedtables(state); - Tracev((stderr, "inflate: fixed codes block%s\n", - state->last ? " (last)" : "")); - state->mode = LEN; /* decode codes */ - break; - case 2: /* dynamic block */ - Tracev((stderr, "inflate: dynamic codes block%s\n", - state->last ? " (last)" : "")); - state->mode = TABLE; - break; - case 3: - strm->msg = (char *)"invalid block type"; - state->mode = BAD; - } - DROPBITS(2); - break; - - case STORED: - /* get and verify stored block length */ - BYTEBITS(); /* go to byte boundary */ - NEEDBITS(32); - if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) { - strm->msg = (char *)"invalid stored block lengths"; - state->mode = BAD; - break; - } - state->length = (unsigned)hold & 0xffff; - Tracev((stderr, "inflate: stored length %u\n", - state->length)); - INITBITS(); - - /* copy stored block from input to output */ - while (state->length != 0) { - copy = state->length; - PULL(); - ROOM(); - if (copy > have) copy = have; - if (copy > left) copy = left; - zmemcpy(put, next, copy); - have -= copy; - next += copy; - left -= copy; - put += copy; - state->length -= copy; - } - Tracev((stderr, "inflate: stored end\n")); - state->mode = TYPE; - break; - - case TABLE: - /* get dynamic table entries descriptor */ - NEEDBITS(14); - state->nlen = BITS(5) + 257; - DROPBITS(5); - state->ndist = BITS(5) + 1; - DROPBITS(5); - state->ncode = BITS(4) + 4; - DROPBITS(4); -#ifndef PKZIP_BUG_WORKAROUND - if (state->nlen > 286 || state->ndist > 30) { - strm->msg = (char *)"too many length or distance symbols"; - state->mode = BAD; - break; - } -#endif - Tracev((stderr, "inflate: table sizes ok\n")); - - /* get code length code lengths (not a typo) */ - state->have = 0; - while (state->have < state->ncode) { - NEEDBITS(3); - state->lens[order[state->have++]] = (unsigned short)BITS(3); - DROPBITS(3); - } - while (state->have < 19) - state->lens[order[state->have++]] = 0; - state->next = state->codes; - state->lencode = (code const FAR *)(state->next); - state->lenbits = 7; - ret = inflate_table(CODES, state->lens, 19, &(state->next), - &(state->lenbits), state->work); - if (ret) { - strm->msg = (char *)"invalid code lengths set"; - state->mode = BAD; - break; - } - Tracev((stderr, "inflate: code lengths ok\n")); - - /* get length and distance code code lengths */ - state->have = 0; - while (state->have < state->nlen + state->ndist) { - for (;;) { - this = state->lencode[BITS(state->lenbits)]; - if ((unsigned)(this.bits) <= bits) break; - PULLBYTE(); - } - if (this.val < 16) { - NEEDBITS(this.bits); - DROPBITS(this.bits); - state->lens[state->have++] = this.val; - } - else { - if (this.val == 16) { - NEEDBITS(this.bits + 2); - DROPBITS(this.bits); - if (state->have == 0) { - strm->msg = (char *)"invalid bit length repeat"; - state->mode = BAD; - break; - } - len = (unsigned)(state->lens[state->have - 1]); - copy = 3 + BITS(2); - DROPBITS(2); - } - else if (this.val == 17) { - NEEDBITS(this.bits + 3); - DROPBITS(this.bits); - len = 0; - copy = 3 + BITS(3); - DROPBITS(3); - } - else { - NEEDBITS(this.bits + 7); - DROPBITS(this.bits); - len = 0; - copy = 11 + BITS(7); - DROPBITS(7); - } - if (state->have + copy > state->nlen + state->ndist) { - strm->msg = (char *)"invalid bit length repeat"; - state->mode = BAD; - break; - } - while (copy--) - state->lens[state->have++] = (unsigned short)len; - } - } - - /* handle error breaks in while */ - if (state->mode == BAD) break; - - /* build code tables */ - state->next = state->codes; - state->lencode = (code const FAR *)(state->next); - state->lenbits = 9; - ret = inflate_table(LENS, state->lens, state->nlen, &(state->next), - &(state->lenbits), state->work); - if (ret) { - strm->msg = (char *)"invalid literal/lengths set"; - state->mode = BAD; - break; - } - state->distcode = (code const FAR *)(state->next); - state->distbits = 6; - ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist, - &(state->next), &(state->distbits), state->work); - if (ret) { - strm->msg = (char *)"invalid distances set"; - state->mode = BAD; - break; - } - Tracev((stderr, "inflate: codes ok\n")); - state->mode = LEN; - - case LEN: - /* use inflate_fast() if we have enough input and output */ - if (have >= 6 && left >= 258) { - RESTORE(); - if (state->whave < state->wsize) - state->whave = state->wsize - left; - inflate_fast(strm, state->wsize); - LOAD(); - break; - } - - /* get a literal, length, or end-of-block code */ - for (;;) { - this = state->lencode[BITS(state->lenbits)]; - if ((unsigned)(this.bits) <= bits) break; - PULLBYTE(); - } - if (this.op && (this.op & 0xf0) == 0) { - last = this; - for (;;) { - this = state->lencode[last.val + - (BITS(last.bits + last.op) >> last.bits)]; - if ((unsigned)(last.bits + this.bits) <= bits) break; - PULLBYTE(); - } - DROPBITS(last.bits); - } - DROPBITS(this.bits); - state->length = (unsigned)this.val; - - /* process literal */ - if (this.op == 0) { - Tracevv((stderr, this.val >= 0x20 && this.val < 0x7f ? - "inflate: literal '%c'\n" : - "inflate: literal 0x%02x\n", this.val)); - ROOM(); - *put++ = (unsigned char)(state->length); - left--; - state->mode = LEN; - break; - } - - /* process end of block */ - if (this.op & 32) { - Tracevv((stderr, "inflate: end of block\n")); - state->mode = TYPE; - break; - } - - /* invalid code */ - if (this.op & 64) { - strm->msg = (char *)"invalid literal/length code"; - state->mode = BAD; - break; - } - - /* length code -- get extra bits, if any */ - state->extra = (unsigned)(this.op) & 15; - if (state->extra != 0) { - NEEDBITS(state->extra); - state->length += BITS(state->extra); - DROPBITS(state->extra); - } - Tracevv((stderr, "inflate: length %u\n", state->length)); - - /* get distance code */ - for (;;) { - this = state->distcode[BITS(state->distbits)]; - if ((unsigned)(this.bits) <= bits) break; - PULLBYTE(); - } - if ((this.op & 0xf0) == 0) { - last = this; - for (;;) { - this = state->distcode[last.val + - (BITS(last.bits + last.op) >> last.bits)]; - if ((unsigned)(last.bits + this.bits) <= bits) break; - PULLBYTE(); - } - DROPBITS(last.bits); - } - DROPBITS(this.bits); - if (this.op & 64) { - strm->msg = (char *)"invalid distance code"; - state->mode = BAD; - break; - } - state->offset = (unsigned)this.val; - - /* get distance extra bits, if any */ - state->extra = (unsigned)(this.op) & 15; - if (state->extra != 0) { - NEEDBITS(state->extra); - state->offset += BITS(state->extra); - DROPBITS(state->extra); - } - if (state->offset > state->wsize - (state->whave < state->wsize ? - left : 0)) { - strm->msg = (char *)"invalid distance too far back"; - state->mode = BAD; - break; - } - Tracevv((stderr, "inflate: distance %u\n", state->offset)); - - /* copy match from window to output */ - do { - ROOM(); - copy = state->wsize - state->offset; - if (copy < left) { - from = put + copy; - copy = left - copy; - } - else { - from = put - state->offset; - copy = left; - } - if (copy > state->length) copy = state->length; - state->length -= copy; - left -= copy; - do { - *put++ = *from++; - } while (--copy); - } while (state->length != 0); - break; - - case DONE: - /* inflate stream terminated properly -- write leftover output */ - ret = Z_STREAM_END; - if (left < state->wsize) { - if (out(out_desc, state->window, state->wsize - left)) - ret = Z_BUF_ERROR; - } - goto inf_leave; - - case BAD: - ret = Z_DATA_ERROR; - goto inf_leave; - - default: /* can't happen, but makes compilers happy */ - ret = Z_STREAM_ERROR; - goto inf_leave; - } - - /* Return unused input */ - inf_leave: - strm->next_in = next; - strm->avail_in = have; - return ret; -} - -int ZEXPORT inflateBackEnd(strm) -z_streamp strm; -{ - if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0) - return Z_STREAM_ERROR; - ZFREE(strm, strm->state); - strm->state = Z_NULL; - Tracev((stderr, "inflate: end\n")); - return Z_OK; -} +/* infback.c -- inflate using a call-back interface + * Copyright (C) 1995-2005 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* + This code is largely copied from inflate.c. Normally either infback.o or + inflate.o would be linked into an application--not both. The interface + with inffast.c is retained so that optimized assembler-coded versions of + inflate_fast() can be used with either inflate.c or infback.c. + */ + +#include "zutil.h" +#include "inftrees.h" +#include "inflate.h" +#include "inffast.h" + +/* function prototypes */ +local void fixedtables OF((struct inflate_state FAR *state)); + +/* + strm provides memory allocation functions in zalloc and zfree, or + Z_NULL to use the library memory allocation functions. + + windowBits is in the range 8..15, and window is a user-supplied + window and output buffer that is 2**windowBits bytes. + */ +int ZEXPORT inflateBackInit_(strm, windowBits, window, version, stream_size) +z_streamp strm; +int windowBits; +unsigned char FAR *window; +const char *version; +int stream_size; +{ + struct inflate_state FAR *state; + + if (version == Z_NULL || version[0] != ZLIB_VERSION[0] || + stream_size != (int)(sizeof(z_stream))) + return Z_VERSION_ERROR; + if (strm == Z_NULL || window == Z_NULL || + windowBits < 8 || windowBits > 15) + return Z_STREAM_ERROR; + strm->msg = Z_NULL; /* in case we return an error */ + if (strm->zalloc == (alloc_func)0) { + strm->zalloc = zcalloc; + strm->opaque = (voidpf)0; + } + if (strm->zfree == (free_func)0) strm->zfree = zcfree; + state = (struct inflate_state FAR *)ZALLOC(strm, 1, + sizeof(struct inflate_state)); + if (state == Z_NULL) return Z_MEM_ERROR; + Tracev((stderr, "inflate: allocated\n")); + strm->state = (struct internal_state FAR *)state; + state->dmax = 32768U; + state->wbits = windowBits; + state->wsize = 1U << windowBits; + state->window = window; + state->write = 0; + state->whave = 0; + return Z_OK; +} + +/* + Return state with length and distance decoding tables and index sizes set to + fixed code decoding. Normally this returns fixed tables from inffixed.h. + If BUILDFIXED is defined, then instead this routine builds the tables the + first time it's called, and returns those tables the first time and + thereafter. This reduces the size of the code by about 2K bytes, in + exchange for a little execution time. However, BUILDFIXED should not be + used for threaded applications, since the rewriting of the tables and virgin + may not be thread-safe. + */ +local void fixedtables(state) +struct inflate_state FAR *state; +{ +#ifdef BUILDFIXED + static int virgin = 1; + static code *lenfix, *distfix; + static code fixed[544]; + + /* build fixed huffman tables if first call (may not be thread safe) */ + if (virgin) { + unsigned sym, bits; + static code *next; + + /* literal/length table */ + sym = 0; + while (sym < 144) state->lens[sym++] = 8; + while (sym < 256) state->lens[sym++] = 9; + while (sym < 280) state->lens[sym++] = 7; + while (sym < 288) state->lens[sym++] = 8; + next = fixed; + lenfix = next; + bits = 9; + inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work); + + /* distance table */ + sym = 0; + while (sym < 32) state->lens[sym++] = 5; + distfix = next; + bits = 5; + inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work); + + /* do this just once */ + virgin = 0; + } +#else /* !BUILDFIXED */ +# include "inffixed.h" +#endif /* BUILDFIXED */ + state->lencode = lenfix; + state->lenbits = 9; + state->distcode = distfix; + state->distbits = 5; +} + +/* Macros for inflateBack(): */ + +/* Load returned state from inflate_fast() */ +#define LOAD() \ + do { \ + put = strm->next_out; \ + left = strm->avail_out; \ + next = strm->next_in; \ + have = strm->avail_in; \ + hold = state->hold; \ + bits = state->bits; \ + } while (0) + +/* Set state from registers for inflate_fast() */ +#define RESTORE() \ + do { \ + strm->next_out = put; \ + strm->avail_out = left; \ + strm->next_in = next; \ + strm->avail_in = have; \ + state->hold = hold; \ + state->bits = bits; \ + } while (0) + +/* Clear the input bit accumulator */ +#define INITBITS() \ + do { \ + hold = 0; \ + bits = 0; \ + } while (0) + +/* Assure that some input is available. If input is requested, but denied, + then return a Z_BUF_ERROR from inflateBack(). */ +#define PULL() \ + do { \ + if (have == 0) { \ + have = in(in_desc, &next); \ + if (have == 0) { \ + next = Z_NULL; \ + ret = Z_BUF_ERROR; \ + goto inf_leave; \ + } \ + } \ + } while (0) + +/* Get a byte of input into the bit accumulator, or return from inflateBack() + with an error if there is no input available. */ +#define PULLBYTE() \ + do { \ + PULL(); \ + have--; \ + hold += (unsigned long)(*next++) << bits; \ + bits += 8; \ + } while (0) + +/* Assure that there are at least n bits in the bit accumulator. If there is + not enough available input to do that, then return from inflateBack() with + an error. */ +#define NEEDBITS(n) \ + do { \ + while (bits < (unsigned)(n)) \ + PULLBYTE(); \ + } while (0) + +/* Return the low n bits of the bit accumulator (n < 16) */ +#define BITS(n) \ + ((unsigned)hold & ((1U << (n)) - 1)) + +/* Remove n bits from the bit accumulator */ +#define DROPBITS(n) \ + do { \ + hold >>= (n); \ + bits -= (unsigned)(n); \ + } while (0) + +/* Remove zero to seven bits as needed to go to a byte boundary */ +#define BYTEBITS() \ + do { \ + hold >>= bits & 7; \ + bits -= bits & 7; \ + } while (0) + +/* Assure that some output space is available, by writing out the window + if it's full. If the write fails, return from inflateBack() with a + Z_BUF_ERROR. */ +#define ROOM() \ + do { \ + if (left == 0) { \ + put = state->window; \ + left = state->wsize; \ + state->whave = left; \ + if (out(out_desc, put, left)) { \ + ret = Z_BUF_ERROR; \ + goto inf_leave; \ + } \ + } \ + } while (0) + +/* + strm provides the memory allocation functions and window buffer on input, + and provides information on the unused input on return. For Z_DATA_ERROR + returns, strm will also provide an error message. + + in() and out() are the call-back input and output functions. When + inflateBack() needs more input, it calls in(). When inflateBack() has + filled the window with output, or when it completes with data in the + window, it calls out() to write out the data. The application must not + change the provided input until in() is called again or inflateBack() + returns. The application must not change the window/output buffer until + inflateBack() returns. + + in() and out() are called with a descriptor parameter provided in the + inflateBack() call. This parameter can be a structure that provides the + information required to do the read or write, as well as accumulated + information on the input and output such as totals and check values. + + in() should return zero on failure. out() should return non-zero on + failure. If either in() or out() fails, than inflateBack() returns a + Z_BUF_ERROR. strm->next_in can be checked for Z_NULL to see whether it + was in() or out() that caused in the error. Otherwise, inflateBack() + returns Z_STREAM_END on success, Z_DATA_ERROR for an deflate format + error, or Z_MEM_ERROR if it could not allocate memory for the state. + inflateBack() can also return Z_STREAM_ERROR if the input parameters + are not correct, i.e. strm is Z_NULL or the state was not initialized. + */ +int ZEXPORT inflateBack(strm, in, in_desc, out, out_desc) +z_streamp strm; +in_func in; +void FAR *in_desc; +out_func out; +void FAR *out_desc; +{ + struct inflate_state FAR *state; + unsigned char FAR *next; /* next input */ + unsigned char FAR *put; /* next output */ + unsigned have, left; /* available input and output */ + unsigned long hold; /* bit buffer */ + unsigned bits; /* bits in bit buffer */ + unsigned copy; /* number of stored or match bytes to copy */ + unsigned char FAR *from; /* where to copy match bytes from */ + code this; /* current decoding table entry */ + code last; /* parent table entry */ + unsigned len; /* length to copy for repeats, bits to drop */ + int ret; /* return code */ + static const unsigned short order[19] = /* permutation of code lengths */ + {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; + + /* Check that the strm exists and that the state was initialized */ + if (strm == Z_NULL || strm->state == Z_NULL) + return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + + /* Reset the state */ + strm->msg = Z_NULL; + state->mode = TYPE; + state->last = 0; + state->whave = 0; + next = strm->next_in; + have = next != Z_NULL ? strm->avail_in : 0; + hold = 0; + bits = 0; + put = state->window; + left = state->wsize; + + /* Inflate until end of block marked as last */ + for (;;) + switch (state->mode) { + case TYPE: + /* determine and dispatch block type */ + if (state->last) { + BYTEBITS(); + state->mode = DONE; + break; + } + NEEDBITS(3); + state->last = BITS(1); + DROPBITS(1); + switch (BITS(2)) { + case 0: /* stored block */ + Tracev((stderr, "inflate: stored block%s\n", + state->last ? " (last)" : "")); + state->mode = STORED; + break; + case 1: /* fixed block */ + fixedtables(state); + Tracev((stderr, "inflate: fixed codes block%s\n", + state->last ? " (last)" : "")); + state->mode = LEN; /* decode codes */ + break; + case 2: /* dynamic block */ + Tracev((stderr, "inflate: dynamic codes block%s\n", + state->last ? " (last)" : "")); + state->mode = TABLE; + break; + case 3: + strm->msg = (char *)"invalid block type"; + state->mode = BAD; + } + DROPBITS(2); + break; + + case STORED: + /* get and verify stored block length */ + BYTEBITS(); /* go to byte boundary */ + NEEDBITS(32); + if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) { + strm->msg = (char *)"invalid stored block lengths"; + state->mode = BAD; + break; + } + state->length = (unsigned)hold & 0xffff; + Tracev((stderr, "inflate: stored length %u\n", + state->length)); + INITBITS(); + + /* copy stored block from input to output */ + while (state->length != 0) { + copy = state->length; + PULL(); + ROOM(); + if (copy > have) copy = have; + if (copy > left) copy = left; + zmemcpy(put, next, copy); + have -= copy; + next += copy; + left -= copy; + put += copy; + state->length -= copy; + } + Tracev((stderr, "inflate: stored end\n")); + state->mode = TYPE; + break; + + case TABLE: + /* get dynamic table entries descriptor */ + NEEDBITS(14); + state->nlen = BITS(5) + 257; + DROPBITS(5); + state->ndist = BITS(5) + 1; + DROPBITS(5); + state->ncode = BITS(4) + 4; + DROPBITS(4); +#ifndef PKZIP_BUG_WORKAROUND + if (state->nlen > 286 || state->ndist > 30) { + strm->msg = (char *)"too many length or distance symbols"; + state->mode = BAD; + break; + } +#endif + Tracev((stderr, "inflate: table sizes ok\n")); + + /* get code length code lengths (not a typo) */ + state->have = 0; + while (state->have < state->ncode) { + NEEDBITS(3); + state->lens[order[state->have++]] = (unsigned short)BITS(3); + DROPBITS(3); + } + while (state->have < 19) + state->lens[order[state->have++]] = 0; + state->next = state->codes; + state->lencode = (code const FAR *)(state->next); + state->lenbits = 7; + ret = inflate_table(CODES, state->lens, 19, &(state->next), + &(state->lenbits), state->work); + if (ret) { + strm->msg = (char *)"invalid code lengths set"; + state->mode = BAD; + break; + } + Tracev((stderr, "inflate: code lengths ok\n")); + + /* get length and distance code code lengths */ + state->have = 0; + while (state->have < state->nlen + state->ndist) { + for (;;) { + this = state->lencode[BITS(state->lenbits)]; + if ((unsigned)(this.bits) <= bits) break; + PULLBYTE(); + } + if (this.val < 16) { + NEEDBITS(this.bits); + DROPBITS(this.bits); + state->lens[state->have++] = this.val; + } + else { + if (this.val == 16) { + NEEDBITS(this.bits + 2); + DROPBITS(this.bits); + if (state->have == 0) { + strm->msg = (char *)"invalid bit length repeat"; + state->mode = BAD; + break; + } + len = (unsigned)(state->lens[state->have - 1]); + copy = 3 + BITS(2); + DROPBITS(2); + } + else if (this.val == 17) { + NEEDBITS(this.bits + 3); + DROPBITS(this.bits); + len = 0; + copy = 3 + BITS(3); + DROPBITS(3); + } + else { + NEEDBITS(this.bits + 7); + DROPBITS(this.bits); + len = 0; + copy = 11 + BITS(7); + DROPBITS(7); + } + if (state->have + copy > state->nlen + state->ndist) { + strm->msg = (char *)"invalid bit length repeat"; + state->mode = BAD; + break; + } + while (copy--) + state->lens[state->have++] = (unsigned short)len; + } + } + + /* handle error breaks in while */ + if (state->mode == BAD) break; + + /* build code tables */ + state->next = state->codes; + state->lencode = (code const FAR *)(state->next); + state->lenbits = 9; + ret = inflate_table(LENS, state->lens, state->nlen, &(state->next), + &(state->lenbits), state->work); + if (ret) { + strm->msg = (char *)"invalid literal/lengths set"; + state->mode = BAD; + break; + } + state->distcode = (code const FAR *)(state->next); + state->distbits = 6; + ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist, + &(state->next), &(state->distbits), state->work); + if (ret) { + strm->msg = (char *)"invalid distances set"; + state->mode = BAD; + break; + } + Tracev((stderr, "inflate: codes ok\n")); + state->mode = LEN; + + case LEN: + /* use inflate_fast() if we have enough input and output */ + if (have >= 6 && left >= 258) { + RESTORE(); + if (state->whave < state->wsize) + state->whave = state->wsize - left; + inflate_fast(strm, state->wsize); + LOAD(); + break; + } + + /* get a literal, length, or end-of-block code */ + for (;;) { + this = state->lencode[BITS(state->lenbits)]; + if ((unsigned)(this.bits) <= bits) break; + PULLBYTE(); + } + if (this.op && (this.op & 0xf0) == 0) { + last = this; + for (;;) { + this = state->lencode[last.val + + (BITS(last.bits + last.op) >> last.bits)]; + if ((unsigned)(last.bits + this.bits) <= bits) break; + PULLBYTE(); + } + DROPBITS(last.bits); + } + DROPBITS(this.bits); + state->length = (unsigned)this.val; + + /* process literal */ + if (this.op == 0) { + Tracevv((stderr, this.val >= 0x20 && this.val < 0x7f ? + "inflate: literal '%c'\n" : + "inflate: literal 0x%02x\n", this.val)); + ROOM(); + *put++ = (unsigned char)(state->length); + left--; + state->mode = LEN; + break; + } + + /* process end of block */ + if (this.op & 32) { + Tracevv((stderr, "inflate: end of block\n")); + state->mode = TYPE; + break; + } + + /* invalid code */ + if (this.op & 64) { + strm->msg = (char *)"invalid literal/length code"; + state->mode = BAD; + break; + } + + /* length code -- get extra bits, if any */ + state->extra = (unsigned)(this.op) & 15; + if (state->extra != 0) { + NEEDBITS(state->extra); + state->length += BITS(state->extra); + DROPBITS(state->extra); + } + Tracevv((stderr, "inflate: length %u\n", state->length)); + + /* get distance code */ + for (;;) { + this = state->distcode[BITS(state->distbits)]; + if ((unsigned)(this.bits) <= bits) break; + PULLBYTE(); + } + if ((this.op & 0xf0) == 0) { + last = this; + for (;;) { + this = state->distcode[last.val + + (BITS(last.bits + last.op) >> last.bits)]; + if ((unsigned)(last.bits + this.bits) <= bits) break; + PULLBYTE(); + } + DROPBITS(last.bits); + } + DROPBITS(this.bits); + if (this.op & 64) { + strm->msg = (char *)"invalid distance code"; + state->mode = BAD; + break; + } + state->offset = (unsigned)this.val; + + /* get distance extra bits, if any */ + state->extra = (unsigned)(this.op) & 15; + if (state->extra != 0) { + NEEDBITS(state->extra); + state->offset += BITS(state->extra); + DROPBITS(state->extra); + } + if (state->offset > state->wsize - (state->whave < state->wsize ? + left : 0)) { + strm->msg = (char *)"invalid distance too far back"; + state->mode = BAD; + break; + } + Tracevv((stderr, "inflate: distance %u\n", state->offset)); + + /* copy match from window to output */ + do { + ROOM(); + copy = state->wsize - state->offset; + if (copy < left) { + from = put + copy; + copy = left - copy; + } + else { + from = put - state->offset; + copy = left; + } + if (copy > state->length) copy = state->length; + state->length -= copy; + left -= copy; + do { + *put++ = *from++; + } while (--copy); + } while (state->length != 0); + break; + + case DONE: + /* inflate stream terminated properly -- write leftover output */ + ret = Z_STREAM_END; + if (left < state->wsize) { + if (out(out_desc, state->window, state->wsize - left)) + ret = Z_BUF_ERROR; + } + goto inf_leave; + + case BAD: + ret = Z_DATA_ERROR; + goto inf_leave; + + default: /* can't happen, but makes compilers happy */ + ret = Z_STREAM_ERROR; + goto inf_leave; + } + + /* Return unused input */ + inf_leave: + strm->next_in = next; + strm->avail_in = have; + return ret; +} + +int ZEXPORT inflateBackEnd(strm) +z_streamp strm; +{ + if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0) + return Z_STREAM_ERROR; + ZFREE(strm, strm->state); + strm->state = Z_NULL; + Tracev((stderr, "inflate: end\n")); + return Z_OK; +} diff --git a/Foundation/src/inffast.c b/Foundation/src/inffast.c index fa31cad90..bbee92ed1 100644 --- a/Foundation/src/inffast.c +++ b/Foundation/src/inffast.c @@ -1,318 +1,318 @@ -/* inffast.c -- fast decoding - * Copyright (C) 1995-2004 Mark Adler - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -#include "zutil.h" -#include "inftrees.h" -#include "inflate.h" -#include "inffast.h" - -#ifndef ASMINF - -/* Allow machine dependent optimization for post-increment or pre-increment. - Based on testing to date, - Pre-increment preferred for: - - PowerPC G3 (Adler) - - MIPS R5000 (Randers-Pehrson) - Post-increment preferred for: - - none - No measurable difference: - - Pentium III (Anderson) - - M68060 (Nikl) - */ -#ifdef POSTINC -# define OFF 0 -# define PUP(a) *(a)++ -#else -# define OFF 1 -# define PUP(a) *++(a) -#endif - -/* - Decode literal, length, and distance codes and write out the resulting - literal and match bytes until either not enough input or output is - available, an end-of-block is encountered, or a data error is encountered. - When large enough input and output buffers are supplied to inflate(), for - example, a 16K input buffer and a 64K output buffer, more than 95% of the - inflate execution time is spent in this routine. - - Entry assumptions: - - state->mode == LEN - strm->avail_in >= 6 - strm->avail_out >= 258 - start >= strm->avail_out - state->bits < 8 - - On return, state->mode is one of: - - LEN -- ran out of enough output space or enough available input - TYPE -- reached end of block code, inflate() to interpret next block - BAD -- error in block data - - Notes: - - - The maximum input bits used by a length/distance pair is 15 bits for the - length code, 5 bits for the length extra, 15 bits for the distance code, - and 13 bits for the distance extra. This totals 48 bits, or six bytes. - Therefore if strm->avail_in >= 6, then there is enough input to avoid - checking for available input while decoding. - - - The maximum bytes that a single length/distance pair can output is 258 - bytes, which is the maximum length that can be coded. inflate_fast() - requires strm->avail_out >= 258 for each loop to avoid checking for - output space. - */ -void inflate_fast(strm, start) -z_streamp strm; -unsigned start; /* inflate()'s starting value for strm->avail_out */ -{ - struct inflate_state FAR *state; - unsigned char FAR *in; /* local strm->next_in */ - unsigned char FAR *last; /* while in < last, enough input available */ - unsigned char FAR *out; /* local strm->next_out */ - unsigned char FAR *beg; /* inflate()'s initial strm->next_out */ - unsigned char FAR *end; /* while out < end, enough space available */ -#ifdef INFLATE_STRICT - unsigned dmax; /* maximum distance from zlib header */ -#endif - unsigned wsize; /* window size or zero if not using window */ - unsigned whave; /* valid bytes in the window */ - unsigned write; /* window write index */ - unsigned char FAR *window; /* allocated sliding window, if wsize != 0 */ - unsigned long hold; /* local strm->hold */ - unsigned bits; /* local strm->bits */ - code const FAR *lcode; /* local strm->lencode */ - code const FAR *dcode; /* local strm->distcode */ - unsigned lmask; /* mask for first level of length codes */ - unsigned dmask; /* mask for first level of distance codes */ - code this; /* retrieved table entry */ - unsigned op; /* code bits, operation, extra bits, or */ - /* window position, window bytes to copy */ - unsigned len; /* match length, unused bytes */ - unsigned dist; /* match distance */ - unsigned char FAR *from; /* where to copy match from */ - - /* copy state to local variables */ - state = (struct inflate_state FAR *)strm->state; - in = strm->next_in - OFF; - last = in + (strm->avail_in - 5); - out = strm->next_out - OFF; - beg = out - (start - strm->avail_out); - end = out + (strm->avail_out - 257); -#ifdef INFLATE_STRICT - dmax = state->dmax; -#endif - wsize = state->wsize; - whave = state->whave; - write = state->write; - window = state->window; - hold = state->hold; - bits = state->bits; - lcode = state->lencode; - dcode = state->distcode; - lmask = (1U << state->lenbits) - 1; - dmask = (1U << state->distbits) - 1; - - /* decode literals and length/distances until end-of-block or not enough - input data or output space */ - do { - if (bits < 15) { - hold += (unsigned long)(PUP(in)) << bits; - bits += 8; - hold += (unsigned long)(PUP(in)) << bits; - bits += 8; - } - this = lcode[hold & lmask]; - dolen: - op = (unsigned)(this.bits); - hold >>= op; - bits -= op; - op = (unsigned)(this.op); - if (op == 0) { /* literal */ - Tracevv((stderr, this.val >= 0x20 && this.val < 0x7f ? - "inflate: literal '%c'\n" : - "inflate: literal 0x%02x\n", this.val)); - PUP(out) = (unsigned char)(this.val); - } - else if (op & 16) { /* length base */ - len = (unsigned)(this.val); - op &= 15; /* number of extra bits */ - if (op) { - if (bits < op) { - hold += (unsigned long)(PUP(in)) << bits; - bits += 8; - } - len += (unsigned)hold & ((1U << op) - 1); - hold >>= op; - bits -= op; - } - Tracevv((stderr, "inflate: length %u\n", len)); - if (bits < 15) { - hold += (unsigned long)(PUP(in)) << bits; - bits += 8; - hold += (unsigned long)(PUP(in)) << bits; - bits += 8; - } - this = dcode[hold & dmask]; - dodist: - op = (unsigned)(this.bits); - hold >>= op; - bits -= op; - op = (unsigned)(this.op); - if (op & 16) { /* distance base */ - dist = (unsigned)(this.val); - op &= 15; /* number of extra bits */ - if (bits < op) { - hold += (unsigned long)(PUP(in)) << bits; - bits += 8; - if (bits < op) { - hold += (unsigned long)(PUP(in)) << bits; - bits += 8; - } - } - dist += (unsigned)hold & ((1U << op) - 1); -#ifdef INFLATE_STRICT - if (dist > dmax) { - strm->msg = (char *)"invalid distance too far back"; - state->mode = BAD; - break; - } -#endif - hold >>= op; - bits -= op; - Tracevv((stderr, "inflate: distance %u\n", dist)); - op = (unsigned)(out - beg); /* max distance in output */ - if (dist > op) { /* see if copy from window */ - op = dist - op; /* distance back in window */ - if (op > whave) { - strm->msg = (char *)"invalid distance too far back"; - state->mode = BAD; - break; - } - from = window - OFF; - if (write == 0) { /* very common case */ - from += wsize - op; - if (op < len) { /* some from window */ - len -= op; - do { - PUP(out) = PUP(from); - } while (--op); - from = out - dist; /* rest from output */ - } - } - else if (write < op) { /* wrap around window */ - from += wsize + write - op; - op -= write; - if (op < len) { /* some from end of window */ - len -= op; - do { - PUP(out) = PUP(from); - } while (--op); - from = window - OFF; - if (write < len) { /* some from start of window */ - op = write; - len -= op; - do { - PUP(out) = PUP(from); - } while (--op); - from = out - dist; /* rest from output */ - } - } - } - else { /* contiguous in window */ - from += write - op; - if (op < len) { /* some from window */ - len -= op; - do { - PUP(out) = PUP(from); - } while (--op); - from = out - dist; /* rest from output */ - } - } - while (len > 2) { - PUP(out) = PUP(from); - PUP(out) = PUP(from); - PUP(out) = PUP(from); - len -= 3; - } - if (len) { - PUP(out) = PUP(from); - if (len > 1) - PUP(out) = PUP(from); - } - } - else { - from = out - dist; /* copy direct from output */ - do { /* minimum length is three */ - PUP(out) = PUP(from); - PUP(out) = PUP(from); - PUP(out) = PUP(from); - len -= 3; - } while (len > 2); - if (len) { - PUP(out) = PUP(from); - if (len > 1) - PUP(out) = PUP(from); - } - } - } - else if ((op & 64) == 0) { /* 2nd level distance code */ - this = dcode[this.val + (hold & ((1U << op) - 1))]; - goto dodist; - } - else { - strm->msg = (char *)"invalid distance code"; - state->mode = BAD; - break; - } - } - else if ((op & 64) == 0) { /* 2nd level length code */ - this = lcode[this.val + (hold & ((1U << op) - 1))]; - goto dolen; - } - else if (op & 32) { /* end-of-block */ - Tracevv((stderr, "inflate: end of block\n")); - state->mode = TYPE; - break; - } - else { - strm->msg = (char *)"invalid literal/length code"; - state->mode = BAD; - break; - } - } while (in < last && out < end); - - /* return unused bytes (on entry, bits < 8, so in won't go too far back) */ - len = bits >> 3; - in -= len; - bits -= len << 3; - hold &= (1U << bits) - 1; - - /* update state and return */ - strm->next_in = in + OFF; - strm->next_out = out + OFF; - strm->avail_in = (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last)); - strm->avail_out = (unsigned)(out < end ? - 257 + (end - out) : 257 - (out - end)); - state->hold = hold; - state->bits = bits; - return; -} - -/* - inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe): - - Using bit fields for code structure - - Different op definition to avoid & for extra bits (do & for table bits) - - Three separate decoding do-loops for direct, window, and write == 0 - - Special case for distance > 1 copies to do overlapped load and store copy - - Explicit branch predictions (based on measured branch probabilities) - - Deferring match copy and interspersed it with decoding subsequent codes - - Swapping literal/length else - - Swapping window/direct else - - Larger unrolled copy loops (three is about right) - - Moving len -= 3 statement into middle of loop - */ - -#endif /* !ASMINF */ +/* inffast.c -- fast decoding + * Copyright (C) 1995-2004 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +#include "zutil.h" +#include "inftrees.h" +#include "inflate.h" +#include "inffast.h" + +#ifndef ASMINF + +/* Allow machine dependent optimization for post-increment or pre-increment. + Based on testing to date, + Pre-increment preferred for: + - PowerPC G3 (Adler) + - MIPS R5000 (Randers-Pehrson) + Post-increment preferred for: + - none + No measurable difference: + - Pentium III (Anderson) + - M68060 (Nikl) + */ +#ifdef POSTINC +# define OFF 0 +# define PUP(a) *(a)++ +#else +# define OFF 1 +# define PUP(a) *++(a) +#endif + +/* + Decode literal, length, and distance codes and write out the resulting + literal and match bytes until either not enough input or output is + available, an end-of-block is encountered, or a data error is encountered. + When large enough input and output buffers are supplied to inflate(), for + example, a 16K input buffer and a 64K output buffer, more than 95% of the + inflate execution time is spent in this routine. + + Entry assumptions: + + state->mode == LEN + strm->avail_in >= 6 + strm->avail_out >= 258 + start >= strm->avail_out + state->bits < 8 + + On return, state->mode is one of: + + LEN -- ran out of enough output space or enough available input + TYPE -- reached end of block code, inflate() to interpret next block + BAD -- error in block data + + Notes: + + - The maximum input bits used by a length/distance pair is 15 bits for the + length code, 5 bits for the length extra, 15 bits for the distance code, + and 13 bits for the distance extra. This totals 48 bits, or six bytes. + Therefore if strm->avail_in >= 6, then there is enough input to avoid + checking for available input while decoding. + + - The maximum bytes that a single length/distance pair can output is 258 + bytes, which is the maximum length that can be coded. inflate_fast() + requires strm->avail_out >= 258 for each loop to avoid checking for + output space. + */ +void inflate_fast(strm, start) +z_streamp strm; +unsigned start; /* inflate()'s starting value for strm->avail_out */ +{ + struct inflate_state FAR *state; + unsigned char FAR *in; /* local strm->next_in */ + unsigned char FAR *last; /* while in < last, enough input available */ + unsigned char FAR *out; /* local strm->next_out */ + unsigned char FAR *beg; /* inflate()'s initial strm->next_out */ + unsigned char FAR *end; /* while out < end, enough space available */ +#ifdef INFLATE_STRICT + unsigned dmax; /* maximum distance from zlib header */ +#endif + unsigned wsize; /* window size or zero if not using window */ + unsigned whave; /* valid bytes in the window */ + unsigned write; /* window write index */ + unsigned char FAR *window; /* allocated sliding window, if wsize != 0 */ + unsigned long hold; /* local strm->hold */ + unsigned bits; /* local strm->bits */ + code const FAR *lcode; /* local strm->lencode */ + code const FAR *dcode; /* local strm->distcode */ + unsigned lmask; /* mask for first level of length codes */ + unsigned dmask; /* mask for first level of distance codes */ + code this; /* retrieved table entry */ + unsigned op; /* code bits, operation, extra bits, or */ + /* window position, window bytes to copy */ + unsigned len; /* match length, unused bytes */ + unsigned dist; /* match distance */ + unsigned char FAR *from; /* where to copy match from */ + + /* copy state to local variables */ + state = (struct inflate_state FAR *)strm->state; + in = strm->next_in - OFF; + last = in + (strm->avail_in - 5); + out = strm->next_out - OFF; + beg = out - (start - strm->avail_out); + end = out + (strm->avail_out - 257); +#ifdef INFLATE_STRICT + dmax = state->dmax; +#endif + wsize = state->wsize; + whave = state->whave; + write = state->write; + window = state->window; + hold = state->hold; + bits = state->bits; + lcode = state->lencode; + dcode = state->distcode; + lmask = (1U << state->lenbits) - 1; + dmask = (1U << state->distbits) - 1; + + /* decode literals and length/distances until end-of-block or not enough + input data or output space */ + do { + if (bits < 15) { + hold += (unsigned long)(PUP(in)) << bits; + bits += 8; + hold += (unsigned long)(PUP(in)) << bits; + bits += 8; + } + this = lcode[hold & lmask]; + dolen: + op = (unsigned)(this.bits); + hold >>= op; + bits -= op; + op = (unsigned)(this.op); + if (op == 0) { /* literal */ + Tracevv((stderr, this.val >= 0x20 && this.val < 0x7f ? + "inflate: literal '%c'\n" : + "inflate: literal 0x%02x\n", this.val)); + PUP(out) = (unsigned char)(this.val); + } + else if (op & 16) { /* length base */ + len = (unsigned)(this.val); + op &= 15; /* number of extra bits */ + if (op) { + if (bits < op) { + hold += (unsigned long)(PUP(in)) << bits; + bits += 8; + } + len += (unsigned)hold & ((1U << op) - 1); + hold >>= op; + bits -= op; + } + Tracevv((stderr, "inflate: length %u\n", len)); + if (bits < 15) { + hold += (unsigned long)(PUP(in)) << bits; + bits += 8; + hold += (unsigned long)(PUP(in)) << bits; + bits += 8; + } + this = dcode[hold & dmask]; + dodist: + op = (unsigned)(this.bits); + hold >>= op; + bits -= op; + op = (unsigned)(this.op); + if (op & 16) { /* distance base */ + dist = (unsigned)(this.val); + op &= 15; /* number of extra bits */ + if (bits < op) { + hold += (unsigned long)(PUP(in)) << bits; + bits += 8; + if (bits < op) { + hold += (unsigned long)(PUP(in)) << bits; + bits += 8; + } + } + dist += (unsigned)hold & ((1U << op) - 1); +#ifdef INFLATE_STRICT + if (dist > dmax) { + strm->msg = (char *)"invalid distance too far back"; + state->mode = BAD; + break; + } +#endif + hold >>= op; + bits -= op; + Tracevv((stderr, "inflate: distance %u\n", dist)); + op = (unsigned)(out - beg); /* max distance in output */ + if (dist > op) { /* see if copy from window */ + op = dist - op; /* distance back in window */ + if (op > whave) { + strm->msg = (char *)"invalid distance too far back"; + state->mode = BAD; + break; + } + from = window - OFF; + if (write == 0) { /* very common case */ + from += wsize - op; + if (op < len) { /* some from window */ + len -= op; + do { + PUP(out) = PUP(from); + } while (--op); + from = out - dist; /* rest from output */ + } + } + else if (write < op) { /* wrap around window */ + from += wsize + write - op; + op -= write; + if (op < len) { /* some from end of window */ + len -= op; + do { + PUP(out) = PUP(from); + } while (--op); + from = window - OFF; + if (write < len) { /* some from start of window */ + op = write; + len -= op; + do { + PUP(out) = PUP(from); + } while (--op); + from = out - dist; /* rest from output */ + } + } + } + else { /* contiguous in window */ + from += write - op; + if (op < len) { /* some from window */ + len -= op; + do { + PUP(out) = PUP(from); + } while (--op); + from = out - dist; /* rest from output */ + } + } + while (len > 2) { + PUP(out) = PUP(from); + PUP(out) = PUP(from); + PUP(out) = PUP(from); + len -= 3; + } + if (len) { + PUP(out) = PUP(from); + if (len > 1) + PUP(out) = PUP(from); + } + } + else { + from = out - dist; /* copy direct from output */ + do { /* minimum length is three */ + PUP(out) = PUP(from); + PUP(out) = PUP(from); + PUP(out) = PUP(from); + len -= 3; + } while (len > 2); + if (len) { + PUP(out) = PUP(from); + if (len > 1) + PUP(out) = PUP(from); + } + } + } + else if ((op & 64) == 0) { /* 2nd level distance code */ + this = dcode[this.val + (hold & ((1U << op) - 1))]; + goto dodist; + } + else { + strm->msg = (char *)"invalid distance code"; + state->mode = BAD; + break; + } + } + else if ((op & 64) == 0) { /* 2nd level length code */ + this = lcode[this.val + (hold & ((1U << op) - 1))]; + goto dolen; + } + else if (op & 32) { /* end-of-block */ + Tracevv((stderr, "inflate: end of block\n")); + state->mode = TYPE; + break; + } + else { + strm->msg = (char *)"invalid literal/length code"; + state->mode = BAD; + break; + } + } while (in < last && out < end); + + /* return unused bytes (on entry, bits < 8, so in won't go too far back) */ + len = bits >> 3; + in -= len; + bits -= len << 3; + hold &= (1U << bits) - 1; + + /* update state and return */ + strm->next_in = in + OFF; + strm->next_out = out + OFF; + strm->avail_in = (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last)); + strm->avail_out = (unsigned)(out < end ? + 257 + (end - out) : 257 - (out - end)); + state->hold = hold; + state->bits = bits; + return; +} + +/* + inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe): + - Using bit fields for code structure + - Different op definition to avoid & for extra bits (do & for table bits) + - Three separate decoding do-loops for direct, window, and write == 0 + - Special case for distance > 1 copies to do overlapped load and store copy + - Explicit branch predictions (based on measured branch probabilities) + - Deferring match copy and interspersed it with decoding subsequent codes + - Swapping literal/length else + - Swapping window/direct else + - Larger unrolled copy loops (three is about right) + - Moving len -= 3 statement into middle of loop + */ + +#endif /* !ASMINF */ diff --git a/Foundation/src/inffast.h b/Foundation/src/inffast.h index 614fa7877..1e88d2d97 100644 --- a/Foundation/src/inffast.h +++ b/Foundation/src/inffast.h @@ -1,11 +1,11 @@ -/* inffast.h -- header to use inffast.c - * Copyright (C) 1995-2003 Mark Adler - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -/* WARNING: this file should *not* be used by applications. It is - part of the implementation of the compression library and is - subject to change. Applications should only use zlib.h. - */ - -void inflate_fast OF((z_streamp strm, unsigned start)); +/* inffast.h -- header to use inffast.c + * Copyright (C) 1995-2003 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* WARNING: this file should *not* be used by applications. It is + part of the implementation of the compression library and is + subject to change. Applications should only use zlib.h. + */ + +void inflate_fast OF((z_streamp strm, unsigned start)); diff --git a/Foundation/src/inffixed.h b/Foundation/src/inffixed.h index 423d5c5b5..75ed4b597 100644 --- a/Foundation/src/inffixed.h +++ b/Foundation/src/inffixed.h @@ -1,94 +1,94 @@ - /* inffixed.h -- table for decoding fixed codes - * Generated automatically by makefixed(). - */ - - /* WARNING: this file should *not* be used by applications. It - is part of the implementation of the compression library and - is subject to change. Applications should only use zlib.h. - */ - - static const code lenfix[512] = { - {96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48}, - {0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128}, - {0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59}, - {0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176}, - {0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20}, - {21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100}, - {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8}, - {0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216}, - {18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76}, - {0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114}, - {0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2}, - {0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148}, - {20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42}, - {0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86}, - {0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15}, - {0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236}, - {16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62}, - {0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142}, - {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31}, - {0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162}, - {0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25}, - {0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105}, - {0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4}, - {0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202}, - {17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69}, - {0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125}, - {0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13}, - {0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195}, - {19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35}, - {0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91}, - {0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19}, - {0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246}, - {16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55}, - {0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135}, - {0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99}, - {0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190}, - {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16}, - {20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96}, - {0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6}, - {0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209}, - {17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72}, - {0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116}, - {0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4}, - {0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153}, - {20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44}, - {0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82}, - {0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11}, - {0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229}, - {16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58}, - {0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138}, - {0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51}, - {0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173}, - {0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30}, - {0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110}, - {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0}, - {0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195}, - {16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65}, - {0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121}, - {0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9}, - {0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258}, - {19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37}, - {0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93}, - {0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23}, - {0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251}, - {16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51}, - {0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131}, - {0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67}, - {0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183}, - {0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23}, - {64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103}, - {0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9}, - {0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223}, - {18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79}, - {0,9,255} - }; - - static const code distfix[32] = { - {16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025}, - {21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193}, - {18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385}, - {19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577}, - {16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073}, - {22,5,193},{64,5,0} - }; + /* inffixed.h -- table for decoding fixed codes + * Generated automatically by makefixed(). + */ + + /* WARNING: this file should *not* be used by applications. It + is part of the implementation of the compression library and + is subject to change. Applications should only use zlib.h. + */ + + static const code lenfix[512] = { + {96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48}, + {0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128}, + {0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59}, + {0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176}, + {0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20}, + {21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100}, + {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8}, + {0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216}, + {18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76}, + {0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114}, + {0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2}, + {0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148}, + {20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42}, + {0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86}, + {0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15}, + {0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236}, + {16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62}, + {0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142}, + {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31}, + {0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162}, + {0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25}, + {0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105}, + {0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4}, + {0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202}, + {17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69}, + {0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125}, + {0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13}, + {0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195}, + {19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35}, + {0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91}, + {0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19}, + {0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246}, + {16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55}, + {0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135}, + {0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99}, + {0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190}, + {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16}, + {20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96}, + {0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6}, + {0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209}, + {17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72}, + {0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116}, + {0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4}, + {0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153}, + {20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44}, + {0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82}, + {0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11}, + {0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229}, + {16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58}, + {0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138}, + {0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51}, + {0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173}, + {0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30}, + {0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110}, + {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0}, + {0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195}, + {16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65}, + {0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121}, + {0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9}, + {0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258}, + {19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37}, + {0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93}, + {0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23}, + {0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251}, + {16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51}, + {0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131}, + {0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67}, + {0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183}, + {0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23}, + {64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103}, + {0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9}, + {0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223}, + {18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79}, + {0,9,255} + }; + + static const code distfix[32] = { + {16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025}, + {21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193}, + {18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385}, + {19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577}, + {16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073}, + {22,5,193},{64,5,0} + }; diff --git a/Foundation/src/inflate.c b/Foundation/src/inflate.c index 33ea90292..792fdee8e 100644 --- a/Foundation/src/inflate.c +++ b/Foundation/src/inflate.c @@ -1,1368 +1,1368 @@ -/* inflate.c -- zlib decompression - * Copyright (C) 1995-2005 Mark Adler - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -/* - * Change history: - * - * 1.2.beta0 24 Nov 2002 - * - First version -- complete rewrite of inflate to simplify code, avoid - * creation of window when not needed, minimize use of window when it is - * needed, make inffast.c even faster, implement gzip decoding, and to - * improve code readability and style over the previous zlib inflate code - * - * 1.2.beta1 25 Nov 2002 - * - Use pointers for available input and output checking in inffast.c - * - Remove input and output counters in inffast.c - * - Change inffast.c entry and loop from avail_in >= 7 to >= 6 - * - Remove unnecessary second byte pull from length extra in inffast.c - * - Unroll direct copy to three copies per loop in inffast.c - * - * 1.2.beta2 4 Dec 2002 - * - Change external routine names to reduce potential conflicts - * - Correct filename to inffixed.h for fixed tables in inflate.c - * - Make hbuf[] unsigned char to match parameter type in inflate.c - * - Change strm->next_out[-state->offset] to *(strm->next_out - state->offset) - * to avoid negation problem on Alphas (64 bit) in inflate.c - * - * 1.2.beta3 22 Dec 2002 - * - Add comments on state->bits assertion in inffast.c - * - Add comments on op field in inftrees.h - * - Fix bug in reuse of allocated window after inflateReset() - * - Remove bit fields--back to byte structure for speed - * - Remove distance extra == 0 check in inflate_fast()--only helps for lengths - * - Change post-increments to pre-increments in inflate_fast(), PPC biased? - * - Add compile time option, POSTINC, to use post-increments instead (Intel?) - * - Make MATCH copy in inflate() much faster for when inflate_fast() not used - * - Use local copies of stream next and avail values, as well as local bit - * buffer and bit count in inflate()--for speed when inflate_fast() not used - * - * 1.2.beta4 1 Jan 2003 - * - Split ptr - 257 statements in inflate_table() to avoid compiler warnings - * - Move a comment on output buffer sizes from inffast.c to inflate.c - * - Add comments in inffast.c to introduce the inflate_fast() routine - * - Rearrange window copies in inflate_fast() for speed and simplification - * - Unroll last copy for window match in inflate_fast() - * - Use local copies of window variables in inflate_fast() for speed - * - Pull out common write == 0 case for speed in inflate_fast() - * - Make op and len in inflate_fast() unsigned for consistency - * - Add FAR to lcode and dcode declarations in inflate_fast() - * - Simplified bad distance check in inflate_fast() - * - Added inflateBackInit(), inflateBack(), and inflateBackEnd() in new - * source file infback.c to provide a call-back interface to inflate for - * programs like gzip and unzip -- uses window as output buffer to avoid - * window copying - * - * 1.2.beta5 1 Jan 2003 - * - Improved inflateBack() interface to allow the caller to provide initial - * input in strm. - * - Fixed stored blocks bug in inflateBack() - * - * 1.2.beta6 4 Jan 2003 - * - Added comments in inffast.c on effectiveness of POSTINC - * - Typecasting all around to reduce compiler warnings - * - Changed loops from while (1) or do {} while (1) to for (;;), again to - * make compilers happy - * - Changed type of window in inflateBackInit() to unsigned char * - * - * 1.2.beta7 27 Jan 2003 - * - Changed many types to unsigned or unsigned short to avoid warnings - * - Added inflateCopy() function - * - * 1.2.0 9 Mar 2003 - * - Changed inflateBack() interface to provide separate opaque descriptors - * for the in() and out() functions - * - Changed inflateBack() argument and in_func typedef to swap the length - * and buffer address return values for the input function - * - Check next_in and next_out for Z_NULL on entry to inflate() - * - * The history for versions after 1.2.0 are in ChangeLog in zlib distribution. - */ - -#include "zutil.h" -#include "inftrees.h" -#include "inflate.h" -#include "inffast.h" - -#ifdef MAKEFIXED -# ifndef BUILDFIXED -# define BUILDFIXED -# endif -#endif - -/* function prototypes */ -local void fixedtables OF((struct inflate_state FAR *state)); -local int updatewindow OF((z_streamp strm, unsigned out)); -#ifdef BUILDFIXED - void makefixed OF((void)); -#endif -local unsigned syncsearch OF((unsigned FAR *have, unsigned char FAR *buf, - unsigned len)); - -int ZEXPORT inflateReset(strm) -z_streamp strm; -{ - struct inflate_state FAR *state; - - if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; - state = (struct inflate_state FAR *)strm->state; - strm->total_in = strm->total_out = state->total = 0; - strm->msg = Z_NULL; - strm->adler = 1; /* to support ill-conceived Java test suite */ - state->mode = HEAD; - state->last = 0; - state->havedict = 0; - state->dmax = 32768U; - state->head = Z_NULL; - state->wsize = 0; - state->whave = 0; - state->write = 0; - state->hold = 0; - state->bits = 0; - state->lencode = state->distcode = state->next = state->codes; - Tracev((stderr, "inflate: reset\n")); - return Z_OK; -} - -int ZEXPORT inflatePrime(strm, bits, value) -z_streamp strm; -int bits; -int value; -{ - struct inflate_state FAR *state; - - if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; - state = (struct inflate_state FAR *)strm->state; - if (bits > 16 || state->bits + bits > 32) return Z_STREAM_ERROR; - value &= (1L << bits) - 1; - state->hold += value << state->bits; - state->bits += bits; - return Z_OK; -} - -int ZEXPORT inflateInit2_(strm, windowBits, version, stream_size) -z_streamp strm; -int windowBits; -const char *version; -int stream_size; -{ - struct inflate_state FAR *state; - - if (version == Z_NULL || version[0] != ZLIB_VERSION[0] || - stream_size != (int)(sizeof(z_stream))) - return Z_VERSION_ERROR; - if (strm == Z_NULL) return Z_STREAM_ERROR; - strm->msg = Z_NULL; /* in case we return an error */ - if (strm->zalloc == (alloc_func)0) { - strm->zalloc = zcalloc; - strm->opaque = (voidpf)0; - } - if (strm->zfree == (free_func)0) strm->zfree = zcfree; - state = (struct inflate_state FAR *) - ZALLOC(strm, 1, sizeof(struct inflate_state)); - if (state == Z_NULL) return Z_MEM_ERROR; - Tracev((stderr, "inflate: allocated\n")); - strm->state = (struct internal_state FAR *)state; - if (windowBits < 0) { - state->wrap = 0; - windowBits = -windowBits; - } - else { - state->wrap = (windowBits >> 4) + 1; -#ifdef GUNZIP - if (windowBits < 48) windowBits &= 15; -#endif - } - if (windowBits < 8 || windowBits > 15) { - ZFREE(strm, state); - strm->state = Z_NULL; - return Z_STREAM_ERROR; - } - state->wbits = (unsigned)windowBits; - state->window = Z_NULL; - return inflateReset(strm); -} - -int ZEXPORT inflateInit_(strm, version, stream_size) -z_streamp strm; -const char *version; -int stream_size; -{ - return inflateInit2_(strm, DEF_WBITS, version, stream_size); -} - -/* - Return state with length and distance decoding tables and index sizes set to - fixed code decoding. Normally this returns fixed tables from inffixed.h. - If BUILDFIXED is defined, then instead this routine builds the tables the - first time it's called, and returns those tables the first time and - thereafter. This reduces the size of the code by about 2K bytes, in - exchange for a little execution time. However, BUILDFIXED should not be - used for threaded applications, since the rewriting of the tables and virgin - may not be thread-safe. - */ -local void fixedtables(state) -struct inflate_state FAR *state; -{ -#ifdef BUILDFIXED - static int virgin = 1; - static code *lenfix, *distfix; - static code fixed[544]; - - /* build fixed huffman tables if first call (may not be thread safe) */ - if (virgin) { - unsigned sym, bits; - static code *next; - - /* literal/length table */ - sym = 0; - while (sym < 144) state->lens[sym++] = 8; - while (sym < 256) state->lens[sym++] = 9; - while (sym < 280) state->lens[sym++] = 7; - while (sym < 288) state->lens[sym++] = 8; - next = fixed; - lenfix = next; - bits = 9; - inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work); - - /* distance table */ - sym = 0; - while (sym < 32) state->lens[sym++] = 5; - distfix = next; - bits = 5; - inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work); - - /* do this just once */ - virgin = 0; - } -#else /* !BUILDFIXED */ -# include "inffixed.h" -#endif /* BUILDFIXED */ - state->lencode = lenfix; - state->lenbits = 9; - state->distcode = distfix; - state->distbits = 5; -} - -#ifdef MAKEFIXED -#include - -/* - Write out the inffixed.h that is #include'd above. Defining MAKEFIXED also - defines BUILDFIXED, so the tables are built on the fly. makefixed() writes - those tables to stdout, which would be piped to inffixed.h. A small program - can simply call makefixed to do this: - - void makefixed(void); - - int main(void) - { - makefixed(); - return 0; - } - - Then that can be linked with zlib built with MAKEFIXED defined and run: - - a.out > inffixed.h - */ -void makefixed() -{ - unsigned low, size; - struct inflate_state state; - - fixedtables(&state); - puts(" /* inffixed.h -- table for decoding fixed codes"); - puts(" * Generated automatically by makefixed()."); - puts(" */"); - puts(""); - puts(" /* WARNING: this file should *not* be used by applications."); - puts(" It is part of the implementation of this library and is"); - puts(" subject to change. Applications should only use zlib.h."); - puts(" */"); - puts(""); - size = 1U << 9; - printf(" static const code lenfix[%u] = {", size); - low = 0; - for (;;) { - if ((low % 7) == 0) printf("\n "); - printf("{%u,%u,%d}", state.lencode[low].op, state.lencode[low].bits, - state.lencode[low].val); - if (++low == size) break; - putchar(','); - } - puts("\n };"); - size = 1U << 5; - printf("\n static const code distfix[%u] = {", size); - low = 0; - for (;;) { - if ((low % 6) == 0) printf("\n "); - printf("{%u,%u,%d}", state.distcode[low].op, state.distcode[low].bits, - state.distcode[low].val); - if (++low == size) break; - putchar(','); - } - puts("\n };"); -} -#endif /* MAKEFIXED */ - -/* - Update the window with the last wsize (normally 32K) bytes written before - returning. If window does not exist yet, create it. This is only called - when a window is already in use, or when output has been written during this - inflate call, but the end of the deflate stream has not been reached yet. - It is also called to create a window for dictionary data when a dictionary - is loaded. - - Providing output buffers larger than 32K to inflate() should provide a speed - advantage, since only the last 32K of output is copied to the sliding window - upon return from inflate(), and since all distances after the first 32K of - output will fall in the output data, making match copies simpler and faster. - The advantage may be dependent on the size of the processor's data caches. - */ -local int updatewindow(strm, out) -z_streamp strm; -unsigned out; -{ - struct inflate_state FAR *state; - unsigned copy, dist; - - state = (struct inflate_state FAR *)strm->state; - - /* if it hasn't been done already, allocate space for the window */ - if (state->window == Z_NULL) { - state->window = (unsigned char FAR *) - ZALLOC(strm, 1U << state->wbits, - sizeof(unsigned char)); - if (state->window == Z_NULL) return 1; - } - - /* if window not in use yet, initialize */ - if (state->wsize == 0) { - state->wsize = 1U << state->wbits; - state->write = 0; - state->whave = 0; - } - - /* copy state->wsize or less output bytes into the circular window */ - copy = out - strm->avail_out; - if (copy >= state->wsize) { - zmemcpy(state->window, strm->next_out - state->wsize, state->wsize); - state->write = 0; - state->whave = state->wsize; - } - else { - dist = state->wsize - state->write; - if (dist > copy) dist = copy; - zmemcpy(state->window + state->write, strm->next_out - copy, dist); - copy -= dist; - if (copy) { - zmemcpy(state->window, strm->next_out - copy, copy); - state->write = copy; - state->whave = state->wsize; - } - else { - state->write += dist; - if (state->write == state->wsize) state->write = 0; - if (state->whave < state->wsize) state->whave += dist; - } - } - return 0; -} - -/* Macros for inflate(): */ - -/* check function to use adler32() for zlib or crc32() for gzip */ -#ifdef GUNZIP -# define UPDATE(check, buf, len) \ - (state->flags ? crc32(check, buf, len) : adler32(check, buf, len)) -#else -# define UPDATE(check, buf, len) adler32(check, buf, len) -#endif - -/* check macros for header crc */ -#ifdef GUNZIP -# define CRC2(check, word) \ - do { \ - hbuf[0] = (unsigned char)(word); \ - hbuf[1] = (unsigned char)((word) >> 8); \ - check = crc32(check, hbuf, 2); \ - } while (0) - -# define CRC4(check, word) \ - do { \ - hbuf[0] = (unsigned char)(word); \ - hbuf[1] = (unsigned char)((word) >> 8); \ - hbuf[2] = (unsigned char)((word) >> 16); \ - hbuf[3] = (unsigned char)((word) >> 24); \ - check = crc32(check, hbuf, 4); \ - } while (0) -#endif - -/* Load registers with state in inflate() for speed */ -#define LOAD() \ - do { \ - put = strm->next_out; \ - left = strm->avail_out; \ - next = strm->next_in; \ - have = strm->avail_in; \ - hold = state->hold; \ - bits = state->bits; \ - } while (0) - -/* Restore state from registers in inflate() */ -#define RESTORE() \ - do { \ - strm->next_out = put; \ - strm->avail_out = left; \ - strm->next_in = next; \ - strm->avail_in = have; \ - state->hold = hold; \ - state->bits = bits; \ - } while (0) - -/* Clear the input bit accumulator */ -#define INITBITS() \ - do { \ - hold = 0; \ - bits = 0; \ - } while (0) - -/* Get a byte of input into the bit accumulator, or return from inflate() - if there is no input available. */ -#define PULLBYTE() \ - do { \ - if (have == 0) goto inf_leave; \ - have--; \ - hold += (unsigned long)(*next++) << bits; \ - bits += 8; \ - } while (0) - -/* Assure that there are at least n bits in the bit accumulator. If there is - not enough available input to do that, then return from inflate(). */ -#define NEEDBITS(n) \ - do { \ - while (bits < (unsigned)(n)) \ - PULLBYTE(); \ - } while (0) - -/* Return the low n bits of the bit accumulator (n < 16) */ -#define BITS(n) \ - ((unsigned)hold & ((1U << (n)) - 1)) - -/* Remove n bits from the bit accumulator */ -#define DROPBITS(n) \ - do { \ - hold >>= (n); \ - bits -= (unsigned)(n); \ - } while (0) - -/* Remove zero to seven bits as needed to go to a byte boundary */ -#define BYTEBITS() \ - do { \ - hold >>= bits & 7; \ - bits -= bits & 7; \ - } while (0) - -/* Reverse the bytes in a 32-bit value */ -#define REVERSE(q) \ - ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \ - (((q) & 0xff00) << 8) + (((q) & 0xff) << 24)) - -/* - inflate() uses a state machine to process as much input data and generate as - much output data as possible before returning. The state machine is - structured roughly as follows: - - for (;;) switch (state) { - ... - case STATEn: - if (not enough input data or output space to make progress) - return; - ... make progress ... - state = STATEm; - break; - ... - } - - so when inflate() is called again, the same case is attempted again, and - if the appropriate resources are provided, the machine proceeds to the - next state. The NEEDBITS() macro is usually the way the state evaluates - whether it can proceed or should return. NEEDBITS() does the return if - the requested bits are not available. The typical use of the BITS macros - is: - - NEEDBITS(n); - ... do something with BITS(n) ... - DROPBITS(n); - - where NEEDBITS(n) either returns from inflate() if there isn't enough - input left to load n bits into the accumulator, or it continues. BITS(n) - gives the low n bits in the accumulator. When done, DROPBITS(n) drops - the low n bits off the accumulator. INITBITS() clears the accumulator - and sets the number of available bits to zero. BYTEBITS() discards just - enough bits to put the accumulator on a byte boundary. After BYTEBITS() - and a NEEDBITS(8), then BITS(8) would return the next byte in the stream. - - NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return - if there is no input available. The decoding of variable length codes uses - PULLBYTE() directly in order to pull just enough bytes to decode the next - code, and no more. - - Some states loop until they get enough input, making sure that enough - state information is maintained to continue the loop where it left off - if NEEDBITS() returns in the loop. For example, want, need, and keep - would all have to actually be part of the saved state in case NEEDBITS() - returns: - - case STATEw: - while (want < need) { - NEEDBITS(n); - keep[want++] = BITS(n); - DROPBITS(n); - } - state = STATEx; - case STATEx: - - As shown above, if the next state is also the next case, then the break - is omitted. - - A state may also return if there is not enough output space available to - complete that state. Those states are copying stored data, writing a - literal byte, and copying a matching string. - - When returning, a "goto inf_leave" is used to update the total counters, - update the check value, and determine whether any progress has been made - during that inflate() call in order to return the proper return code. - Progress is defined as a change in either strm->avail_in or strm->avail_out. - When there is a window, goto inf_leave will update the window with the last - output written. If a goto inf_leave occurs in the middle of decompression - and there is no window currently, goto inf_leave will create one and copy - output to the window for the next call of inflate(). - - In this implementation, the flush parameter of inflate() only affects the - return code (per zlib.h). inflate() always writes as much as possible to - strm->next_out, given the space available and the provided input--the effect - documented in zlib.h of Z_SYNC_FLUSH. Furthermore, inflate() always defers - the allocation of and copying into a sliding window until necessary, which - provides the effect documented in zlib.h for Z_FINISH when the entire input - stream available. So the only thing the flush parameter actually does is: - when flush is set to Z_FINISH, inflate() cannot return Z_OK. Instead it - will return Z_BUF_ERROR if it has not reached the end of the stream. - */ - -int ZEXPORT inflate(strm, flush) -z_streamp strm; -int flush; -{ - struct inflate_state FAR *state; - unsigned char FAR *next; /* next input */ - unsigned char FAR *put; /* next output */ - unsigned have, left; /* available input and output */ - unsigned long hold; /* bit buffer */ - unsigned bits; /* bits in bit buffer */ - unsigned in, out; /* save starting available input and output */ - unsigned copy; /* number of stored or match bytes to copy */ - unsigned char FAR *from; /* where to copy match bytes from */ - code this; /* current decoding table entry */ - code last; /* parent table entry */ - unsigned len; /* length to copy for repeats, bits to drop */ - int ret; /* return code */ -#ifdef GUNZIP - unsigned char hbuf[4]; /* buffer for gzip header crc calculation */ -#endif - static const unsigned short order[19] = /* permutation of code lengths */ - {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; - - if (strm == Z_NULL || strm->state == Z_NULL || strm->next_out == Z_NULL || - (strm->next_in == Z_NULL && strm->avail_in != 0)) - return Z_STREAM_ERROR; - - state = (struct inflate_state FAR *)strm->state; - if (state->mode == TYPE) state->mode = TYPEDO; /* skip check */ - LOAD(); - in = have; - out = left; - ret = Z_OK; - for (;;) - switch (state->mode) { - case HEAD: - if (state->wrap == 0) { - state->mode = TYPEDO; - break; - } - NEEDBITS(16); -#ifdef GUNZIP - if ((state->wrap & 2) && hold == 0x8b1f) { /* gzip header */ - state->check = crc32(0L, Z_NULL, 0); - CRC2(state->check, hold); - INITBITS(); - state->mode = FLAGS; - break; - } - state->flags = 0; /* expect zlib header */ - if (state->head != Z_NULL) - state->head->done = -1; - if (!(state->wrap & 1) || /* check if zlib header allowed */ -#else - if ( -#endif - ((BITS(8) << 8) + (hold >> 8)) % 31) { - strm->msg = (char *)"incorrect header check"; - state->mode = BAD; - break; - } - if (BITS(4) != Z_DEFLATED) { - strm->msg = (char *)"unknown compression method"; - state->mode = BAD; - break; - } - DROPBITS(4); - len = BITS(4) + 8; - if (len > state->wbits) { - strm->msg = (char *)"invalid window size"; - state->mode = BAD; - break; - } - state->dmax = 1U << len; - Tracev((stderr, "inflate: zlib header ok\n")); - strm->adler = state->check = adler32(0L, Z_NULL, 0); - state->mode = hold & 0x200 ? DICTID : TYPE; - INITBITS(); - break; -#ifdef GUNZIP - case FLAGS: - NEEDBITS(16); - state->flags = (int)(hold); - if ((state->flags & 0xff) != Z_DEFLATED) { - strm->msg = (char *)"unknown compression method"; - state->mode = BAD; - break; - } - if (state->flags & 0xe000) { - strm->msg = (char *)"unknown header flags set"; - state->mode = BAD; - break; - } - if (state->head != Z_NULL) - state->head->text = (int)((hold >> 8) & 1); - if (state->flags & 0x0200) CRC2(state->check, hold); - INITBITS(); - state->mode = TIME; - case TIME: - NEEDBITS(32); - if (state->head != Z_NULL) - state->head->time = hold; - if (state->flags & 0x0200) CRC4(state->check, hold); - INITBITS(); - state->mode = OS; - case OS: - NEEDBITS(16); - if (state->head != Z_NULL) { - state->head->xflags = (int)(hold & 0xff); - state->head->os = (int)(hold >> 8); - } - if (state->flags & 0x0200) CRC2(state->check, hold); - INITBITS(); - state->mode = EXLEN; - case EXLEN: - if (state->flags & 0x0400) { - NEEDBITS(16); - state->length = (unsigned)(hold); - if (state->head != Z_NULL) - state->head->extra_len = (unsigned)hold; - if (state->flags & 0x0200) CRC2(state->check, hold); - INITBITS(); - } - else if (state->head != Z_NULL) - state->head->extra = Z_NULL; - state->mode = EXTRA; - case EXTRA: - if (state->flags & 0x0400) { - copy = state->length; - if (copy > have) copy = have; - if (copy) { - if (state->head != Z_NULL && - state->head->extra != Z_NULL) { - len = state->head->extra_len - state->length; - zmemcpy(state->head->extra + len, next, - len + copy > state->head->extra_max ? - state->head->extra_max - len : copy); - } - if (state->flags & 0x0200) - state->check = crc32(state->check, next, copy); - have -= copy; - next += copy; - state->length -= copy; - } - if (state->length) goto inf_leave; - } - state->length = 0; - state->mode = NAME; - case NAME: - if (state->flags & 0x0800) { - if (have == 0) goto inf_leave; - copy = 0; - do { - len = (unsigned)(next[copy++]); - if (state->head != Z_NULL && - state->head->name != Z_NULL && - state->length < state->head->name_max) - state->head->name[state->length++] = len; - } while (len && copy < have); - if (state->flags & 0x0200) - state->check = crc32(state->check, next, copy); - have -= copy; - next += copy; - if (len) goto inf_leave; - } - else if (state->head != Z_NULL) - state->head->name = Z_NULL; - state->length = 0; - state->mode = COMMENT; - case COMMENT: - if (state->flags & 0x1000) { - if (have == 0) goto inf_leave; - copy = 0; - do { - len = (unsigned)(next[copy++]); - if (state->head != Z_NULL && - state->head->comment != Z_NULL && - state->length < state->head->comm_max) - state->head->comment[state->length++] = len; - } while (len && copy < have); - if (state->flags & 0x0200) - state->check = crc32(state->check, next, copy); - have -= copy; - next += copy; - if (len) goto inf_leave; - } - else if (state->head != Z_NULL) - state->head->comment = Z_NULL; - state->mode = HCRC; - case HCRC: - if (state->flags & 0x0200) { - NEEDBITS(16); - if (hold != (state->check & 0xffff)) { - strm->msg = (char *)"header crc mismatch"; - state->mode = BAD; - break; - } - INITBITS(); - } - if (state->head != Z_NULL) { - state->head->hcrc = (int)((state->flags >> 9) & 1); - state->head->done = 1; - } - strm->adler = state->check = crc32(0L, Z_NULL, 0); - state->mode = TYPE; - break; -#endif - case DICTID: - NEEDBITS(32); - strm->adler = state->check = REVERSE(hold); - INITBITS(); - state->mode = DICT; - case DICT: - if (state->havedict == 0) { - RESTORE(); - return Z_NEED_DICT; - } - strm->adler = state->check = adler32(0L, Z_NULL, 0); - state->mode = TYPE; - case TYPE: - if (flush == Z_BLOCK) goto inf_leave; - case TYPEDO: - if (state->last) { - BYTEBITS(); - state->mode = CHECK; - break; - } - NEEDBITS(3); - state->last = BITS(1); - DROPBITS(1); - switch (BITS(2)) { - case 0: /* stored block */ - Tracev((stderr, "inflate: stored block%s\n", - state->last ? " (last)" : "")); - state->mode = STORED; - break; - case 1: /* fixed block */ - fixedtables(state); - Tracev((stderr, "inflate: fixed codes block%s\n", - state->last ? " (last)" : "")); - state->mode = LEN; /* decode codes */ - break; - case 2: /* dynamic block */ - Tracev((stderr, "inflate: dynamic codes block%s\n", - state->last ? " (last)" : "")); - state->mode = TABLE; - break; - case 3: - strm->msg = (char *)"invalid block type"; - state->mode = BAD; - } - DROPBITS(2); - break; - case STORED: - BYTEBITS(); /* go to byte boundary */ - NEEDBITS(32); - if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) { - strm->msg = (char *)"invalid stored block lengths"; - state->mode = BAD; - break; - } - state->length = (unsigned)hold & 0xffff; - Tracev((stderr, "inflate: stored length %u\n", - state->length)); - INITBITS(); - state->mode = COPY; - case COPY: - copy = state->length; - if (copy) { - if (copy > have) copy = have; - if (copy > left) copy = left; - if (copy == 0) goto inf_leave; - zmemcpy(put, next, copy); - have -= copy; - next += copy; - left -= copy; - put += copy; - state->length -= copy; - break; - } - Tracev((stderr, "inflate: stored end\n")); - state->mode = TYPE; - break; - case TABLE: - NEEDBITS(14); - state->nlen = BITS(5) + 257; - DROPBITS(5); - state->ndist = BITS(5) + 1; - DROPBITS(5); - state->ncode = BITS(4) + 4; - DROPBITS(4); -#ifndef PKZIP_BUG_WORKAROUND - if (state->nlen > 286 || state->ndist > 30) { - strm->msg = (char *)"too many length or distance symbols"; - state->mode = BAD; - break; - } -#endif - Tracev((stderr, "inflate: table sizes ok\n")); - state->have = 0; - state->mode = LENLENS; - case LENLENS: - while (state->have < state->ncode) { - NEEDBITS(3); - state->lens[order[state->have++]] = (unsigned short)BITS(3); - DROPBITS(3); - } - while (state->have < 19) - state->lens[order[state->have++]] = 0; - state->next = state->codes; - state->lencode = (code const FAR *)(state->next); - state->lenbits = 7; - ret = inflate_table(CODES, state->lens, 19, &(state->next), - &(state->lenbits), state->work); - if (ret) { - strm->msg = (char *)"invalid code lengths set"; - state->mode = BAD; - break; - } - Tracev((stderr, "inflate: code lengths ok\n")); - state->have = 0; - state->mode = CODELENS; - case CODELENS: - while (state->have < state->nlen + state->ndist) { - for (;;) { - this = state->lencode[BITS(state->lenbits)]; - if ((unsigned)(this.bits) <= bits) break; - PULLBYTE(); - } - if (this.val < 16) { - NEEDBITS(this.bits); - DROPBITS(this.bits); - state->lens[state->have++] = this.val; - } - else { - if (this.val == 16) { - NEEDBITS(this.bits + 2); - DROPBITS(this.bits); - if (state->have == 0) { - strm->msg = (char *)"invalid bit length repeat"; - state->mode = BAD; - break; - } - len = state->lens[state->have - 1]; - copy = 3 + BITS(2); - DROPBITS(2); - } - else if (this.val == 17) { - NEEDBITS(this.bits + 3); - DROPBITS(this.bits); - len = 0; - copy = 3 + BITS(3); - DROPBITS(3); - } - else { - NEEDBITS(this.bits + 7); - DROPBITS(this.bits); - len = 0; - copy = 11 + BITS(7); - DROPBITS(7); - } - if (state->have + copy > state->nlen + state->ndist) { - strm->msg = (char *)"invalid bit length repeat"; - state->mode = BAD; - break; - } - while (copy--) - state->lens[state->have++] = (unsigned short)len; - } - } - - /* handle error breaks in while */ - if (state->mode == BAD) break; - - /* build code tables */ - state->next = state->codes; - state->lencode = (code const FAR *)(state->next); - state->lenbits = 9; - ret = inflate_table(LENS, state->lens, state->nlen, &(state->next), - &(state->lenbits), state->work); - if (ret) { - strm->msg = (char *)"invalid literal/lengths set"; - state->mode = BAD; - break; - } - state->distcode = (code const FAR *)(state->next); - state->distbits = 6; - ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist, - &(state->next), &(state->distbits), state->work); - if (ret) { - strm->msg = (char *)"invalid distances set"; - state->mode = BAD; - break; - } - Tracev((stderr, "inflate: codes ok\n")); - state->mode = LEN; - case LEN: - if (have >= 6 && left >= 258) { - RESTORE(); - inflate_fast(strm, out); - LOAD(); - break; - } - for (;;) { - this = state->lencode[BITS(state->lenbits)]; - if ((unsigned)(this.bits) <= bits) break; - PULLBYTE(); - } - if (this.op && (this.op & 0xf0) == 0) { - last = this; - for (;;) { - this = state->lencode[last.val + - (BITS(last.bits + last.op) >> last.bits)]; - if ((unsigned)(last.bits + this.bits) <= bits) break; - PULLBYTE(); - } - DROPBITS(last.bits); - } - DROPBITS(this.bits); - state->length = (unsigned)this.val; - if ((int)(this.op) == 0) { - Tracevv((stderr, this.val >= 0x20 && this.val < 0x7f ? - "inflate: literal '%c'\n" : - "inflate: literal 0x%02x\n", this.val)); - state->mode = LIT; - break; - } - if (this.op & 32) { - Tracevv((stderr, "inflate: end of block\n")); - state->mode = TYPE; - break; - } - if (this.op & 64) { - strm->msg = (char *)"invalid literal/length code"; - state->mode = BAD; - break; - } - state->extra = (unsigned)(this.op) & 15; - state->mode = LENEXT; - case LENEXT: - if (state->extra) { - NEEDBITS(state->extra); - state->length += BITS(state->extra); - DROPBITS(state->extra); - } - Tracevv((stderr, "inflate: length %u\n", state->length)); - state->mode = DIST; - case DIST: - for (;;) { - this = state->distcode[BITS(state->distbits)]; - if ((unsigned)(this.bits) <= bits) break; - PULLBYTE(); - } - if ((this.op & 0xf0) == 0) { - last = this; - for (;;) { - this = state->distcode[last.val + - (BITS(last.bits + last.op) >> last.bits)]; - if ((unsigned)(last.bits + this.bits) <= bits) break; - PULLBYTE(); - } - DROPBITS(last.bits); - } - DROPBITS(this.bits); - if (this.op & 64) { - strm->msg = (char *)"invalid distance code"; - state->mode = BAD; - break; - } - state->offset = (unsigned)this.val; - state->extra = (unsigned)(this.op) & 15; - state->mode = DISTEXT; - case DISTEXT: - if (state->extra) { - NEEDBITS(state->extra); - state->offset += BITS(state->extra); - DROPBITS(state->extra); - } -#ifdef INFLATE_STRICT - if (state->offset > state->dmax) { - strm->msg = (char *)"invalid distance too far back"; - state->mode = BAD; - break; - } -#endif - if (state->offset > state->whave + out - left) { - strm->msg = (char *)"invalid distance too far back"; - state->mode = BAD; - break; - } - Tracevv((stderr, "inflate: distance %u\n", state->offset)); - state->mode = MATCH; - case MATCH: - if (left == 0) goto inf_leave; - copy = out - left; - if (state->offset > copy) { /* copy from window */ - copy = state->offset - copy; - if (copy > state->write) { - copy -= state->write; - from = state->window + (state->wsize - copy); - } - else - from = state->window + (state->write - copy); - if (copy > state->length) copy = state->length; - } - else { /* copy from output */ - from = put - state->offset; - copy = state->length; - } - if (copy > left) copy = left; - left -= copy; - state->length -= copy; - do { - *put++ = *from++; - } while (--copy); - if (state->length == 0) state->mode = LEN; - break; - case LIT: - if (left == 0) goto inf_leave; - *put++ = (unsigned char)(state->length); - left--; - state->mode = LEN; - break; - case CHECK: - if (state->wrap) { - NEEDBITS(32); - out -= left; - strm->total_out += out; - state->total += out; - if (out) - strm->adler = state->check = - UPDATE(state->check, put - out, out); - out = left; - if (( -#ifdef GUNZIP - state->flags ? hold : -#endif - REVERSE(hold)) != state->check) { - strm->msg = (char *)"incorrect data check"; - state->mode = BAD; - break; - } - INITBITS(); - Tracev((stderr, "inflate: check matches trailer\n")); - } -#ifdef GUNZIP - state->mode = LENGTH; - case LENGTH: - if (state->wrap && state->flags) { - NEEDBITS(32); - if (hold != (state->total & 0xffffffffUL)) { - strm->msg = (char *)"incorrect length check"; - state->mode = BAD; - break; - } - INITBITS(); - Tracev((stderr, "inflate: length matches trailer\n")); - } -#endif - state->mode = DONE; - case DONE: - ret = Z_STREAM_END; - goto inf_leave; - case BAD: - ret = Z_DATA_ERROR; - goto inf_leave; - case MEM: - return Z_MEM_ERROR; - case SYNC: - default: - return Z_STREAM_ERROR; - } - - /* - Return from inflate(), updating the total counts and the check value. - If there was no progress during the inflate() call, return a buffer - error. Call updatewindow() to create and/or update the window state. - Note: a memory error from inflate() is non-recoverable. - */ - inf_leave: - RESTORE(); - if (state->wsize || (state->mode < CHECK && out != strm->avail_out)) - if (updatewindow(strm, out)) { - state->mode = MEM; - return Z_MEM_ERROR; - } - in -= strm->avail_in; - out -= strm->avail_out; - strm->total_in += in; - strm->total_out += out; - state->total += out; - if (state->wrap && out) - strm->adler = state->check = - UPDATE(state->check, strm->next_out - out, out); - strm->data_type = state->bits + (state->last ? 64 : 0) + - (state->mode == TYPE ? 128 : 0); - if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK) - ret = Z_BUF_ERROR; - return ret; -} - -int ZEXPORT inflateEnd(strm) -z_streamp strm; -{ - struct inflate_state FAR *state; - if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0) - return Z_STREAM_ERROR; - state = (struct inflate_state FAR *)strm->state; - if (state->window != Z_NULL) ZFREE(strm, state->window); - ZFREE(strm, strm->state); - strm->state = Z_NULL; - Tracev((stderr, "inflate: end\n")); - return Z_OK; -} - -int ZEXPORT inflateSetDictionary(strm, dictionary, dictLength) -z_streamp strm; -const Bytef *dictionary; -uInt dictLength; -{ - struct inflate_state FAR *state; - unsigned long id; - - /* check state */ - if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; - state = (struct inflate_state FAR *)strm->state; - if (state->wrap != 0 && state->mode != DICT) - return Z_STREAM_ERROR; - - /* check for correct dictionary id */ - if (state->mode == DICT) { - id = adler32(0L, Z_NULL, 0); - id = adler32(id, dictionary, dictLength); - if (id != state->check) - return Z_DATA_ERROR; - } - - /* copy dictionary to window */ - if (updatewindow(strm, strm->avail_out)) { - state->mode = MEM; - return Z_MEM_ERROR; - } - if (dictLength > state->wsize) { - zmemcpy(state->window, dictionary + dictLength - state->wsize, - state->wsize); - state->whave = state->wsize; - } - else { - zmemcpy(state->window + state->wsize - dictLength, dictionary, - dictLength); - state->whave = dictLength; - } - state->havedict = 1; - Tracev((stderr, "inflate: dictionary set\n")); - return Z_OK; -} - -int ZEXPORT inflateGetHeader(strm, head) -z_streamp strm; -gz_headerp head; -{ - struct inflate_state FAR *state; - - /* check state */ - if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; - state = (struct inflate_state FAR *)strm->state; - if ((state->wrap & 2) == 0) return Z_STREAM_ERROR; - - /* save header structure */ - state->head = head; - head->done = 0; - return Z_OK; -} - -/* - Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff. Return when found - or when out of input. When called, *have is the number of pattern bytes - found in order so far, in 0..3. On return *have is updated to the new - state. If on return *have equals four, then the pattern was found and the - return value is how many bytes were read including the last byte of the - pattern. If *have is less than four, then the pattern has not been found - yet and the return value is len. In the latter case, syncsearch() can be - called again with more data and the *have state. *have is initialized to - zero for the first call. - */ -local unsigned syncsearch(have, buf, len) -unsigned FAR *have; -unsigned char FAR *buf; -unsigned len; -{ - unsigned got; - unsigned next; - - got = *have; - next = 0; - while (next < len && got < 4) { - if ((int)(buf[next]) == (got < 2 ? 0 : 0xff)) - got++; - else if (buf[next]) - got = 0; - else - got = 4 - got; - next++; - } - *have = got; - return next; -} - -int ZEXPORT inflateSync(strm) -z_streamp strm; -{ - unsigned len; /* number of bytes to look at or looked at */ - unsigned long in, out; /* temporary to save total_in and total_out */ - unsigned char buf[4]; /* to restore bit buffer to byte string */ - struct inflate_state FAR *state; - - /* check parameters */ - if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; - state = (struct inflate_state FAR *)strm->state; - if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR; - - /* if first time, start search in bit buffer */ - if (state->mode != SYNC) { - state->mode = SYNC; - state->hold <<= state->bits & 7; - state->bits -= state->bits & 7; - len = 0; - while (state->bits >= 8) { - buf[len++] = (unsigned char)(state->hold); - state->hold >>= 8; - state->bits -= 8; - } - state->have = 0; - syncsearch(&(state->have), buf, len); - } - - /* search available input */ - len = syncsearch(&(state->have), strm->next_in, strm->avail_in); - strm->avail_in -= len; - strm->next_in += len; - strm->total_in += len; - - /* return no joy or set up to restart inflate() on a new block */ - if (state->have != 4) return Z_DATA_ERROR; - in = strm->total_in; out = strm->total_out; - inflateReset(strm); - strm->total_in = in; strm->total_out = out; - state->mode = TYPE; - return Z_OK; -} - -/* - Returns true if inflate is currently at the end of a block generated by - Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP - implementation to provide an additional safety check. PPP uses - Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored - block. When decompressing, PPP checks that at the end of input packet, - inflate is waiting for these length bytes. - */ -int ZEXPORT inflateSyncPoint(strm) -z_streamp strm; -{ - struct inflate_state FAR *state; - - if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; - state = (struct inflate_state FAR *)strm->state; - return state->mode == STORED && state->bits == 0; -} - -int ZEXPORT inflateCopy(dest, source) -z_streamp dest; -z_streamp source; -{ - struct inflate_state FAR *state; - struct inflate_state FAR *copy; - unsigned char FAR *window; - unsigned wsize; - - /* check input */ - if (dest == Z_NULL || source == Z_NULL || source->state == Z_NULL || - source->zalloc == (alloc_func)0 || source->zfree == (free_func)0) - return Z_STREAM_ERROR; - state = (struct inflate_state FAR *)source->state; - - /* allocate space */ - copy = (struct inflate_state FAR *) - ZALLOC(source, 1, sizeof(struct inflate_state)); - if (copy == Z_NULL) return Z_MEM_ERROR; - window = Z_NULL; - if (state->window != Z_NULL) { - window = (unsigned char FAR *) - ZALLOC(source, 1U << state->wbits, sizeof(unsigned char)); - if (window == Z_NULL) { - ZFREE(source, copy); - return Z_MEM_ERROR; - } - } - - /* copy state */ - zmemcpy(dest, source, sizeof(z_stream)); - zmemcpy(copy, state, sizeof(struct inflate_state)); - if (state->lencode >= state->codes && - state->lencode <= state->codes + ENOUGH - 1) { - copy->lencode = copy->codes + (state->lencode - state->codes); - copy->distcode = copy->codes + (state->distcode - state->codes); - } - copy->next = copy->codes + (state->next - state->codes); - if (window != Z_NULL) { - wsize = 1U << state->wbits; - zmemcpy(window, state->window, wsize); - } - copy->window = window; - dest->state = (struct internal_state FAR *)copy; - return Z_OK; -} +/* inflate.c -- zlib decompression + * Copyright (C) 1995-2005 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* + * Change history: + * + * 1.2.beta0 24 Nov 2002 + * - First version -- complete rewrite of inflate to simplify code, avoid + * creation of window when not needed, minimize use of window when it is + * needed, make inffast.c even faster, implement gzip decoding, and to + * improve code readability and style over the previous zlib inflate code + * + * 1.2.beta1 25 Nov 2002 + * - Use pointers for available input and output checking in inffast.c + * - Remove input and output counters in inffast.c + * - Change inffast.c entry and loop from avail_in >= 7 to >= 6 + * - Remove unnecessary second byte pull from length extra in inffast.c + * - Unroll direct copy to three copies per loop in inffast.c + * + * 1.2.beta2 4 Dec 2002 + * - Change external routine names to reduce potential conflicts + * - Correct filename to inffixed.h for fixed tables in inflate.c + * - Make hbuf[] unsigned char to match parameter type in inflate.c + * - Change strm->next_out[-state->offset] to *(strm->next_out - state->offset) + * to avoid negation problem on Alphas (64 bit) in inflate.c + * + * 1.2.beta3 22 Dec 2002 + * - Add comments on state->bits assertion in inffast.c + * - Add comments on op field in inftrees.h + * - Fix bug in reuse of allocated window after inflateReset() + * - Remove bit fields--back to byte structure for speed + * - Remove distance extra == 0 check in inflate_fast()--only helps for lengths + * - Change post-increments to pre-increments in inflate_fast(), PPC biased? + * - Add compile time option, POSTINC, to use post-increments instead (Intel?) + * - Make MATCH copy in inflate() much faster for when inflate_fast() not used + * - Use local copies of stream next and avail values, as well as local bit + * buffer and bit count in inflate()--for speed when inflate_fast() not used + * + * 1.2.beta4 1 Jan 2003 + * - Split ptr - 257 statements in inflate_table() to avoid compiler warnings + * - Move a comment on output buffer sizes from inffast.c to inflate.c + * - Add comments in inffast.c to introduce the inflate_fast() routine + * - Rearrange window copies in inflate_fast() for speed and simplification + * - Unroll last copy for window match in inflate_fast() + * - Use local copies of window variables in inflate_fast() for speed + * - Pull out common write == 0 case for speed in inflate_fast() + * - Make op and len in inflate_fast() unsigned for consistency + * - Add FAR to lcode and dcode declarations in inflate_fast() + * - Simplified bad distance check in inflate_fast() + * - Added inflateBackInit(), inflateBack(), and inflateBackEnd() in new + * source file infback.c to provide a call-back interface to inflate for + * programs like gzip and unzip -- uses window as output buffer to avoid + * window copying + * + * 1.2.beta5 1 Jan 2003 + * - Improved inflateBack() interface to allow the caller to provide initial + * input in strm. + * - Fixed stored blocks bug in inflateBack() + * + * 1.2.beta6 4 Jan 2003 + * - Added comments in inffast.c on effectiveness of POSTINC + * - Typecasting all around to reduce compiler warnings + * - Changed loops from while (1) or do {} while (1) to for (;;), again to + * make compilers happy + * - Changed type of window in inflateBackInit() to unsigned char * + * + * 1.2.beta7 27 Jan 2003 + * - Changed many types to unsigned or unsigned short to avoid warnings + * - Added inflateCopy() function + * + * 1.2.0 9 Mar 2003 + * - Changed inflateBack() interface to provide separate opaque descriptors + * for the in() and out() functions + * - Changed inflateBack() argument and in_func typedef to swap the length + * and buffer address return values for the input function + * - Check next_in and next_out for Z_NULL on entry to inflate() + * + * The history for versions after 1.2.0 are in ChangeLog in zlib distribution. + */ + +#include "zutil.h" +#include "inftrees.h" +#include "inflate.h" +#include "inffast.h" + +#ifdef MAKEFIXED +# ifndef BUILDFIXED +# define BUILDFIXED +# endif +#endif + +/* function prototypes */ +local void fixedtables OF((struct inflate_state FAR *state)); +local int updatewindow OF((z_streamp strm, unsigned out)); +#ifdef BUILDFIXED + void makefixed OF((void)); +#endif +local unsigned syncsearch OF((unsigned FAR *have, unsigned char FAR *buf, + unsigned len)); + +int ZEXPORT inflateReset(strm) +z_streamp strm; +{ + struct inflate_state FAR *state; + + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + strm->total_in = strm->total_out = state->total = 0; + strm->msg = Z_NULL; + strm->adler = 1; /* to support ill-conceived Java test suite */ + state->mode = HEAD; + state->last = 0; + state->havedict = 0; + state->dmax = 32768U; + state->head = Z_NULL; + state->wsize = 0; + state->whave = 0; + state->write = 0; + state->hold = 0; + state->bits = 0; + state->lencode = state->distcode = state->next = state->codes; + Tracev((stderr, "inflate: reset\n")); + return Z_OK; +} + +int ZEXPORT inflatePrime(strm, bits, value) +z_streamp strm; +int bits; +int value; +{ + struct inflate_state FAR *state; + + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + if (bits > 16 || state->bits + bits > 32) return Z_STREAM_ERROR; + value &= (1L << bits) - 1; + state->hold += value << state->bits; + state->bits += bits; + return Z_OK; +} + +int ZEXPORT inflateInit2_(strm, windowBits, version, stream_size) +z_streamp strm; +int windowBits; +const char *version; +int stream_size; +{ + struct inflate_state FAR *state; + + if (version == Z_NULL || version[0] != ZLIB_VERSION[0] || + stream_size != (int)(sizeof(z_stream))) + return Z_VERSION_ERROR; + if (strm == Z_NULL) return Z_STREAM_ERROR; + strm->msg = Z_NULL; /* in case we return an error */ + if (strm->zalloc == (alloc_func)0) { + strm->zalloc = zcalloc; + strm->opaque = (voidpf)0; + } + if (strm->zfree == (free_func)0) strm->zfree = zcfree; + state = (struct inflate_state FAR *) + ZALLOC(strm, 1, sizeof(struct inflate_state)); + if (state == Z_NULL) return Z_MEM_ERROR; + Tracev((stderr, "inflate: allocated\n")); + strm->state = (struct internal_state FAR *)state; + if (windowBits < 0) { + state->wrap = 0; + windowBits = -windowBits; + } + else { + state->wrap = (windowBits >> 4) + 1; +#ifdef GUNZIP + if (windowBits < 48) windowBits &= 15; +#endif + } + if (windowBits < 8 || windowBits > 15) { + ZFREE(strm, state); + strm->state = Z_NULL; + return Z_STREAM_ERROR; + } + state->wbits = (unsigned)windowBits; + state->window = Z_NULL; + return inflateReset(strm); +} + +int ZEXPORT inflateInit_(strm, version, stream_size) +z_streamp strm; +const char *version; +int stream_size; +{ + return inflateInit2_(strm, DEF_WBITS, version, stream_size); +} + +/* + Return state with length and distance decoding tables and index sizes set to + fixed code decoding. Normally this returns fixed tables from inffixed.h. + If BUILDFIXED is defined, then instead this routine builds the tables the + first time it's called, and returns those tables the first time and + thereafter. This reduces the size of the code by about 2K bytes, in + exchange for a little execution time. However, BUILDFIXED should not be + used for threaded applications, since the rewriting of the tables and virgin + may not be thread-safe. + */ +local void fixedtables(state) +struct inflate_state FAR *state; +{ +#ifdef BUILDFIXED + static int virgin = 1; + static code *lenfix, *distfix; + static code fixed[544]; + + /* build fixed huffman tables if first call (may not be thread safe) */ + if (virgin) { + unsigned sym, bits; + static code *next; + + /* literal/length table */ + sym = 0; + while (sym < 144) state->lens[sym++] = 8; + while (sym < 256) state->lens[sym++] = 9; + while (sym < 280) state->lens[sym++] = 7; + while (sym < 288) state->lens[sym++] = 8; + next = fixed; + lenfix = next; + bits = 9; + inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work); + + /* distance table */ + sym = 0; + while (sym < 32) state->lens[sym++] = 5; + distfix = next; + bits = 5; + inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work); + + /* do this just once */ + virgin = 0; + } +#else /* !BUILDFIXED */ +# include "inffixed.h" +#endif /* BUILDFIXED */ + state->lencode = lenfix; + state->lenbits = 9; + state->distcode = distfix; + state->distbits = 5; +} + +#ifdef MAKEFIXED +#include + +/* + Write out the inffixed.h that is #include'd above. Defining MAKEFIXED also + defines BUILDFIXED, so the tables are built on the fly. makefixed() writes + those tables to stdout, which would be piped to inffixed.h. A small program + can simply call makefixed to do this: + + void makefixed(void); + + int main(void) + { + makefixed(); + return 0; + } + + Then that can be linked with zlib built with MAKEFIXED defined and run: + + a.out > inffixed.h + */ +void makefixed() +{ + unsigned low, size; + struct inflate_state state; + + fixedtables(&state); + puts(" /* inffixed.h -- table for decoding fixed codes"); + puts(" * Generated automatically by makefixed()."); + puts(" */"); + puts(""); + puts(" /* WARNING: this file should *not* be used by applications."); + puts(" It is part of the implementation of this library and is"); + puts(" subject to change. Applications should only use zlib.h."); + puts(" */"); + puts(""); + size = 1U << 9; + printf(" static const code lenfix[%u] = {", size); + low = 0; + for (;;) { + if ((low % 7) == 0) printf("\n "); + printf("{%u,%u,%d}", state.lencode[low].op, state.lencode[low].bits, + state.lencode[low].val); + if (++low == size) break; + putchar(','); + } + puts("\n };"); + size = 1U << 5; + printf("\n static const code distfix[%u] = {", size); + low = 0; + for (;;) { + if ((low % 6) == 0) printf("\n "); + printf("{%u,%u,%d}", state.distcode[low].op, state.distcode[low].bits, + state.distcode[low].val); + if (++low == size) break; + putchar(','); + } + puts("\n };"); +} +#endif /* MAKEFIXED */ + +/* + Update the window with the last wsize (normally 32K) bytes written before + returning. If window does not exist yet, create it. This is only called + when a window is already in use, or when output has been written during this + inflate call, but the end of the deflate stream has not been reached yet. + It is also called to create a window for dictionary data when a dictionary + is loaded. + + Providing output buffers larger than 32K to inflate() should provide a speed + advantage, since only the last 32K of output is copied to the sliding window + upon return from inflate(), and since all distances after the first 32K of + output will fall in the output data, making match copies simpler and faster. + The advantage may be dependent on the size of the processor's data caches. + */ +local int updatewindow(strm, out) +z_streamp strm; +unsigned out; +{ + struct inflate_state FAR *state; + unsigned copy, dist; + + state = (struct inflate_state FAR *)strm->state; + + /* if it hasn't been done already, allocate space for the window */ + if (state->window == Z_NULL) { + state->window = (unsigned char FAR *) + ZALLOC(strm, 1U << state->wbits, + sizeof(unsigned char)); + if (state->window == Z_NULL) return 1; + } + + /* if window not in use yet, initialize */ + if (state->wsize == 0) { + state->wsize = 1U << state->wbits; + state->write = 0; + state->whave = 0; + } + + /* copy state->wsize or less output bytes into the circular window */ + copy = out - strm->avail_out; + if (copy >= state->wsize) { + zmemcpy(state->window, strm->next_out - state->wsize, state->wsize); + state->write = 0; + state->whave = state->wsize; + } + else { + dist = state->wsize - state->write; + if (dist > copy) dist = copy; + zmemcpy(state->window + state->write, strm->next_out - copy, dist); + copy -= dist; + if (copy) { + zmemcpy(state->window, strm->next_out - copy, copy); + state->write = copy; + state->whave = state->wsize; + } + else { + state->write += dist; + if (state->write == state->wsize) state->write = 0; + if (state->whave < state->wsize) state->whave += dist; + } + } + return 0; +} + +/* Macros for inflate(): */ + +/* check function to use adler32() for zlib or crc32() for gzip */ +#ifdef GUNZIP +# define UPDATE(check, buf, len) \ + (state->flags ? crc32(check, buf, len) : adler32(check, buf, len)) +#else +# define UPDATE(check, buf, len) adler32(check, buf, len) +#endif + +/* check macros for header crc */ +#ifdef GUNZIP +# define CRC2(check, word) \ + do { \ + hbuf[0] = (unsigned char)(word); \ + hbuf[1] = (unsigned char)((word) >> 8); \ + check = crc32(check, hbuf, 2); \ + } while (0) + +# define CRC4(check, word) \ + do { \ + hbuf[0] = (unsigned char)(word); \ + hbuf[1] = (unsigned char)((word) >> 8); \ + hbuf[2] = (unsigned char)((word) >> 16); \ + hbuf[3] = (unsigned char)((word) >> 24); \ + check = crc32(check, hbuf, 4); \ + } while (0) +#endif + +/* Load registers with state in inflate() for speed */ +#define LOAD() \ + do { \ + put = strm->next_out; \ + left = strm->avail_out; \ + next = strm->next_in; \ + have = strm->avail_in; \ + hold = state->hold; \ + bits = state->bits; \ + } while (0) + +/* Restore state from registers in inflate() */ +#define RESTORE() \ + do { \ + strm->next_out = put; \ + strm->avail_out = left; \ + strm->next_in = next; \ + strm->avail_in = have; \ + state->hold = hold; \ + state->bits = bits; \ + } while (0) + +/* Clear the input bit accumulator */ +#define INITBITS() \ + do { \ + hold = 0; \ + bits = 0; \ + } while (0) + +/* Get a byte of input into the bit accumulator, or return from inflate() + if there is no input available. */ +#define PULLBYTE() \ + do { \ + if (have == 0) goto inf_leave; \ + have--; \ + hold += (unsigned long)(*next++) << bits; \ + bits += 8; \ + } while (0) + +/* Assure that there are at least n bits in the bit accumulator. If there is + not enough available input to do that, then return from inflate(). */ +#define NEEDBITS(n) \ + do { \ + while (bits < (unsigned)(n)) \ + PULLBYTE(); \ + } while (0) + +/* Return the low n bits of the bit accumulator (n < 16) */ +#define BITS(n) \ + ((unsigned)hold & ((1U << (n)) - 1)) + +/* Remove n bits from the bit accumulator */ +#define DROPBITS(n) \ + do { \ + hold >>= (n); \ + bits -= (unsigned)(n); \ + } while (0) + +/* Remove zero to seven bits as needed to go to a byte boundary */ +#define BYTEBITS() \ + do { \ + hold >>= bits & 7; \ + bits -= bits & 7; \ + } while (0) + +/* Reverse the bytes in a 32-bit value */ +#define REVERSE(q) \ + ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \ + (((q) & 0xff00) << 8) + (((q) & 0xff) << 24)) + +/* + inflate() uses a state machine to process as much input data and generate as + much output data as possible before returning. The state machine is + structured roughly as follows: + + for (;;) switch (state) { + ... + case STATEn: + if (not enough input data or output space to make progress) + return; + ... make progress ... + state = STATEm; + break; + ... + } + + so when inflate() is called again, the same case is attempted again, and + if the appropriate resources are provided, the machine proceeds to the + next state. The NEEDBITS() macro is usually the way the state evaluates + whether it can proceed or should return. NEEDBITS() does the return if + the requested bits are not available. The typical use of the BITS macros + is: + + NEEDBITS(n); + ... do something with BITS(n) ... + DROPBITS(n); + + where NEEDBITS(n) either returns from inflate() if there isn't enough + input left to load n bits into the accumulator, or it continues. BITS(n) + gives the low n bits in the accumulator. When done, DROPBITS(n) drops + the low n bits off the accumulator. INITBITS() clears the accumulator + and sets the number of available bits to zero. BYTEBITS() discards just + enough bits to put the accumulator on a byte boundary. After BYTEBITS() + and a NEEDBITS(8), then BITS(8) would return the next byte in the stream. + + NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return + if there is no input available. The decoding of variable length codes uses + PULLBYTE() directly in order to pull just enough bytes to decode the next + code, and no more. + + Some states loop until they get enough input, making sure that enough + state information is maintained to continue the loop where it left off + if NEEDBITS() returns in the loop. For example, want, need, and keep + would all have to actually be part of the saved state in case NEEDBITS() + returns: + + case STATEw: + while (want < need) { + NEEDBITS(n); + keep[want++] = BITS(n); + DROPBITS(n); + } + state = STATEx; + case STATEx: + + As shown above, if the next state is also the next case, then the break + is omitted. + + A state may also return if there is not enough output space available to + complete that state. Those states are copying stored data, writing a + literal byte, and copying a matching string. + + When returning, a "goto inf_leave" is used to update the total counters, + update the check value, and determine whether any progress has been made + during that inflate() call in order to return the proper return code. + Progress is defined as a change in either strm->avail_in or strm->avail_out. + When there is a window, goto inf_leave will update the window with the last + output written. If a goto inf_leave occurs in the middle of decompression + and there is no window currently, goto inf_leave will create one and copy + output to the window for the next call of inflate(). + + In this implementation, the flush parameter of inflate() only affects the + return code (per zlib.h). inflate() always writes as much as possible to + strm->next_out, given the space available and the provided input--the effect + documented in zlib.h of Z_SYNC_FLUSH. Furthermore, inflate() always defers + the allocation of and copying into a sliding window until necessary, which + provides the effect documented in zlib.h for Z_FINISH when the entire input + stream available. So the only thing the flush parameter actually does is: + when flush is set to Z_FINISH, inflate() cannot return Z_OK. Instead it + will return Z_BUF_ERROR if it has not reached the end of the stream. + */ + +int ZEXPORT inflate(strm, flush) +z_streamp strm; +int flush; +{ + struct inflate_state FAR *state; + unsigned char FAR *next; /* next input */ + unsigned char FAR *put; /* next output */ + unsigned have, left; /* available input and output */ + unsigned long hold; /* bit buffer */ + unsigned bits; /* bits in bit buffer */ + unsigned in, out; /* save starting available input and output */ + unsigned copy; /* number of stored or match bytes to copy */ + unsigned char FAR *from; /* where to copy match bytes from */ + code this; /* current decoding table entry */ + code last; /* parent table entry */ + unsigned len; /* length to copy for repeats, bits to drop */ + int ret; /* return code */ +#ifdef GUNZIP + unsigned char hbuf[4]; /* buffer for gzip header crc calculation */ +#endif + static const unsigned short order[19] = /* permutation of code lengths */ + {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; + + if (strm == Z_NULL || strm->state == Z_NULL || strm->next_out == Z_NULL || + (strm->next_in == Z_NULL && strm->avail_in != 0)) + return Z_STREAM_ERROR; + + state = (struct inflate_state FAR *)strm->state; + if (state->mode == TYPE) state->mode = TYPEDO; /* skip check */ + LOAD(); + in = have; + out = left; + ret = Z_OK; + for (;;) + switch (state->mode) { + case HEAD: + if (state->wrap == 0) { + state->mode = TYPEDO; + break; + } + NEEDBITS(16); +#ifdef GUNZIP + if ((state->wrap & 2) && hold == 0x8b1f) { /* gzip header */ + state->check = crc32(0L, Z_NULL, 0); + CRC2(state->check, hold); + INITBITS(); + state->mode = FLAGS; + break; + } + state->flags = 0; /* expect zlib header */ + if (state->head != Z_NULL) + state->head->done = -1; + if (!(state->wrap & 1) || /* check if zlib header allowed */ +#else + if ( +#endif + ((BITS(8) << 8) + (hold >> 8)) % 31) { + strm->msg = (char *)"incorrect header check"; + state->mode = BAD; + break; + } + if (BITS(4) != Z_DEFLATED) { + strm->msg = (char *)"unknown compression method"; + state->mode = BAD; + break; + } + DROPBITS(4); + len = BITS(4) + 8; + if (len > state->wbits) { + strm->msg = (char *)"invalid window size"; + state->mode = BAD; + break; + } + state->dmax = 1U << len; + Tracev((stderr, "inflate: zlib header ok\n")); + strm->adler = state->check = adler32(0L, Z_NULL, 0); + state->mode = hold & 0x200 ? DICTID : TYPE; + INITBITS(); + break; +#ifdef GUNZIP + case FLAGS: + NEEDBITS(16); + state->flags = (int)(hold); + if ((state->flags & 0xff) != Z_DEFLATED) { + strm->msg = (char *)"unknown compression method"; + state->mode = BAD; + break; + } + if (state->flags & 0xe000) { + strm->msg = (char *)"unknown header flags set"; + state->mode = BAD; + break; + } + if (state->head != Z_NULL) + state->head->text = (int)((hold >> 8) & 1); + if (state->flags & 0x0200) CRC2(state->check, hold); + INITBITS(); + state->mode = TIME; + case TIME: + NEEDBITS(32); + if (state->head != Z_NULL) + state->head->time = hold; + if (state->flags & 0x0200) CRC4(state->check, hold); + INITBITS(); + state->mode = OS; + case OS: + NEEDBITS(16); + if (state->head != Z_NULL) { + state->head->xflags = (int)(hold & 0xff); + state->head->os = (int)(hold >> 8); + } + if (state->flags & 0x0200) CRC2(state->check, hold); + INITBITS(); + state->mode = EXLEN; + case EXLEN: + if (state->flags & 0x0400) { + NEEDBITS(16); + state->length = (unsigned)(hold); + if (state->head != Z_NULL) + state->head->extra_len = (unsigned)hold; + if (state->flags & 0x0200) CRC2(state->check, hold); + INITBITS(); + } + else if (state->head != Z_NULL) + state->head->extra = Z_NULL; + state->mode = EXTRA; + case EXTRA: + if (state->flags & 0x0400) { + copy = state->length; + if (copy > have) copy = have; + if (copy) { + if (state->head != Z_NULL && + state->head->extra != Z_NULL) { + len = state->head->extra_len - state->length; + zmemcpy(state->head->extra + len, next, + len + copy > state->head->extra_max ? + state->head->extra_max - len : copy); + } + if (state->flags & 0x0200) + state->check = crc32(state->check, next, copy); + have -= copy; + next += copy; + state->length -= copy; + } + if (state->length) goto inf_leave; + } + state->length = 0; + state->mode = NAME; + case NAME: + if (state->flags & 0x0800) { + if (have == 0) goto inf_leave; + copy = 0; + do { + len = (unsigned)(next[copy++]); + if (state->head != Z_NULL && + state->head->name != Z_NULL && + state->length < state->head->name_max) + state->head->name[state->length++] = len; + } while (len && copy < have); + if (state->flags & 0x0200) + state->check = crc32(state->check, next, copy); + have -= copy; + next += copy; + if (len) goto inf_leave; + } + else if (state->head != Z_NULL) + state->head->name = Z_NULL; + state->length = 0; + state->mode = COMMENT; + case COMMENT: + if (state->flags & 0x1000) { + if (have == 0) goto inf_leave; + copy = 0; + do { + len = (unsigned)(next[copy++]); + if (state->head != Z_NULL && + state->head->comment != Z_NULL && + state->length < state->head->comm_max) + state->head->comment[state->length++] = len; + } while (len && copy < have); + if (state->flags & 0x0200) + state->check = crc32(state->check, next, copy); + have -= copy; + next += copy; + if (len) goto inf_leave; + } + else if (state->head != Z_NULL) + state->head->comment = Z_NULL; + state->mode = HCRC; + case HCRC: + if (state->flags & 0x0200) { + NEEDBITS(16); + if (hold != (state->check & 0xffff)) { + strm->msg = (char *)"header crc mismatch"; + state->mode = BAD; + break; + } + INITBITS(); + } + if (state->head != Z_NULL) { + state->head->hcrc = (int)((state->flags >> 9) & 1); + state->head->done = 1; + } + strm->adler = state->check = crc32(0L, Z_NULL, 0); + state->mode = TYPE; + break; +#endif + case DICTID: + NEEDBITS(32); + strm->adler = state->check = REVERSE(hold); + INITBITS(); + state->mode = DICT; + case DICT: + if (state->havedict == 0) { + RESTORE(); + return Z_NEED_DICT; + } + strm->adler = state->check = adler32(0L, Z_NULL, 0); + state->mode = TYPE; + case TYPE: + if (flush == Z_BLOCK) goto inf_leave; + case TYPEDO: + if (state->last) { + BYTEBITS(); + state->mode = CHECK; + break; + } + NEEDBITS(3); + state->last = BITS(1); + DROPBITS(1); + switch (BITS(2)) { + case 0: /* stored block */ + Tracev((stderr, "inflate: stored block%s\n", + state->last ? " (last)" : "")); + state->mode = STORED; + break; + case 1: /* fixed block */ + fixedtables(state); + Tracev((stderr, "inflate: fixed codes block%s\n", + state->last ? " (last)" : "")); + state->mode = LEN; /* decode codes */ + break; + case 2: /* dynamic block */ + Tracev((stderr, "inflate: dynamic codes block%s\n", + state->last ? " (last)" : "")); + state->mode = TABLE; + break; + case 3: + strm->msg = (char *)"invalid block type"; + state->mode = BAD; + } + DROPBITS(2); + break; + case STORED: + BYTEBITS(); /* go to byte boundary */ + NEEDBITS(32); + if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) { + strm->msg = (char *)"invalid stored block lengths"; + state->mode = BAD; + break; + } + state->length = (unsigned)hold & 0xffff; + Tracev((stderr, "inflate: stored length %u\n", + state->length)); + INITBITS(); + state->mode = COPY; + case COPY: + copy = state->length; + if (copy) { + if (copy > have) copy = have; + if (copy > left) copy = left; + if (copy == 0) goto inf_leave; + zmemcpy(put, next, copy); + have -= copy; + next += copy; + left -= copy; + put += copy; + state->length -= copy; + break; + } + Tracev((stderr, "inflate: stored end\n")); + state->mode = TYPE; + break; + case TABLE: + NEEDBITS(14); + state->nlen = BITS(5) + 257; + DROPBITS(5); + state->ndist = BITS(5) + 1; + DROPBITS(5); + state->ncode = BITS(4) + 4; + DROPBITS(4); +#ifndef PKZIP_BUG_WORKAROUND + if (state->nlen > 286 || state->ndist > 30) { + strm->msg = (char *)"too many length or distance symbols"; + state->mode = BAD; + break; + } +#endif + Tracev((stderr, "inflate: table sizes ok\n")); + state->have = 0; + state->mode = LENLENS; + case LENLENS: + while (state->have < state->ncode) { + NEEDBITS(3); + state->lens[order[state->have++]] = (unsigned short)BITS(3); + DROPBITS(3); + } + while (state->have < 19) + state->lens[order[state->have++]] = 0; + state->next = state->codes; + state->lencode = (code const FAR *)(state->next); + state->lenbits = 7; + ret = inflate_table(CODES, state->lens, 19, &(state->next), + &(state->lenbits), state->work); + if (ret) { + strm->msg = (char *)"invalid code lengths set"; + state->mode = BAD; + break; + } + Tracev((stderr, "inflate: code lengths ok\n")); + state->have = 0; + state->mode = CODELENS; + case CODELENS: + while (state->have < state->nlen + state->ndist) { + for (;;) { + this = state->lencode[BITS(state->lenbits)]; + if ((unsigned)(this.bits) <= bits) break; + PULLBYTE(); + } + if (this.val < 16) { + NEEDBITS(this.bits); + DROPBITS(this.bits); + state->lens[state->have++] = this.val; + } + else { + if (this.val == 16) { + NEEDBITS(this.bits + 2); + DROPBITS(this.bits); + if (state->have == 0) { + strm->msg = (char *)"invalid bit length repeat"; + state->mode = BAD; + break; + } + len = state->lens[state->have - 1]; + copy = 3 + BITS(2); + DROPBITS(2); + } + else if (this.val == 17) { + NEEDBITS(this.bits + 3); + DROPBITS(this.bits); + len = 0; + copy = 3 + BITS(3); + DROPBITS(3); + } + else { + NEEDBITS(this.bits + 7); + DROPBITS(this.bits); + len = 0; + copy = 11 + BITS(7); + DROPBITS(7); + } + if (state->have + copy > state->nlen + state->ndist) { + strm->msg = (char *)"invalid bit length repeat"; + state->mode = BAD; + break; + } + while (copy--) + state->lens[state->have++] = (unsigned short)len; + } + } + + /* handle error breaks in while */ + if (state->mode == BAD) break; + + /* build code tables */ + state->next = state->codes; + state->lencode = (code const FAR *)(state->next); + state->lenbits = 9; + ret = inflate_table(LENS, state->lens, state->nlen, &(state->next), + &(state->lenbits), state->work); + if (ret) { + strm->msg = (char *)"invalid literal/lengths set"; + state->mode = BAD; + break; + } + state->distcode = (code const FAR *)(state->next); + state->distbits = 6; + ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist, + &(state->next), &(state->distbits), state->work); + if (ret) { + strm->msg = (char *)"invalid distances set"; + state->mode = BAD; + break; + } + Tracev((stderr, "inflate: codes ok\n")); + state->mode = LEN; + case LEN: + if (have >= 6 && left >= 258) { + RESTORE(); + inflate_fast(strm, out); + LOAD(); + break; + } + for (;;) { + this = state->lencode[BITS(state->lenbits)]; + if ((unsigned)(this.bits) <= bits) break; + PULLBYTE(); + } + if (this.op && (this.op & 0xf0) == 0) { + last = this; + for (;;) { + this = state->lencode[last.val + + (BITS(last.bits + last.op) >> last.bits)]; + if ((unsigned)(last.bits + this.bits) <= bits) break; + PULLBYTE(); + } + DROPBITS(last.bits); + } + DROPBITS(this.bits); + state->length = (unsigned)this.val; + if ((int)(this.op) == 0) { + Tracevv((stderr, this.val >= 0x20 && this.val < 0x7f ? + "inflate: literal '%c'\n" : + "inflate: literal 0x%02x\n", this.val)); + state->mode = LIT; + break; + } + if (this.op & 32) { + Tracevv((stderr, "inflate: end of block\n")); + state->mode = TYPE; + break; + } + if (this.op & 64) { + strm->msg = (char *)"invalid literal/length code"; + state->mode = BAD; + break; + } + state->extra = (unsigned)(this.op) & 15; + state->mode = LENEXT; + case LENEXT: + if (state->extra) { + NEEDBITS(state->extra); + state->length += BITS(state->extra); + DROPBITS(state->extra); + } + Tracevv((stderr, "inflate: length %u\n", state->length)); + state->mode = DIST; + case DIST: + for (;;) { + this = state->distcode[BITS(state->distbits)]; + if ((unsigned)(this.bits) <= bits) break; + PULLBYTE(); + } + if ((this.op & 0xf0) == 0) { + last = this; + for (;;) { + this = state->distcode[last.val + + (BITS(last.bits + last.op) >> last.bits)]; + if ((unsigned)(last.bits + this.bits) <= bits) break; + PULLBYTE(); + } + DROPBITS(last.bits); + } + DROPBITS(this.bits); + if (this.op & 64) { + strm->msg = (char *)"invalid distance code"; + state->mode = BAD; + break; + } + state->offset = (unsigned)this.val; + state->extra = (unsigned)(this.op) & 15; + state->mode = DISTEXT; + case DISTEXT: + if (state->extra) { + NEEDBITS(state->extra); + state->offset += BITS(state->extra); + DROPBITS(state->extra); + } +#ifdef INFLATE_STRICT + if (state->offset > state->dmax) { + strm->msg = (char *)"invalid distance too far back"; + state->mode = BAD; + break; + } +#endif + if (state->offset > state->whave + out - left) { + strm->msg = (char *)"invalid distance too far back"; + state->mode = BAD; + break; + } + Tracevv((stderr, "inflate: distance %u\n", state->offset)); + state->mode = MATCH; + case MATCH: + if (left == 0) goto inf_leave; + copy = out - left; + if (state->offset > copy) { /* copy from window */ + copy = state->offset - copy; + if (copy > state->write) { + copy -= state->write; + from = state->window + (state->wsize - copy); + } + else + from = state->window + (state->write - copy); + if (copy > state->length) copy = state->length; + } + else { /* copy from output */ + from = put - state->offset; + copy = state->length; + } + if (copy > left) copy = left; + left -= copy; + state->length -= copy; + do { + *put++ = *from++; + } while (--copy); + if (state->length == 0) state->mode = LEN; + break; + case LIT: + if (left == 0) goto inf_leave; + *put++ = (unsigned char)(state->length); + left--; + state->mode = LEN; + break; + case CHECK: + if (state->wrap) { + NEEDBITS(32); + out -= left; + strm->total_out += out; + state->total += out; + if (out) + strm->adler = state->check = + UPDATE(state->check, put - out, out); + out = left; + if (( +#ifdef GUNZIP + state->flags ? hold : +#endif + REVERSE(hold)) != state->check) { + strm->msg = (char *)"incorrect data check"; + state->mode = BAD; + break; + } + INITBITS(); + Tracev((stderr, "inflate: check matches trailer\n")); + } +#ifdef GUNZIP + state->mode = LENGTH; + case LENGTH: + if (state->wrap && state->flags) { + NEEDBITS(32); + if (hold != (state->total & 0xffffffffUL)) { + strm->msg = (char *)"incorrect length check"; + state->mode = BAD; + break; + } + INITBITS(); + Tracev((stderr, "inflate: length matches trailer\n")); + } +#endif + state->mode = DONE; + case DONE: + ret = Z_STREAM_END; + goto inf_leave; + case BAD: + ret = Z_DATA_ERROR; + goto inf_leave; + case MEM: + return Z_MEM_ERROR; + case SYNC: + default: + return Z_STREAM_ERROR; + } + + /* + Return from inflate(), updating the total counts and the check value. + If there was no progress during the inflate() call, return a buffer + error. Call updatewindow() to create and/or update the window state. + Note: a memory error from inflate() is non-recoverable. + */ + inf_leave: + RESTORE(); + if (state->wsize || (state->mode < CHECK && out != strm->avail_out)) + if (updatewindow(strm, out)) { + state->mode = MEM; + return Z_MEM_ERROR; + } + in -= strm->avail_in; + out -= strm->avail_out; + strm->total_in += in; + strm->total_out += out; + state->total += out; + if (state->wrap && out) + strm->adler = state->check = + UPDATE(state->check, strm->next_out - out, out); + strm->data_type = state->bits + (state->last ? 64 : 0) + + (state->mode == TYPE ? 128 : 0); + if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK) + ret = Z_BUF_ERROR; + return ret; +} + +int ZEXPORT inflateEnd(strm) +z_streamp strm; +{ + struct inflate_state FAR *state; + if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0) + return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + if (state->window != Z_NULL) ZFREE(strm, state->window); + ZFREE(strm, strm->state); + strm->state = Z_NULL; + Tracev((stderr, "inflate: end\n")); + return Z_OK; +} + +int ZEXPORT inflateSetDictionary(strm, dictionary, dictLength) +z_streamp strm; +const Bytef *dictionary; +uInt dictLength; +{ + struct inflate_state FAR *state; + unsigned long id; + + /* check state */ + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + if (state->wrap != 0 && state->mode != DICT) + return Z_STREAM_ERROR; + + /* check for correct dictionary id */ + if (state->mode == DICT) { + id = adler32(0L, Z_NULL, 0); + id = adler32(id, dictionary, dictLength); + if (id != state->check) + return Z_DATA_ERROR; + } + + /* copy dictionary to window */ + if (updatewindow(strm, strm->avail_out)) { + state->mode = MEM; + return Z_MEM_ERROR; + } + if (dictLength > state->wsize) { + zmemcpy(state->window, dictionary + dictLength - state->wsize, + state->wsize); + state->whave = state->wsize; + } + else { + zmemcpy(state->window + state->wsize - dictLength, dictionary, + dictLength); + state->whave = dictLength; + } + state->havedict = 1; + Tracev((stderr, "inflate: dictionary set\n")); + return Z_OK; +} + +int ZEXPORT inflateGetHeader(strm, head) +z_streamp strm; +gz_headerp head; +{ + struct inflate_state FAR *state; + + /* check state */ + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + if ((state->wrap & 2) == 0) return Z_STREAM_ERROR; + + /* save header structure */ + state->head = head; + head->done = 0; + return Z_OK; +} + +/* + Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff. Return when found + or when out of input. When called, *have is the number of pattern bytes + found in order so far, in 0..3. On return *have is updated to the new + state. If on return *have equals four, then the pattern was found and the + return value is how many bytes were read including the last byte of the + pattern. If *have is less than four, then the pattern has not been found + yet and the return value is len. In the latter case, syncsearch() can be + called again with more data and the *have state. *have is initialized to + zero for the first call. + */ +local unsigned syncsearch(have, buf, len) +unsigned FAR *have; +unsigned char FAR *buf; +unsigned len; +{ + unsigned got; + unsigned next; + + got = *have; + next = 0; + while (next < len && got < 4) { + if ((int)(buf[next]) == (got < 2 ? 0 : 0xff)) + got++; + else if (buf[next]) + got = 0; + else + got = 4 - got; + next++; + } + *have = got; + return next; +} + +int ZEXPORT inflateSync(strm) +z_streamp strm; +{ + unsigned len; /* number of bytes to look at or looked at */ + unsigned long in, out; /* temporary to save total_in and total_out */ + unsigned char buf[4]; /* to restore bit buffer to byte string */ + struct inflate_state FAR *state; + + /* check parameters */ + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR; + + /* if first time, start search in bit buffer */ + if (state->mode != SYNC) { + state->mode = SYNC; + state->hold <<= state->bits & 7; + state->bits -= state->bits & 7; + len = 0; + while (state->bits >= 8) { + buf[len++] = (unsigned char)(state->hold); + state->hold >>= 8; + state->bits -= 8; + } + state->have = 0; + syncsearch(&(state->have), buf, len); + } + + /* search available input */ + len = syncsearch(&(state->have), strm->next_in, strm->avail_in); + strm->avail_in -= len; + strm->next_in += len; + strm->total_in += len; + + /* return no joy or set up to restart inflate() on a new block */ + if (state->have != 4) return Z_DATA_ERROR; + in = strm->total_in; out = strm->total_out; + inflateReset(strm); + strm->total_in = in; strm->total_out = out; + state->mode = TYPE; + return Z_OK; +} + +/* + Returns true if inflate is currently at the end of a block generated by + Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP + implementation to provide an additional safety check. PPP uses + Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored + block. When decompressing, PPP checks that at the end of input packet, + inflate is waiting for these length bytes. + */ +int ZEXPORT inflateSyncPoint(strm) +z_streamp strm; +{ + struct inflate_state FAR *state; + + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + return state->mode == STORED && state->bits == 0; +} + +int ZEXPORT inflateCopy(dest, source) +z_streamp dest; +z_streamp source; +{ + struct inflate_state FAR *state; + struct inflate_state FAR *copy; + unsigned char FAR *window; + unsigned wsize; + + /* check input */ + if (dest == Z_NULL || source == Z_NULL || source->state == Z_NULL || + source->zalloc == (alloc_func)0 || source->zfree == (free_func)0) + return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)source->state; + + /* allocate space */ + copy = (struct inflate_state FAR *) + ZALLOC(source, 1, sizeof(struct inflate_state)); + if (copy == Z_NULL) return Z_MEM_ERROR; + window = Z_NULL; + if (state->window != Z_NULL) { + window = (unsigned char FAR *) + ZALLOC(source, 1U << state->wbits, sizeof(unsigned char)); + if (window == Z_NULL) { + ZFREE(source, copy); + return Z_MEM_ERROR; + } + } + + /* copy state */ + zmemcpy(dest, source, sizeof(z_stream)); + zmemcpy(copy, state, sizeof(struct inflate_state)); + if (state->lencode >= state->codes && + state->lencode <= state->codes + ENOUGH - 1) { + copy->lencode = copy->codes + (state->lencode - state->codes); + copy->distcode = copy->codes + (state->distcode - state->codes); + } + copy->next = copy->codes + (state->next - state->codes); + if (window != Z_NULL) { + wsize = 1U << state->wbits; + zmemcpy(window, state->window, wsize); + } + copy->window = window; + dest->state = (struct internal_state FAR *)copy; + return Z_OK; +} diff --git a/Foundation/src/inflate.h b/Foundation/src/inflate.h index fbbc87143..07bd3e78a 100644 --- a/Foundation/src/inflate.h +++ b/Foundation/src/inflate.h @@ -1,115 +1,115 @@ -/* inflate.h -- internal inflate state definition - * Copyright (C) 1995-2004 Mark Adler - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -/* WARNING: this file should *not* be used by applications. It is - part of the implementation of the compression library and is - subject to change. Applications should only use zlib.h. - */ - -/* define NO_GZIP when compiling if you want to disable gzip header and - trailer decoding by inflate(). NO_GZIP would be used to avoid linking in - the crc code when it is not needed. For shared libraries, gzip decoding - should be left enabled. */ -#ifndef NO_GZIP -# define GUNZIP -#endif - -/* Possible inflate modes between inflate() calls */ -typedef enum { - HEAD, /* i: waiting for magic header */ - FLAGS, /* i: waiting for method and flags (gzip) */ - TIME, /* i: waiting for modification time (gzip) */ - OS, /* i: waiting for extra flags and operating system (gzip) */ - EXLEN, /* i: waiting for extra length (gzip) */ - EXTRA, /* i: waiting for extra bytes (gzip) */ - NAME, /* i: waiting for end of file name (gzip) */ - COMMENT, /* i: waiting for end of comment (gzip) */ - HCRC, /* i: waiting for header crc (gzip) */ - DICTID, /* i: waiting for dictionary check value */ - DICT, /* waiting for inflateSetDictionary() call */ - TYPE, /* i: waiting for type bits, including last-flag bit */ - TYPEDO, /* i: same, but skip check to exit inflate on new block */ - STORED, /* i: waiting for stored size (length and complement) */ - COPY, /* i/o: waiting for input or output to copy stored block */ - TABLE, /* i: waiting for dynamic block table lengths */ - LENLENS, /* i: waiting for code length code lengths */ - CODELENS, /* i: waiting for length/lit and distance code lengths */ - LEN, /* i: waiting for length/lit code */ - LENEXT, /* i: waiting for length extra bits */ - DIST, /* i: waiting for distance code */ - DISTEXT, /* i: waiting for distance extra bits */ - MATCH, /* o: waiting for output space to copy string */ - LIT, /* o: waiting for output space to write literal */ - CHECK, /* i: waiting for 32-bit check value */ - LENGTH, /* i: waiting for 32-bit length (gzip) */ - DONE, /* finished check, done -- remain here until reset */ - BAD, /* got a data error -- remain here until reset */ - MEM, /* got an inflate() memory error -- remain here until reset */ - SYNC /* looking for synchronization bytes to restart inflate() */ -} inflate_mode; - -/* - State transitions between above modes - - - (most modes can go to the BAD or MEM mode -- not shown for clarity) - - Process header: - HEAD -> (gzip) or (zlib) - (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME - NAME -> COMMENT -> HCRC -> TYPE - (zlib) -> DICTID or TYPE - DICTID -> DICT -> TYPE - Read deflate blocks: - TYPE -> STORED or TABLE or LEN or CHECK - STORED -> COPY -> TYPE - TABLE -> LENLENS -> CODELENS -> LEN - Read deflate codes: - LEN -> LENEXT or LIT or TYPE - LENEXT -> DIST -> DISTEXT -> MATCH -> LEN - LIT -> LEN - Process trailer: - CHECK -> LENGTH -> DONE - */ - -/* state maintained between inflate() calls. Approximately 7K bytes. */ -struct inflate_state { - inflate_mode mode; /* current inflate mode */ - int last; /* true if processing last block */ - int wrap; /* bit 0 true for zlib, bit 1 true for gzip */ - int havedict; /* true if dictionary provided */ - int flags; /* gzip header method and flags (0 if zlib) */ - unsigned dmax; /* zlib header max distance (INFLATE_STRICT) */ - unsigned long check; /* protected copy of check value */ - unsigned long total; /* protected copy of output count */ - gz_headerp head; /* where to save gzip header information */ - /* sliding window */ - unsigned wbits; /* log base 2 of requested window size */ - unsigned wsize; /* window size or zero if not using window */ - unsigned whave; /* valid bytes in the window */ - unsigned write; /* window write index */ - unsigned char FAR *window; /* allocated sliding window, if needed */ - /* bit accumulator */ - unsigned long hold; /* input bit accumulator */ - unsigned bits; /* number of bits in "in" */ - /* for string and stored block copying */ - unsigned length; /* literal or length of data to copy */ - unsigned offset; /* distance back to copy string from */ - /* for table and code decoding */ - unsigned extra; /* extra bits needed */ - /* fixed and dynamic code tables */ - code const FAR *lencode; /* starting table for length/literal codes */ - code const FAR *distcode; /* starting table for distance codes */ - unsigned lenbits; /* index bits for lencode */ - unsigned distbits; /* index bits for distcode */ - /* dynamic table building */ - unsigned ncode; /* number of code length code lengths */ - unsigned nlen; /* number of length code lengths */ - unsigned ndist; /* number of distance code lengths */ - unsigned have; /* number of code lengths in lens[] */ - code FAR *next; /* next available space in codes[] */ - unsigned short lens[320]; /* temporary storage for code lengths */ - unsigned short work[288]; /* work area for code table building */ - code codes[ENOUGH]; /* space for code tables */ -}; +/* inflate.h -- internal inflate state definition + * Copyright (C) 1995-2004 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* WARNING: this file should *not* be used by applications. It is + part of the implementation of the compression library and is + subject to change. Applications should only use zlib.h. + */ + +/* define NO_GZIP when compiling if you want to disable gzip header and + trailer decoding by inflate(). NO_GZIP would be used to avoid linking in + the crc code when it is not needed. For shared libraries, gzip decoding + should be left enabled. */ +#ifndef NO_GZIP +# define GUNZIP +#endif + +/* Possible inflate modes between inflate() calls */ +typedef enum { + HEAD, /* i: waiting for magic header */ + FLAGS, /* i: waiting for method and flags (gzip) */ + TIME, /* i: waiting for modification time (gzip) */ + OS, /* i: waiting for extra flags and operating system (gzip) */ + EXLEN, /* i: waiting for extra length (gzip) */ + EXTRA, /* i: waiting for extra bytes (gzip) */ + NAME, /* i: waiting for end of file name (gzip) */ + COMMENT, /* i: waiting for end of comment (gzip) */ + HCRC, /* i: waiting for header crc (gzip) */ + DICTID, /* i: waiting for dictionary check value */ + DICT, /* waiting for inflateSetDictionary() call */ + TYPE, /* i: waiting for type bits, including last-flag bit */ + TYPEDO, /* i: same, but skip check to exit inflate on new block */ + STORED, /* i: waiting for stored size (length and complement) */ + COPY, /* i/o: waiting for input or output to copy stored block */ + TABLE, /* i: waiting for dynamic block table lengths */ + LENLENS, /* i: waiting for code length code lengths */ + CODELENS, /* i: waiting for length/lit and distance code lengths */ + LEN, /* i: waiting for length/lit code */ + LENEXT, /* i: waiting for length extra bits */ + DIST, /* i: waiting for distance code */ + DISTEXT, /* i: waiting for distance extra bits */ + MATCH, /* o: waiting for output space to copy string */ + LIT, /* o: waiting for output space to write literal */ + CHECK, /* i: waiting for 32-bit check value */ + LENGTH, /* i: waiting for 32-bit length (gzip) */ + DONE, /* finished check, done -- remain here until reset */ + BAD, /* got a data error -- remain here until reset */ + MEM, /* got an inflate() memory error -- remain here until reset */ + SYNC /* looking for synchronization bytes to restart inflate() */ +} inflate_mode; + +/* + State transitions between above modes - + + (most modes can go to the BAD or MEM mode -- not shown for clarity) + + Process header: + HEAD -> (gzip) or (zlib) + (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME + NAME -> COMMENT -> HCRC -> TYPE + (zlib) -> DICTID or TYPE + DICTID -> DICT -> TYPE + Read deflate blocks: + TYPE -> STORED or TABLE or LEN or CHECK + STORED -> COPY -> TYPE + TABLE -> LENLENS -> CODELENS -> LEN + Read deflate codes: + LEN -> LENEXT or LIT or TYPE + LENEXT -> DIST -> DISTEXT -> MATCH -> LEN + LIT -> LEN + Process trailer: + CHECK -> LENGTH -> DONE + */ + +/* state maintained between inflate() calls. Approximately 7K bytes. */ +struct inflate_state { + inflate_mode mode; /* current inflate mode */ + int last; /* true if processing last block */ + int wrap; /* bit 0 true for zlib, bit 1 true for gzip */ + int havedict; /* true if dictionary provided */ + int flags; /* gzip header method and flags (0 if zlib) */ + unsigned dmax; /* zlib header max distance (INFLATE_STRICT) */ + unsigned long check; /* protected copy of check value */ + unsigned long total; /* protected copy of output count */ + gz_headerp head; /* where to save gzip header information */ + /* sliding window */ + unsigned wbits; /* log base 2 of requested window size */ + unsigned wsize; /* window size or zero if not using window */ + unsigned whave; /* valid bytes in the window */ + unsigned write; /* window write index */ + unsigned char FAR *window; /* allocated sliding window, if needed */ + /* bit accumulator */ + unsigned long hold; /* input bit accumulator */ + unsigned bits; /* number of bits in "in" */ + /* for string and stored block copying */ + unsigned length; /* literal or length of data to copy */ + unsigned offset; /* distance back to copy string from */ + /* for table and code decoding */ + unsigned extra; /* extra bits needed */ + /* fixed and dynamic code tables */ + code const FAR *lencode; /* starting table for length/literal codes */ + code const FAR *distcode; /* starting table for distance codes */ + unsigned lenbits; /* index bits for lencode */ + unsigned distbits; /* index bits for distcode */ + /* dynamic table building */ + unsigned ncode; /* number of code length code lengths */ + unsigned nlen; /* number of length code lengths */ + unsigned ndist; /* number of distance code lengths */ + unsigned have; /* number of code lengths in lens[] */ + code FAR *next; /* next available space in codes[] */ + unsigned short lens[320]; /* temporary storage for code lengths */ + unsigned short work[288]; /* work area for code table building */ + code codes[ENOUGH]; /* space for code tables */ +}; diff --git a/Foundation/src/inftrees.c b/Foundation/src/inftrees.c index 38ded81c3..8a9c13ff0 100644 --- a/Foundation/src/inftrees.c +++ b/Foundation/src/inftrees.c @@ -1,329 +1,329 @@ -/* inftrees.c -- generate Huffman trees for efficient decoding - * Copyright (C) 1995-2005 Mark Adler - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -#include "zutil.h" -#include "inftrees.h" - -#define MAXBITS 15 - -const char inflate_copyright[] = - " inflate 1.2.3 Copyright 1995-2005 Mark Adler "; -/* - If you use the zlib library in a product, an acknowledgment is welcome - in the documentation of your product. If for some reason you cannot - include such an acknowledgment, I would appreciate that you keep this - copyright string in the executable of your product. - */ - -/* - Build a set of tables to decode the provided canonical Huffman code. - The code lengths are lens[0..codes-1]. The result starts at *table, - whose indices are 0..2^bits-1. work is a writable array of at least - lens shorts, which is used as a work area. type is the type of code - to be generated, CODES, LENS, or DISTS. On return, zero is success, - -1 is an invalid code, and +1 means that ENOUGH isn't enough. table - on return points to the next available entry's address. bits is the - requested root table index bits, and on return it is the actual root - table index bits. It will differ if the request is greater than the - longest code or if it is less than the shortest code. - */ -int inflate_table(type, lens, codes, table, bits, work) -codetype type; -unsigned short FAR *lens; -unsigned codes; -code FAR * FAR *table; -unsigned FAR *bits; -unsigned short FAR *work; -{ - unsigned len; /* a code's length in bits */ - unsigned sym; /* index of code symbols */ - unsigned min, max; /* minimum and maximum code lengths */ - unsigned root; /* number of index bits for root table */ - unsigned curr; /* number of index bits for current table */ - unsigned drop; /* code bits to drop for sub-table */ - int left; /* number of prefix codes available */ - unsigned used; /* code entries in table used */ - unsigned huff; /* Huffman code */ - unsigned incr; /* for incrementing code, index */ - unsigned fill; /* index for replicating entries */ - unsigned low; /* low bits for current root entry */ - unsigned mask; /* mask for low root bits */ - code this; /* table entry for duplication */ - code FAR *next; /* next available space in table */ - const unsigned short FAR *base; /* base value table to use */ - const unsigned short FAR *extra; /* extra bits table to use */ - int end; /* use base and extra for symbol > end */ - unsigned short count[MAXBITS+1]; /* number of codes of each length */ - unsigned short offs[MAXBITS+1]; /* offsets in table for each length */ - static const unsigned short lbase[31] = { /* Length codes 257..285 base */ - 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, - 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0}; - static const unsigned short lext[31] = { /* Length codes 257..285 extra */ - 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, - 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 201, 196}; - static const unsigned short dbase[32] = { /* Distance codes 0..29 base */ - 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, - 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, - 8193, 12289, 16385, 24577, 0, 0}; - static const unsigned short dext[32] = { /* Distance codes 0..29 extra */ - 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, - 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, - 28, 28, 29, 29, 64, 64}; - - /* - Process a set of code lengths to create a canonical Huffman code. The - code lengths are lens[0..codes-1]. Each length corresponds to the - symbols 0..codes-1. The Huffman code is generated by first sorting the - symbols by length from short to long, and retaining the symbol order - for codes with equal lengths. Then the code starts with all zero bits - for the first code of the shortest length, and the codes are integer - increments for the same length, and zeros are appended as the length - increases. For the deflate format, these bits are stored backwards - from their more natural integer increment ordering, and so when the - decoding tables are built in the large loop below, the integer codes - are incremented backwards. - - This routine assumes, but does not check, that all of the entries in - lens[] are in the range 0..MAXBITS. The caller must assure this. - 1..MAXBITS is interpreted as that code length. zero means that that - symbol does not occur in this code. - - The codes are sorted by computing a count of codes for each length, - creating from that a table of starting indices for each length in the - sorted table, and then entering the symbols in order in the sorted - table. The sorted table is work[], with that space being provided by - the caller. - - The length counts are used for other purposes as well, i.e. finding - the minimum and maximum length codes, determining if there are any - codes at all, checking for a valid set of lengths, and looking ahead - at length counts to determine sub-table sizes when building the - decoding tables. - */ - - /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */ - for (len = 0; len <= MAXBITS; len++) - count[len] = 0; - for (sym = 0; sym < codes; sym++) - count[lens[sym]]++; - - /* bound code lengths, force root to be within code lengths */ - root = *bits; - for (max = MAXBITS; max >= 1; max--) - if (count[max] != 0) break; - if (root > max) root = max; - if (max == 0) { /* no symbols to code at all */ - this.op = (unsigned char)64; /* invalid code marker */ - this.bits = (unsigned char)1; - this.val = (unsigned short)0; - *(*table)++ = this; /* make a table to force an error */ - *(*table)++ = this; - *bits = 1; - return 0; /* no symbols, but wait for decoding to report error */ - } - for (min = 1; min <= MAXBITS; min++) - if (count[min] != 0) break; - if (root < min) root = min; - - /* check for an over-subscribed or incomplete set of lengths */ - left = 1; - for (len = 1; len <= MAXBITS; len++) { - left <<= 1; - left -= count[len]; - if (left < 0) return -1; /* over-subscribed */ - } - if (left > 0 && (type == CODES || max != 1)) - return -1; /* incomplete set */ - - /* generate offsets into symbol table for each length for sorting */ - offs[1] = 0; - for (len = 1; len < MAXBITS; len++) - offs[len + 1] = offs[len] + count[len]; - - /* sort symbols by length, by symbol order within each length */ - for (sym = 0; sym < codes; sym++) - if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym; - - /* - Create and fill in decoding tables. In this loop, the table being - filled is at next and has curr index bits. The code being used is huff - with length len. That code is converted to an index by dropping drop - bits off of the bottom. For codes where len is less than drop + curr, - those top drop + curr - len bits are incremented through all values to - fill the table with replicated entries. - - root is the number of index bits for the root table. When len exceeds - root, sub-tables are created pointed to by the root entry with an index - of the low root bits of huff. This is saved in low to check for when a - new sub-table should be started. drop is zero when the root table is - being filled, and drop is root when sub-tables are being filled. - - When a new sub-table is needed, it is necessary to look ahead in the - code lengths to determine what size sub-table is needed. The length - counts are used for this, and so count[] is decremented as codes are - entered in the tables. - - used keeps track of how many table entries have been allocated from the - provided *table space. It is checked when a LENS table is being made - against the space in *table, ENOUGH, minus the maximum space needed by - the worst case distance code, MAXD. This should never happen, but the - sufficiency of ENOUGH has not been proven exhaustively, hence the check. - This assumes that when type == LENS, bits == 9. - - sym increments through all symbols, and the loop terminates when - all codes of length max, i.e. all codes, have been processed. This - routine permits incomplete codes, so another loop after this one fills - in the rest of the decoding tables with invalid code markers. - */ - - /* set up for code type */ - switch (type) { - case CODES: - base = extra = work; /* dummy value--not used */ - end = 19; - break; - case LENS: - base = lbase; - base -= 257; - extra = lext; - extra -= 257; - end = 256; - break; - default: /* DISTS */ - base = dbase; - extra = dext; - end = -1; - } - - /* initialize state for loop */ - huff = 0; /* starting code */ - sym = 0; /* starting code symbol */ - len = min; /* starting code length */ - next = *table; /* current table to fill in */ - curr = root; /* current table index bits */ - drop = 0; /* current bits to drop from code for index */ - low = (unsigned)(-1); /* trigger new sub-table when len > root */ - used = 1U << root; /* use root table entries */ - mask = used - 1; /* mask for comparing low */ - - /* check available table space */ - if (type == LENS && used >= ENOUGH - MAXD) - return 1; - - /* process all codes and make table entries */ - for (;;) { - /* create table entry */ - this.bits = (unsigned char)(len - drop); - if ((int)(work[sym]) < end) { - this.op = (unsigned char)0; - this.val = work[sym]; - } - else if ((int)(work[sym]) > end) { - this.op = (unsigned char)(extra[work[sym]]); - this.val = base[work[sym]]; - } - else { - this.op = (unsigned char)(32 + 64); /* end of block */ - this.val = 0; - } - - /* replicate for those indices with low len bits equal to huff */ - incr = 1U << (len - drop); - fill = 1U << curr; - min = fill; /* save offset to next table */ - do { - fill -= incr; - next[(huff >> drop) + fill] = this; - } while (fill != 0); - - /* backwards increment the len-bit code huff */ - incr = 1U << (len - 1); - while (huff & incr) - incr >>= 1; - if (incr != 0) { - huff &= incr - 1; - huff += incr; - } - else - huff = 0; - - /* go to next symbol, update count, len */ - sym++; - if (--(count[len]) == 0) { - if (len == max) break; - len = lens[work[sym]]; - } - - /* create new sub-table if needed */ - if (len > root && (huff & mask) != low) { - /* if first time, transition to sub-tables */ - if (drop == 0) - drop = root; - - /* increment past last table */ - next += min; /* here min is 1 << curr */ - - /* determine length of next table */ - curr = len - drop; - left = (int)(1 << curr); - while (curr + drop < max) { - left -= count[curr + drop]; - if (left <= 0) break; - curr++; - left <<= 1; - } - - /* check for enough space */ - used += 1U << curr; - if (type == LENS && used >= ENOUGH - MAXD) - return 1; - - /* point entry in root table to sub-table */ - low = huff & mask; - (*table)[low].op = (unsigned char)curr; - (*table)[low].bits = (unsigned char)root; - (*table)[low].val = (unsigned short)(next - *table); - } - } - - /* - Fill in rest of table for incomplete codes. This loop is similar to the - loop above in incrementing huff for table indices. It is assumed that - len is equal to curr + drop, so there is no loop needed to increment - through high index bits. When the current sub-table is filled, the loop - drops back to the root table to fill in any remaining entries there. - */ - this.op = (unsigned char)64; /* invalid code marker */ - this.bits = (unsigned char)(len - drop); - this.val = (unsigned short)0; - while (huff != 0) { - /* when done with sub-table, drop back to root table */ - if (drop != 0 && (huff & mask) != low) { - drop = 0; - len = root; - next = *table; - this.bits = (unsigned char)len; - } - - /* put invalid code marker in table */ - next[huff >> drop] = this; - - /* backwards increment the len-bit code huff */ - incr = 1U << (len - 1); - while (huff & incr) - incr >>= 1; - if (incr != 0) { - huff &= incr - 1; - huff += incr; - } - else - huff = 0; - } - - /* set return parameters */ - *table += used; - *bits = root; - return 0; -} +/* inftrees.c -- generate Huffman trees for efficient decoding + * Copyright (C) 1995-2005 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +#include "zutil.h" +#include "inftrees.h" + +#define MAXBITS 15 + +const char inflate_copyright[] = + " inflate 1.2.3 Copyright 1995-2005 Mark Adler "; +/* + If you use the zlib library in a product, an acknowledgment is welcome + in the documentation of your product. If for some reason you cannot + include such an acknowledgment, I would appreciate that you keep this + copyright string in the executable of your product. + */ + +/* + Build a set of tables to decode the provided canonical Huffman code. + The code lengths are lens[0..codes-1]. The result starts at *table, + whose indices are 0..2^bits-1. work is a writable array of at least + lens shorts, which is used as a work area. type is the type of code + to be generated, CODES, LENS, or DISTS. On return, zero is success, + -1 is an invalid code, and +1 means that ENOUGH isn't enough. table + on return points to the next available entry's address. bits is the + requested root table index bits, and on return it is the actual root + table index bits. It will differ if the request is greater than the + longest code or if it is less than the shortest code. + */ +int inflate_table(type, lens, codes, table, bits, work) +codetype type; +unsigned short FAR *lens; +unsigned codes; +code FAR * FAR *table; +unsigned FAR *bits; +unsigned short FAR *work; +{ + unsigned len; /* a code's length in bits */ + unsigned sym; /* index of code symbols */ + unsigned min, max; /* minimum and maximum code lengths */ + unsigned root; /* number of index bits for root table */ + unsigned curr; /* number of index bits for current table */ + unsigned drop; /* code bits to drop for sub-table */ + int left; /* number of prefix codes available */ + unsigned used; /* code entries in table used */ + unsigned huff; /* Huffman code */ + unsigned incr; /* for incrementing code, index */ + unsigned fill; /* index for replicating entries */ + unsigned low; /* low bits for current root entry */ + unsigned mask; /* mask for low root bits */ + code this; /* table entry for duplication */ + code FAR *next; /* next available space in table */ + const unsigned short FAR *base; /* base value table to use */ + const unsigned short FAR *extra; /* extra bits table to use */ + int end; /* use base and extra for symbol > end */ + unsigned short count[MAXBITS+1]; /* number of codes of each length */ + unsigned short offs[MAXBITS+1]; /* offsets in table for each length */ + static const unsigned short lbase[31] = { /* Length codes 257..285 base */ + 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, + 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0}; + static const unsigned short lext[31] = { /* Length codes 257..285 extra */ + 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, + 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 201, 196}; + static const unsigned short dbase[32] = { /* Distance codes 0..29 base */ + 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, + 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, + 8193, 12289, 16385, 24577, 0, 0}; + static const unsigned short dext[32] = { /* Distance codes 0..29 extra */ + 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, + 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, + 28, 28, 29, 29, 64, 64}; + + /* + Process a set of code lengths to create a canonical Huffman code. The + code lengths are lens[0..codes-1]. Each length corresponds to the + symbols 0..codes-1. The Huffman code is generated by first sorting the + symbols by length from short to long, and retaining the symbol order + for codes with equal lengths. Then the code starts with all zero bits + for the first code of the shortest length, and the codes are integer + increments for the same length, and zeros are appended as the length + increases. For the deflate format, these bits are stored backwards + from their more natural integer increment ordering, and so when the + decoding tables are built in the large loop below, the integer codes + are incremented backwards. + + This routine assumes, but does not check, that all of the entries in + lens[] are in the range 0..MAXBITS. The caller must assure this. + 1..MAXBITS is interpreted as that code length. zero means that that + symbol does not occur in this code. + + The codes are sorted by computing a count of codes for each length, + creating from that a table of starting indices for each length in the + sorted table, and then entering the symbols in order in the sorted + table. The sorted table is work[], with that space being provided by + the caller. + + The length counts are used for other purposes as well, i.e. finding + the minimum and maximum length codes, determining if there are any + codes at all, checking for a valid set of lengths, and looking ahead + at length counts to determine sub-table sizes when building the + decoding tables. + */ + + /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */ + for (len = 0; len <= MAXBITS; len++) + count[len] = 0; + for (sym = 0; sym < codes; sym++) + count[lens[sym]]++; + + /* bound code lengths, force root to be within code lengths */ + root = *bits; + for (max = MAXBITS; max >= 1; max--) + if (count[max] != 0) break; + if (root > max) root = max; + if (max == 0) { /* no symbols to code at all */ + this.op = (unsigned char)64; /* invalid code marker */ + this.bits = (unsigned char)1; + this.val = (unsigned short)0; + *(*table)++ = this; /* make a table to force an error */ + *(*table)++ = this; + *bits = 1; + return 0; /* no symbols, but wait for decoding to report error */ + } + for (min = 1; min <= MAXBITS; min++) + if (count[min] != 0) break; + if (root < min) root = min; + + /* check for an over-subscribed or incomplete set of lengths */ + left = 1; + for (len = 1; len <= MAXBITS; len++) { + left <<= 1; + left -= count[len]; + if (left < 0) return -1; /* over-subscribed */ + } + if (left > 0 && (type == CODES || max != 1)) + return -1; /* incomplete set */ + + /* generate offsets into symbol table for each length for sorting */ + offs[1] = 0; + for (len = 1; len < MAXBITS; len++) + offs[len + 1] = offs[len] + count[len]; + + /* sort symbols by length, by symbol order within each length */ + for (sym = 0; sym < codes; sym++) + if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym; + + /* + Create and fill in decoding tables. In this loop, the table being + filled is at next and has curr index bits. The code being used is huff + with length len. That code is converted to an index by dropping drop + bits off of the bottom. For codes where len is less than drop + curr, + those top drop + curr - len bits are incremented through all values to + fill the table with replicated entries. + + root is the number of index bits for the root table. When len exceeds + root, sub-tables are created pointed to by the root entry with an index + of the low root bits of huff. This is saved in low to check for when a + new sub-table should be started. drop is zero when the root table is + being filled, and drop is root when sub-tables are being filled. + + When a new sub-table is needed, it is necessary to look ahead in the + code lengths to determine what size sub-table is needed. The length + counts are used for this, and so count[] is decremented as codes are + entered in the tables. + + used keeps track of how many table entries have been allocated from the + provided *table space. It is checked when a LENS table is being made + against the space in *table, ENOUGH, minus the maximum space needed by + the worst case distance code, MAXD. This should never happen, but the + sufficiency of ENOUGH has not been proven exhaustively, hence the check. + This assumes that when type == LENS, bits == 9. + + sym increments through all symbols, and the loop terminates when + all codes of length max, i.e. all codes, have been processed. This + routine permits incomplete codes, so another loop after this one fills + in the rest of the decoding tables with invalid code markers. + */ + + /* set up for code type */ + switch (type) { + case CODES: + base = extra = work; /* dummy value--not used */ + end = 19; + break; + case LENS: + base = lbase; + base -= 257; + extra = lext; + extra -= 257; + end = 256; + break; + default: /* DISTS */ + base = dbase; + extra = dext; + end = -1; + } + + /* initialize state for loop */ + huff = 0; /* starting code */ + sym = 0; /* starting code symbol */ + len = min; /* starting code length */ + next = *table; /* current table to fill in */ + curr = root; /* current table index bits */ + drop = 0; /* current bits to drop from code for index */ + low = (unsigned)(-1); /* trigger new sub-table when len > root */ + used = 1U << root; /* use root table entries */ + mask = used - 1; /* mask for comparing low */ + + /* check available table space */ + if (type == LENS && used >= ENOUGH - MAXD) + return 1; + + /* process all codes and make table entries */ + for (;;) { + /* create table entry */ + this.bits = (unsigned char)(len - drop); + if ((int)(work[sym]) < end) { + this.op = (unsigned char)0; + this.val = work[sym]; + } + else if ((int)(work[sym]) > end) { + this.op = (unsigned char)(extra[work[sym]]); + this.val = base[work[sym]]; + } + else { + this.op = (unsigned char)(32 + 64); /* end of block */ + this.val = 0; + } + + /* replicate for those indices with low len bits equal to huff */ + incr = 1U << (len - drop); + fill = 1U << curr; + min = fill; /* save offset to next table */ + do { + fill -= incr; + next[(huff >> drop) + fill] = this; + } while (fill != 0); + + /* backwards increment the len-bit code huff */ + incr = 1U << (len - 1); + while (huff & incr) + incr >>= 1; + if (incr != 0) { + huff &= incr - 1; + huff += incr; + } + else + huff = 0; + + /* go to next symbol, update count, len */ + sym++; + if (--(count[len]) == 0) { + if (len == max) break; + len = lens[work[sym]]; + } + + /* create new sub-table if needed */ + if (len > root && (huff & mask) != low) { + /* if first time, transition to sub-tables */ + if (drop == 0) + drop = root; + + /* increment past last table */ + next += min; /* here min is 1 << curr */ + + /* determine length of next table */ + curr = len - drop; + left = (int)(1 << curr); + while (curr + drop < max) { + left -= count[curr + drop]; + if (left <= 0) break; + curr++; + left <<= 1; + } + + /* check for enough space */ + used += 1U << curr; + if (type == LENS && used >= ENOUGH - MAXD) + return 1; + + /* point entry in root table to sub-table */ + low = huff & mask; + (*table)[low].op = (unsigned char)curr; + (*table)[low].bits = (unsigned char)root; + (*table)[low].val = (unsigned short)(next - *table); + } + } + + /* + Fill in rest of table for incomplete codes. This loop is similar to the + loop above in incrementing huff for table indices. It is assumed that + len is equal to curr + drop, so there is no loop needed to increment + through high index bits. When the current sub-table is filled, the loop + drops back to the root table to fill in any remaining entries there. + */ + this.op = (unsigned char)64; /* invalid code marker */ + this.bits = (unsigned char)(len - drop); + this.val = (unsigned short)0; + while (huff != 0) { + /* when done with sub-table, drop back to root table */ + if (drop != 0 && (huff & mask) != low) { + drop = 0; + len = root; + next = *table; + this.bits = (unsigned char)len; + } + + /* put invalid code marker in table */ + next[huff >> drop] = this; + + /* backwards increment the len-bit code huff */ + incr = 1U << (len - 1); + while (huff & incr) + incr >>= 1; + if (incr != 0) { + huff &= incr - 1; + huff += incr; + } + else + huff = 0; + } + + /* set return parameters */ + *table += used; + *bits = root; + return 0; +} diff --git a/Foundation/src/inftrees.h b/Foundation/src/inftrees.h index dc0fd567e..b1104c87e 100644 --- a/Foundation/src/inftrees.h +++ b/Foundation/src/inftrees.h @@ -1,55 +1,55 @@ -/* inftrees.h -- header to use inftrees.c - * Copyright (C) 1995-2005 Mark Adler - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -/* WARNING: this file should *not* be used by applications. It is - part of the implementation of the compression library and is - subject to change. Applications should only use zlib.h. - */ - -/* Structure for decoding tables. Each entry provides either the - information needed to do the operation requested by the code that - indexed that table entry, or it provides a pointer to another - table that indexes more bits of the code. op indicates whether - the entry is a pointer to another table, a literal, a length or - distance, an end-of-block, or an invalid code. For a table - pointer, the low four bits of op is the number of index bits of - that table. For a length or distance, the low four bits of op - is the number of extra bits to get after the code. bits is - the number of bits in this code or part of the code to drop off - of the bit buffer. val is the actual byte to output in the case - of a literal, the base length or distance, or the offset from - the current table to the next table. Each entry is four bytes. */ -typedef struct { - unsigned char op; /* operation, extra bits, table bits */ - unsigned char bits; /* bits in this part of the code */ - unsigned short val; /* offset in table or code value */ -} code; - -/* op values as set by inflate_table(): - 00000000 - literal - 0000tttt - table link, tttt != 0 is the number of table index bits - 0001eeee - length or distance, eeee is the number of extra bits - 01100000 - end of block - 01000000 - invalid code - */ - -/* Maximum size of dynamic tree. The maximum found in a long but non- - exhaustive search was 1444 code structures (852 for length/literals - and 592 for distances, the latter actually the result of an - exhaustive search). The true maximum is not known, but the value - below is more than safe. */ -#define ENOUGH 2048 -#define MAXD 592 - -/* Type of code to build for inftable() */ -typedef enum { - CODES, - LENS, - DISTS -} codetype; - -extern int inflate_table OF((codetype type, unsigned short FAR *lens, - unsigned codes, code FAR * FAR *table, - unsigned FAR *bits, unsigned short FAR *work)); +/* inftrees.h -- header to use inftrees.c + * Copyright (C) 1995-2005 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* WARNING: this file should *not* be used by applications. It is + part of the implementation of the compression library and is + subject to change. Applications should only use zlib.h. + */ + +/* Structure for decoding tables. Each entry provides either the + information needed to do the operation requested by the code that + indexed that table entry, or it provides a pointer to another + table that indexes more bits of the code. op indicates whether + the entry is a pointer to another table, a literal, a length or + distance, an end-of-block, or an invalid code. For a table + pointer, the low four bits of op is the number of index bits of + that table. For a length or distance, the low four bits of op + is the number of extra bits to get after the code. bits is + the number of bits in this code or part of the code to drop off + of the bit buffer. val is the actual byte to output in the case + of a literal, the base length or distance, or the offset from + the current table to the next table. Each entry is four bytes. */ +typedef struct { + unsigned char op; /* operation, extra bits, table bits */ + unsigned char bits; /* bits in this part of the code */ + unsigned short val; /* offset in table or code value */ +} code; + +/* op values as set by inflate_table(): + 00000000 - literal + 0000tttt - table link, tttt != 0 is the number of table index bits + 0001eeee - length or distance, eeee is the number of extra bits + 01100000 - end of block + 01000000 - invalid code + */ + +/* Maximum size of dynamic tree. The maximum found in a long but non- + exhaustive search was 1444 code structures (852 for length/literals + and 592 for distances, the latter actually the result of an + exhaustive search). The true maximum is not known, but the value + below is more than safe. */ +#define ENOUGH 2048 +#define MAXD 592 + +/* Type of code to build for inftable() */ +typedef enum { + CODES, + LENS, + DISTS +} codetype; + +extern int inflate_table OF((codetype type, unsigned short FAR *lens, + unsigned codes, code FAR * FAR *table, + unsigned FAR *bits, unsigned short FAR *work)); diff --git a/Foundation/src/maketables.c b/Foundation/src/maketables.c index e4321b788..155c165fe 100644 --- a/Foundation/src/maketables.c +++ b/Foundation/src/maketables.c @@ -1,146 +1,146 @@ -/************************************************* -* Perl-Compatible Regular Expressions * -*************************************************/ - -/* -PCRE is a library of functions to support regular expressions whose syntax -and semantics are as close as possible to those of the Perl 5 language. - -Written by: Philip Hazel - - Copyright (c) 1997-2003 University of Cambridge - ------------------------------------------------------------------------------ -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - * 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. - - * Neither the name of the University of Cambridge nor the names of its - contributors may be used to endorse or promote products derived from - this software without specific prior written permission. - -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. ------------------------------------------------------------------------------ -*/ - - -/* This file is compiled on its own as part of the PCRE library. However, -it is also included in the compilation of dftables.c, in which case the macro -DFTABLES is defined. */ - -#ifndef DFTABLES -#include "pcreinternal.h" -#endif - - - -/************************************************* -* Create PCRE character tables * -*************************************************/ - -/* This function builds a set of character tables for use by PCRE and returns -a pointer to them. They are build using the ctype functions, and consequently -their contents will depend upon the current locale setting. When compiled as -part of the library, the store is obtained via pcre_malloc(), but when compiled -inside dftables, use malloc(). - -Arguments: none -Returns: pointer to the contiguous block of data -*/ - -const unsigned char * -pcre_maketables(void) -{ -unsigned char *yield, *p; -int i; - -#ifndef DFTABLES -yield = (unsigned char*)(pcre_malloc)(tables_length); -#else -yield = (unsigned char*)malloc(tables_length); -#endif - -if (yield == NULL) return NULL; -p = yield; - -/* First comes the lower casing table */ - -for (i = 0; i < 256; i++) *p++ = tolower(i); - -/* Next the case-flipping table */ - -for (i = 0; i < 256; i++) *p++ = islower(i)? toupper(i) : tolower(i); - -/* Then the character class tables. Don't try to be clever and save effort -on exclusive ones - in some locales things may be different. Note that the -table for "space" includes everything "isspace" gives, including VT in the -default locale. This makes it work for the POSIX class [:space:]. */ - -memset(p, 0, cbit_length); -for (i = 0; i < 256; i++) - { - if (isdigit(i)) - { - p[cbit_digit + i/8] |= 1 << (i&7); - p[cbit_word + i/8] |= 1 << (i&7); - } - if (isupper(i)) - { - p[cbit_upper + i/8] |= 1 << (i&7); - p[cbit_word + i/8] |= 1 << (i&7); - } - if (islower(i)) - { - p[cbit_lower + i/8] |= 1 << (i&7); - p[cbit_word + i/8] |= 1 << (i&7); - } - if (i == '_') p[cbit_word + i/8] |= 1 << (i&7); - if (isspace(i)) p[cbit_space + i/8] |= 1 << (i&7); - if (isxdigit(i))p[cbit_xdigit + i/8] |= 1 << (i&7); - if (isgraph(i)) p[cbit_graph + i/8] |= 1 << (i&7); - if (isprint(i)) p[cbit_print + i/8] |= 1 << (i&7); - if (ispunct(i)) p[cbit_punct + i/8] |= 1 << (i&7); - if (iscntrl(i)) p[cbit_cntrl + i/8] |= 1 << (i&7); - } -p += cbit_length; - -/* Finally, the character type table. In this, we exclude VT from the white -space chars, because Perl doesn't recognize it as such for \s and for comments -within regexes. */ - -for (i = 0; i < 256; i++) - { - int x = 0; - if (i != 0x0b && isspace(i)) x += ctype_space; - if (isalpha(i)) x += ctype_letter; - if (isdigit(i)) x += ctype_digit; - if (isxdigit(i)) x += ctype_xdigit; - if (isalnum(i) || i == '_') x += ctype_word; - - /* Note: strchr includes the terminating zero in the characters it considers. - In this instance, that is ok because we want binary zero to be flagged as a - meta-character, which in this sense is any character that terminates a run - of data characters. */ - - if (strchr("*+?{^.$|()[", i) != 0) x += ctype_meta; *p++ = x; } - -return yield; -} - -/* End of maketables.c */ +/************************************************* +* Perl-Compatible Regular Expressions * +*************************************************/ + +/* +PCRE is a library of functions to support regular expressions whose syntax +and semantics are as close as possible to those of the Perl 5 language. + +Written by: Philip Hazel + + Copyright (c) 1997-2003 University of Cambridge + +----------------------------------------------------------------------------- +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + * 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. + + * Neither the name of the University of Cambridge nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +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. +----------------------------------------------------------------------------- +*/ + + +/* This file is compiled on its own as part of the PCRE library. However, +it is also included in the compilation of dftables.c, in which case the macro +DFTABLES is defined. */ + +#ifndef DFTABLES +#include "pcreinternal.h" +#endif + + + +/************************************************* +* Create PCRE character tables * +*************************************************/ + +/* This function builds a set of character tables for use by PCRE and returns +a pointer to them. They are build using the ctype functions, and consequently +their contents will depend upon the current locale setting. When compiled as +part of the library, the store is obtained via pcre_malloc(), but when compiled +inside dftables, use malloc(). + +Arguments: none +Returns: pointer to the contiguous block of data +*/ + +const unsigned char * +pcre_maketables(void) +{ +unsigned char *yield, *p; +int i; + +#ifndef DFTABLES +yield = (unsigned char*)(pcre_malloc)(tables_length); +#else +yield = (unsigned char*)malloc(tables_length); +#endif + +if (yield == NULL) return NULL; +p = yield; + +/* First comes the lower casing table */ + +for (i = 0; i < 256; i++) *p++ = tolower(i); + +/* Next the case-flipping table */ + +for (i = 0; i < 256; i++) *p++ = islower(i)? toupper(i) : tolower(i); + +/* Then the character class tables. Don't try to be clever and save effort +on exclusive ones - in some locales things may be different. Note that the +table for "space" includes everything "isspace" gives, including VT in the +default locale. This makes it work for the POSIX class [:space:]. */ + +memset(p, 0, cbit_length); +for (i = 0; i < 256; i++) + { + if (isdigit(i)) + { + p[cbit_digit + i/8] |= 1 << (i&7); + p[cbit_word + i/8] |= 1 << (i&7); + } + if (isupper(i)) + { + p[cbit_upper + i/8] |= 1 << (i&7); + p[cbit_word + i/8] |= 1 << (i&7); + } + if (islower(i)) + { + p[cbit_lower + i/8] |= 1 << (i&7); + p[cbit_word + i/8] |= 1 << (i&7); + } + if (i == '_') p[cbit_word + i/8] |= 1 << (i&7); + if (isspace(i)) p[cbit_space + i/8] |= 1 << (i&7); + if (isxdigit(i))p[cbit_xdigit + i/8] |= 1 << (i&7); + if (isgraph(i)) p[cbit_graph + i/8] |= 1 << (i&7); + if (isprint(i)) p[cbit_print + i/8] |= 1 << (i&7); + if (ispunct(i)) p[cbit_punct + i/8] |= 1 << (i&7); + if (iscntrl(i)) p[cbit_cntrl + i/8] |= 1 << (i&7); + } +p += cbit_length; + +/* Finally, the character type table. In this, we exclude VT from the white +space chars, because Perl doesn't recognize it as such for \s and for comments +within regexes. */ + +for (i = 0; i < 256; i++) + { + int x = 0; + if (i != 0x0b && isspace(i)) x += ctype_space; + if (isalpha(i)) x += ctype_letter; + if (isdigit(i)) x += ctype_digit; + if (isxdigit(i)) x += ctype_xdigit; + if (isalnum(i) || i == '_') x += ctype_word; + + /* Note: strchr includes the terminating zero in the characters it considers. + In this instance, that is ok because we want binary zero to be flagged as a + meta-character, which in this sense is any character that terminates a run + of data characters. */ + + if (strchr("*+?{^.$|()[", i) != 0) x += ctype_meta; *p++ = x; } + +return yield; +} + +/* End of maketables.c */ diff --git a/Foundation/src/pcre.c b/Foundation/src/pcre.c index 552517159..17d084b76 100644 --- a/Foundation/src/pcre.c +++ b/Foundation/src/pcre.c @@ -1,9195 +1,9195 @@ -/************************************************* -* Perl-Compatible Regular Expressions * -*************************************************/ - -/* -This is a library of functions to support regular expressions whose syntax -and semantics are as close as possible to those of the Perl 5 language. See -the file Tech.Notes for some information on the internals. - -Written by: Philip Hazel - - Copyright (c) 1997-2004 University of Cambridge - ------------------------------------------------------------------------------ -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - * 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. - - * Neither the name of the University of Cambridge nor the names of its - contributors may be used to endorse or promote products derived from - this software without specific prior written permission. - -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. ------------------------------------------------------------------------------ -*/ - - -/* Define DEBUG to get debugging output on stdout. */ -/* #define DEBUG */ - -/* Use a macro for debugging printing, 'cause that eliminates the use of #ifdef -inline, and there are *still* stupid compilers about that don't like indented -pre-processor statements. I suppose it's only been 10 years... */ - -#ifdef DEBUG -#define DPRINTF(p) printf p -#else -#define DPRINTF(p) /*nothing*/ -#endif - -/* Include the internals header, which itself includes "config.h", the Standard -C headers, and the external pcre header. */ - -#include "pcreinternal.h" - -/* If Unicode Property support is wanted, include a private copy of the -function that does it, and the table that translates names to numbers. */ - -#ifdef SUPPORT_UCP -#include "ucp.c" -#include "ucptypetable.c" -#endif - -/* Maximum number of items on the nested bracket stacks at compile time. This -applies to the nesting of all kinds of parentheses. It does not limit -un-nested, non-capturing parentheses. This number can be made bigger if -necessary - it is used to dimension one int and one unsigned char vector at -compile time. */ - -#define BRASTACK_SIZE 200 - - -/* Maximum number of ints of offset to save on the stack for recursive calls. -If the offset vector is bigger, malloc is used. This should be a multiple of 3, -because the offset vector is always a multiple of 3 long. */ - -#define REC_STACK_SAVE_MAX 30 - - -/* The maximum remaining length of subject we are prepared to search for a -req_byte match. */ - -#define REQ_BYTE_MAX 1000 - - -/* Table of sizes for the fixed-length opcodes. It's defined in a macro so that -the definition is next to the definition of the opcodes in internal.h. */ - -static const uschar OP_lengths[] = { OP_LENGTHS }; - -/* Min and max values for the common repeats; for the maxima, 0 => infinity */ - -static const char rep_min[] = { 0, 0, 1, 1, 0, 0 }; -static const char rep_max[] = { 0, 0, 0, 0, 1, 1 }; - -/* Table for handling escaped characters in the range '0'-'z'. Positive returns -are simple data values; negative values are for special things like \d and so -on. Zero means further processing is needed (for things like \x), or the escape -is invalid. */ - -#if !EBCDIC /* This is the "normal" table for ASCII systems */ -static const short int escapes[] = { - 0, 0, 0, 0, 0, 0, 0, 0, /* 0 - 7 */ - 0, 0, ':', ';', '<', '=', '>', '?', /* 8 - ? */ - '@', -ESC_A, -ESC_B, -ESC_C, -ESC_D, -ESC_E, 0, -ESC_G, /* @ - G */ - 0, 0, 0, 0, 0, 0, 0, 0, /* H - O */ --ESC_P, -ESC_Q, 0, -ESC_S, 0, 0, 0, -ESC_W, /* P - W */ --ESC_X, 0, -ESC_Z, '[', '\\', ']', '^', '_', /* X - _ */ - '`', 7, -ESC_b, 0, -ESC_d, ESC_e, ESC_f, 0, /* ` - g */ - 0, 0, 0, 0, 0, 0, ESC_n, 0, /* h - o */ --ESC_p, 0, ESC_r, -ESC_s, ESC_tee, 0, 0, -ESC_w, /* p - w */ - 0, 0, -ESC_z /* x - z */ -}; - -#else /* This is the "abnormal" table for EBCDIC systems */ -static const short int escapes[] = { -/* 48 */ 0, 0, 0, '.', '<', '(', '+', '|', -/* 50 */ '&', 0, 0, 0, 0, 0, 0, 0, -/* 58 */ 0, 0, '!', '$', '*', ')', ';', '~', -/* 60 */ '-', '/', 0, 0, 0, 0, 0, 0, -/* 68 */ 0, 0, '|', ',', '%', '_', '>', '?', -/* 70 */ 0, 0, 0, 0, 0, 0, 0, 0, -/* 78 */ 0, '`', ':', '#', '@', '\'', '=', '"', -/* 80 */ 0, 7, -ESC_b, 0, -ESC_d, ESC_e, ESC_f, 0, -/* 88 */ 0, 0, 0, '{', 0, 0, 0, 0, -/* 90 */ 0, 0, 0, 'l', 0, ESC_n, 0, -ESC_p, -/* 98 */ 0, ESC_r, 0, '}', 0, 0, 0, 0, -/* A0 */ 0, '~', -ESC_s, ESC_tee, 0, 0, -ESC_w, 0, -/* A8 */ 0,-ESC_z, 0, 0, 0, '[', 0, 0, -/* B0 */ 0, 0, 0, 0, 0, 0, 0, 0, -/* B8 */ 0, 0, 0, 0, 0, ']', '=', '-', -/* C0 */ '{',-ESC_A, -ESC_B, -ESC_C, -ESC_D,-ESC_E, 0, -ESC_G, -/* C8 */ 0, 0, 0, 0, 0, 0, 0, 0, -/* D0 */ '}', 0, 0, 0, 0, 0, 0, -ESC_P, -/* D8 */-ESC_Q, 0, 0, 0, 0, 0, 0, 0, -/* E0 */ '\\', 0, -ESC_S, 0, 0, 0, -ESC_W, -ESC_X, -/* E8 */ 0,-ESC_Z, 0, 0, 0, 0, 0, 0, -/* F0 */ 0, 0, 0, 0, 0, 0, 0, 0, -/* F8 */ 0, 0, 0, 0, 0, 0, 0, 0 -}; -#endif - - -/* Tables of names of POSIX character classes and their lengths. The list is -terminated by a zero length entry. The first three must be alpha, upper, lower, -as this is assumed for handling case independence. */ - -static const char *const posix_names[] = { - "alpha", "lower", "upper", - "alnum", "ascii", "blank", "cntrl", "digit", "graph", - "print", "punct", "space", "word", "xdigit" }; - -static const uschar posix_name_lengths[] = { - 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 4, 6, 0 }; - -/* Table of class bit maps for each POSIX class; up to three may be combined -to form the class. The table for [:blank:] is dynamically modified to remove -the vertical space characters. */ - -static const int posix_class_maps[] = { - cbit_lower, cbit_upper, -1, /* alpha */ - cbit_lower, -1, -1, /* lower */ - cbit_upper, -1, -1, /* upper */ - cbit_digit, cbit_lower, cbit_upper, /* alnum */ - cbit_print, cbit_cntrl, -1, /* ascii */ - cbit_space, -1, -1, /* blank - a GNU extension */ - cbit_cntrl, -1, -1, /* cntrl */ - cbit_digit, -1, -1, /* digit */ - cbit_graph, -1, -1, /* graph */ - cbit_print, -1, -1, /* print */ - cbit_punct, -1, -1, /* punct */ - cbit_space, -1, -1, /* space */ - cbit_word, -1, -1, /* word - a Perl extension */ - cbit_xdigit,-1, -1 /* xdigit */ -}; - -/* Table to identify digits and hex digits. This is used when compiling -patterns. Note that the tables in chartables are dependent on the locale, and -may mark arbitrary characters as digits - but the PCRE compiling code expects -to handle only 0-9, a-z, and A-Z as digits when compiling. That is why we have -a private table here. It costs 256 bytes, but it is a lot faster than doing -character value tests (at least in some simple cases I timed), and in some -applications one wants PCRE to compile efficiently as well as match -efficiently. - -For convenience, we use the same bit definitions as in chartables: - - 0x04 decimal digit - 0x08 hexadecimal digit - -Then we can use ctype_digit and ctype_xdigit in the code. */ - -#if !EBCDIC /* This is the "normal" case, for ASCII systems */ -static const unsigned char digitab[] = - { - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 0- 7 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 8- 15 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 16- 23 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 24- 31 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* - ' */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* ( - / */ - 0x0c,0x0c,0x0c,0x0c,0x0c,0x0c,0x0c,0x0c, /* 0 - 7 */ - 0x0c,0x0c,0x00,0x00,0x00,0x00,0x00,0x00, /* 8 - ? */ - 0x00,0x08,0x08,0x08,0x08,0x08,0x08,0x00, /* @ - G */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* H - O */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* P - W */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* X - _ */ - 0x00,0x08,0x08,0x08,0x08,0x08,0x08,0x00, /* ` - g */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* h - o */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* p - w */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* x -127 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 128-135 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 136-143 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 144-151 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 152-159 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 160-167 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 168-175 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 176-183 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 184-191 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 192-199 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 200-207 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 208-215 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 216-223 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 224-231 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 232-239 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 240-247 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};/* 248-255 */ - -#else /* This is the "abnormal" case, for EBCDIC systems */ -static const unsigned char digitab[] = - { - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 0- 7 0 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 8- 15 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 16- 23 10 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 24- 31 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 32- 39 20 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 40- 47 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 48- 55 30 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 56- 63 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* - 71 40 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 72- | */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* & - 87 50 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 88- ¬ */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* - -103 60 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 104- ? */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 112-119 70 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 120- " */ - 0x00,0x08,0x08,0x08,0x08,0x08,0x08,0x00, /* 128- g 80 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* h -143 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 144- p 90 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* q -159 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 160- x A0 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* y -175 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* ^ -183 B0 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 184-191 */ - 0x00,0x08,0x08,0x08,0x08,0x08,0x08,0x00, /* { - G C0 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* H -207 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* } - P D0 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* Q -223 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* \ - X E0 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* Y -239 */ - 0x0c,0x0c,0x0c,0x0c,0x0c,0x0c,0x0c,0x0c, /* 0 - 7 F0 */ - 0x0c,0x0c,0x00,0x00,0x00,0x00,0x00,0x00};/* 8 -255 */ - -static const unsigned char ebcdic_chartab[] = { /* chartable partial dup */ - 0x80,0x00,0x00,0x00,0x00,0x01,0x00,0x00, /* 0- 7 */ - 0x00,0x00,0x00,0x00,0x01,0x01,0x00,0x00, /* 8- 15 */ - 0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00, /* 16- 23 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 24- 31 */ - 0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00, /* 32- 39 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 40- 47 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 48- 55 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 56- 63 */ - 0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* - 71 */ - 0x00,0x00,0x00,0x80,0x00,0x80,0x80,0x80, /* 72- | */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* & - 87 */ - 0x00,0x00,0x00,0x80,0x80,0x80,0x00,0x00, /* 88- ¬ */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* - -103 */ - 0x00,0x00,0x00,0x00,0x00,0x10,0x00,0x80, /* 104- ? */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 112-119 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 120- " */ - 0x00,0x1a,0x1a,0x1a,0x1a,0x1a,0x1a,0x12, /* 128- g */ - 0x12,0x12,0x00,0x00,0x00,0x00,0x00,0x00, /* h -143 */ - 0x00,0x12,0x12,0x12,0x12,0x12,0x12,0x12, /* 144- p */ - 0x12,0x12,0x00,0x00,0x00,0x00,0x00,0x00, /* q -159 */ - 0x00,0x00,0x12,0x12,0x12,0x12,0x12,0x12, /* 160- x */ - 0x12,0x12,0x00,0x00,0x00,0x00,0x00,0x00, /* y -175 */ - 0x80,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* ^ -183 */ - 0x00,0x00,0x80,0x00,0x00,0x00,0x00,0x00, /* 184-191 */ - 0x80,0x1a,0x1a,0x1a,0x1a,0x1a,0x1a,0x12, /* { - G */ - 0x12,0x12,0x00,0x00,0x00,0x00,0x00,0x00, /* H -207 */ - 0x00,0x12,0x12,0x12,0x12,0x12,0x12,0x12, /* } - P */ - 0x12,0x12,0x00,0x00,0x00,0x00,0x00,0x00, /* Q -223 */ - 0x00,0x00,0x12,0x12,0x12,0x12,0x12,0x12, /* \ - X */ - 0x12,0x12,0x00,0x00,0x00,0x00,0x00,0x00, /* Y -239 */ - 0x1c,0x1c,0x1c,0x1c,0x1c,0x1c,0x1c,0x1c, /* 0 - 7 */ - 0x1c,0x1c,0x00,0x00,0x00,0x00,0x00,0x00};/* 8 -255 */ -#endif - - -/* Definition to allow mutual recursion */ - -static BOOL - compile_regex(int, int, int *, uschar **, const uschar **, const char **, - BOOL, int, int *, int *, branch_chain *, compile_data *); - -/* Structure for building a chain of data that actually lives on the -stack, for holding the values of the subject pointer at the start of each -subpattern, so as to detect when an empty string has been matched by a -subpattern - to break infinite loops. When NO_RECURSE is set, these blocks -are on the heap, not on the stack. */ - -typedef struct eptrblock { - struct eptrblock *epb_prev; - const uschar *epb_saved_eptr; -} eptrblock; - -/* Flag bits for the match() function */ - -#define match_condassert 0x01 /* Called to check a condition assertion */ -#define match_isgroup 0x02 /* Set if start of bracketed group */ - -/* Non-error returns from the match() function. Error returns are externally -defined PCRE_ERROR_xxx codes, which are all negative. */ - -#define MATCH_MATCH 1 -#define MATCH_NOMATCH 0 - - - -/************************************************* -* Global variables * -*************************************************/ - -/* PCRE is thread-clean and doesn't use any global variables in the normal -sense. However, it calls memory allocation and free functions via the four -indirections below, and it can optionally do callouts. These values can be -changed by the caller, but are shared between all threads. However, when -compiling for Virtual Pascal, things are done differently (see pcre.in). */ - -#ifndef VPCOMPAT -#ifdef __cplusplus -extern "C" void *(*pcre_malloc)(size_t) = malloc; -extern "C" void (*pcre_free)(void *) = free; -extern "C" void *(*pcre_stack_malloc)(size_t) = malloc; -extern "C" void (*pcre_stack_free)(void *) = free; -extern "C" int (*pcre_callout)(pcre_callout_block *) = NULL; -#else -void *(*pcre_malloc)(size_t) = malloc; -void (*pcre_free)(void *) = free; -void *(*pcre_stack_malloc)(size_t) = malloc; -void (*pcre_stack_free)(void *) = free; -int (*pcre_callout)(pcre_callout_block *) = NULL; -#endif -#endif - - -/************************************************* -* Macros and tables for character handling * -*************************************************/ - -/* When UTF-8 encoding is being used, a character is no longer just a single -byte. The macros for character handling generate simple sequences when used in -byte-mode, and more complicated ones for UTF-8 characters. */ - -#ifndef SUPPORT_UTF8 -#define GETCHAR(c, eptr) c = *eptr; -#define GETCHARINC(c, eptr) c = *eptr++; -#define GETCHARINCTEST(c, eptr) c = *eptr++; -#define GETCHARLEN(c, eptr, len) c = *eptr; -#define BACKCHAR(eptr) - -#else /* SUPPORT_UTF8 */ - -/* Get the next UTF-8 character, not advancing the pointer. This is called when -we know we are in UTF-8 mode. */ - -#define GETCHAR(c, eptr) \ - c = *eptr; \ - if ((c & 0xc0) == 0xc0) \ - { \ - int gcii; \ - int gcaa = utf8_table4[c & 0x3f]; /* Number of additional bytes */ \ - int gcss = 6*gcaa; \ - c = (c & utf8_table3[gcaa]) << gcss; \ - for (gcii = 1; gcii <= gcaa; gcii++) \ - { \ - gcss -= 6; \ - c |= (eptr[gcii] & 0x3f) << gcss; \ - } \ - } - -/* Get the next UTF-8 character, advancing the pointer. This is called when we -know we are in UTF-8 mode. */ - -#define GETCHARINC(c, eptr) \ - c = *eptr++; \ - if ((c & 0xc0) == 0xc0) \ - { \ - int gcaa = utf8_table4[c & 0x3f]; /* Number of additional bytes */ \ - int gcss = 6*gcaa; \ - c = (c & utf8_table3[gcaa]) << gcss; \ - while (gcaa-- > 0) \ - { \ - gcss -= 6; \ - c |= (*eptr++ & 0x3f) << gcss; \ - } \ - } - -/* Get the next character, testing for UTF-8 mode, and advancing the pointer */ - -#define GETCHARINCTEST(c, eptr) \ - c = *eptr++; \ - if (md->utf8 && (c & 0xc0) == 0xc0) \ - { \ - int gcaa = utf8_table4[c & 0x3f]; /* Number of additional bytes */ \ - int gcss = 6*gcaa; \ - c = (c & utf8_table3[gcaa]) << gcss; \ - while (gcaa-- > 0) \ - { \ - gcss -= 6; \ - c |= (*eptr++ & 0x3f) << gcss; \ - } \ - } - -/* Get the next UTF-8 character, not advancing the pointer, incrementing length -if there are extra bytes. This is called when we know we are in UTF-8 mode. */ - -#define GETCHARLEN(c, eptr, len) \ - c = *eptr; \ - if ((c & 0xc0) == 0xc0) \ - { \ - int gcii; \ - int gcaa = utf8_table4[c & 0x3f]; /* Number of additional bytes */ \ - int gcss = 6*gcaa; \ - c = (c & utf8_table3[gcaa]) << gcss; \ - for (gcii = 1; gcii <= gcaa; gcii++) \ - { \ - gcss -= 6; \ - c |= (eptr[gcii] & 0x3f) << gcss; \ - } \ - len += gcaa; \ - } - -/* If the pointer is not at the start of a character, move it back until -it is. Called only in UTF-8 mode. */ - -#define BACKCHAR(eptr) while((*eptr & 0xc0) == 0x80) eptr--; - -#endif - - - -/************************************************* -* Default character tables * -*************************************************/ - -/* A default set of character tables is included in the PCRE binary. Its source -is built by the maketables auxiliary program, which uses the default C ctypes -functions, and put in the file chartables.c. These tables are used by PCRE -whenever the caller of pcre_compile() does not provide an alternate set of -tables. */ - -#include "chartables.c" - - - -#ifdef SUPPORT_UTF8 -/************************************************* -* Tables for UTF-8 support * -*************************************************/ - -/* These are the breakpoints for different numbers of bytes in a UTF-8 -character. */ - -static const int utf8_table1[] = - { 0x7f, 0x7ff, 0xffff, 0x1fffff, 0x3ffffff, 0x7fffffff}; - -/* These are the indicator bits and the mask for the data bits to set in the -first byte of a character, indexed by the number of additional bytes. */ - -static const int utf8_table2[] = { 0, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc}; -static const int utf8_table3[] = { 0xff, 0x1f, 0x0f, 0x07, 0x03, 0x01}; - -/* Table of the number of extra characters, indexed by the first character -masked with 0x3f. The highest number for a valid UTF-8 character is in fact -0x3d. */ - -static const uschar utf8_table4[] = { - 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, - 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, - 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, - 3,3,3,3,3,3,3,3,4,4,4,4,5,5,5,5 }; - - -/************************************************* -* Convert character value to UTF-8 * -*************************************************/ - -/* This function takes an integer value in the range 0 - 0x7fffffff -and encodes it as a UTF-8 character in 0 to 6 bytes. - -Arguments: - cvalue the character value - buffer pointer to buffer for result - at least 6 bytes long - -Returns: number of characters placed in the buffer -*/ - -static int -ord2utf8(int cvalue, uschar *buffer) -{ -register int i, j; -for (i = 0; i < sizeof(utf8_table1)/sizeof(int); i++) - if (cvalue <= utf8_table1[i]) break; -buffer += i; -for (j = i; j > 0; j--) - { - *buffer-- = 0x80 | (cvalue & 0x3f); - cvalue >>= 6; - } -*buffer = utf8_table2[i] | cvalue; -return i + 1; -} -#endif - - - -/************************************************* -* Print compiled regex * -*************************************************/ - -/* The code for doing this is held in a separate file that is also included in -pcretest.c. It defines a function called print_internals(). */ - -#ifdef DEBUG -#include "printint.c" -#endif - - - -/************************************************* -* Return version string * -*************************************************/ - -#define STRING(a) # a -#define XSTRING(s) STRING(s) - -EXPORT const char * -pcre_version(void) -{ -return XSTRING(PCRE_MAJOR) "." XSTRING(PCRE_MINOR) " " XSTRING(PCRE_DATE); -} - - - - -/************************************************* -* Flip bytes in an integer * -*************************************************/ - -/* This function is called when the magic number in a regex doesn't match in -order to flip its bytes to see if we are dealing with a pattern that was -compiled on a host of different endianness. If so, this function is used to -flip other byte values. - -Arguments: - value the number to flip - n the number of bytes to flip (assumed to be 2 or 4) - -Returns: the flipped value -*/ - -static long int -byteflip(long int value, int n) -{ -if (n == 2) return ((value & 0x00ff) << 8) | ((value & 0xff00) >> 8); -return ((value & 0x000000ff) << 24) | - ((value & 0x0000ff00) << 8) | - ((value & 0x00ff0000) >> 8) | - ((value & 0xff000000) >> 24); -} - - - -/************************************************* -* Test for a byte-flipped compiled regex * -*************************************************/ - -/* This function is called from pce_exec() and also from pcre_fullinfo(). Its -job is to test whether the regex is byte-flipped - that is, it was compiled on -a system of opposite endianness. The function is called only when the native -MAGIC_NUMBER test fails. If the regex is indeed flipped, we flip all the -relevant values into a different data block, and return it. - -Arguments: - re points to the regex - study points to study data, or NULL - internal_re points to a new regex block - internal_study points to a new study block - -Returns: the new block if is is indeed a byte-flipped regex - NULL if it is not -*/ - -static real_pcre * -try_flipped(const real_pcre *re, real_pcre *internal_re, - const pcre_study_data *study, pcre_study_data *internal_study) -{ -if (byteflip(re->magic_number, sizeof(re->magic_number)) != MAGIC_NUMBER) - return NULL; - -*internal_re = *re; /* To copy other fields */ -internal_re->size = byteflip(re->size, sizeof(re->size)); -internal_re->options = byteflip(re->options, sizeof(re->options)); -internal_re->top_bracket = byteflip(re->top_bracket, sizeof(re->top_bracket)); -internal_re->top_backref = byteflip(re->top_backref, sizeof(re->top_backref)); -internal_re->first_byte = byteflip(re->first_byte, sizeof(re->first_byte)); -internal_re->req_byte = byteflip(re->req_byte, sizeof(re->req_byte)); -internal_re->name_table_offset = byteflip(re->name_table_offset, - sizeof(re->name_table_offset)); -internal_re->name_entry_size = byteflip(re->name_entry_size, - sizeof(re->name_entry_size)); -internal_re->name_count = byteflip(re->name_count, sizeof(re->name_count)); - -if (study != NULL) - { - *internal_study = *study; /* To copy other fields */ - internal_study->size = byteflip(study->size, sizeof(study->size)); - internal_study->options = byteflip(study->options, sizeof(study->options)); - } - -return internal_re; -} - - - -/************************************************* -* (Obsolete) Return info about compiled pattern * -*************************************************/ - -/* This is the original "info" function. It picks potentially useful data out -of the private structure, but its interface was too rigid. It remains for -backwards compatibility. The public options are passed back in an int - though -the re->options field has been expanded to a long int, all the public options -at the low end of it, and so even on 16-bit systems this will still be OK. -Therefore, I haven't changed the API for pcre_info(). - -Arguments: - argument_re points to compiled code - optptr where to pass back the options - first_byte where to pass back the first character, - or -1 if multiline and all branches start ^, - or -2 otherwise - -Returns: number of capturing subpatterns - or negative values on error -*/ - -EXPORT int -pcre_info(const pcre *argument_re, int *optptr, int *first_byte) -{ -real_pcre internal_re; -const real_pcre *re = (const real_pcre *)argument_re; -if (re == NULL) return PCRE_ERROR_NULL; -if (re->magic_number != MAGIC_NUMBER) - { - re = try_flipped(re, &internal_re, NULL, NULL); - if (re == NULL) return PCRE_ERROR_BADMAGIC; - } -if (optptr != NULL) *optptr = (int)(re->options & PUBLIC_OPTIONS); -if (first_byte != NULL) - *first_byte = ((re->options & PCRE_FIRSTSET) != 0)? re->first_byte : - ((re->options & PCRE_STARTLINE) != 0)? -1 : -2; -return re->top_bracket; -} - - - -/************************************************* -* Return info about compiled pattern * -*************************************************/ - -/* This is a newer "info" function which has an extensible interface so -that additional items can be added compatibly. - -Arguments: - argument_re points to compiled code - extra_data points extra data, or NULL - what what information is required - where where to put the information - -Returns: 0 if data returned, negative on error -*/ - -EXPORT int -pcre_fullinfo(const pcre *argument_re, const pcre_extra *extra_data, int what, - void *where) -{ -real_pcre internal_re; -pcre_study_data internal_study; -const real_pcre *re = (const real_pcre *)argument_re; -const pcre_study_data *study = NULL; - -if (re == NULL || where == NULL) return PCRE_ERROR_NULL; - -if (extra_data != NULL && (extra_data->flags & PCRE_EXTRA_STUDY_DATA) != 0) - study = (const pcre_study_data *)extra_data->study_data; - -if (re->magic_number != MAGIC_NUMBER) - { - re = try_flipped(re, &internal_re, study, &internal_study); - if (re == NULL) return PCRE_ERROR_BADMAGIC; - if (study != NULL) study = &internal_study; - } - -switch (what) - { - case PCRE_INFO_OPTIONS: - *((unsigned long int *)where) = re->options & PUBLIC_OPTIONS; - break; - - case PCRE_INFO_SIZE: - *((size_t *)where) = re->size; - break; - - case PCRE_INFO_STUDYSIZE: - *((size_t *)where) = (study == NULL)? 0 : study->size; - break; - - case PCRE_INFO_CAPTURECOUNT: - *((int *)where) = re->top_bracket; - break; - - case PCRE_INFO_BACKREFMAX: - *((int *)where) = re->top_backref; - break; - - case PCRE_INFO_FIRSTBYTE: - *((int *)where) = - ((re->options & PCRE_FIRSTSET) != 0)? re->first_byte : - ((re->options & PCRE_STARTLINE) != 0)? -1 : -2; - break; - - /* Make sure we pass back the pointer to the bit vector in the external - block, not the internal copy (with flipped integer fields). */ - - case PCRE_INFO_FIRSTTABLE: - *((const uschar **)where) = - (study != NULL && (study->options & PCRE_STUDY_MAPPED) != 0)? - ((const pcre_study_data *)extra_data->study_data)->start_bits : NULL; - break; - - case PCRE_INFO_LASTLITERAL: - *((int *)where) = - ((re->options & PCRE_REQCHSET) != 0)? re->req_byte : -1; - break; - - case PCRE_INFO_NAMEENTRYSIZE: - *((int *)where) = re->name_entry_size; - break; - - case PCRE_INFO_NAMECOUNT: - *((int *)where) = re->name_count; - break; - - case PCRE_INFO_NAMETABLE: - *((const uschar **)where) = (const uschar *)re + re->name_table_offset; - break; - - case PCRE_INFO_DEFAULT_TABLES: - *((const uschar **)where) = (const uschar *)pcre_default_tables; - break; - - default: return PCRE_ERROR_BADOPTION; - } - -return 0; -} - - - -/************************************************* -* Return info about what features are configured * -*************************************************/ - -/* This is function which has an extensible interface so that additional items -can be added compatibly. - -Arguments: - what what information is required - where where to put the information - -Returns: 0 if data returned, negative on error -*/ - -EXPORT int -pcre_config(int what, void *where) -{ -switch (what) - { - case PCRE_CONFIG_UTF8: -#ifdef SUPPORT_UTF8 - *((int *)where) = 1; -#else - *((int *)where) = 0; -#endif - break; - - case PCRE_CONFIG_UNICODE_PROPERTIES: -#ifdef SUPPORT_UCP - *((int *)where) = 1; -#else - *((int *)where) = 0; -#endif - break; - - case PCRE_CONFIG_NEWLINE: - *((int *)where) = NEWLINE; - break; - - case PCRE_CONFIG_LINK_SIZE: - *((int *)where) = LINK_SIZE; - break; - - case PCRE_CONFIG_POSIX_MALLOC_THRESHOLD: - *((int *)where) = POSIX_MALLOC_THRESHOLD; - break; - - case PCRE_CONFIG_MATCH_LIMIT: - *((unsigned int *)where) = MATCH_LIMIT; - break; - - case PCRE_CONFIG_STACKRECURSE: -#ifdef NO_RECURSE - *((int *)where) = 0; -#else - *((int *)where) = 1; -#endif - break; - - default: return PCRE_ERROR_BADOPTION; - } - -return 0; -} - - - -#ifdef DEBUG -/************************************************* -* Debugging function to print chars * -*************************************************/ - -/* Print a sequence of chars in printable format, stopping at the end of the -subject if the requested. - -Arguments: - p points to characters - length number to print - is_subject TRUE if printing from within md->start_subject - md pointer to matching data block, if is_subject is TRUE - -Returns: nothing -*/ - -static void -pchars(const uschar *p, int length, BOOL is_subject, match_data *md) -{ -int c; -if (is_subject && length > md->end_subject - p) length = md->end_subject - p; -while (length-- > 0) - if (isprint(c = *(p++))) printf("%c", c); else printf("\\x%02x", c); -} -#endif - - - - -/************************************************* -* Handle escapes * -*************************************************/ - -/* This function is called when a \ has been encountered. It either returns a -positive value for a simple escape such as \n, or a negative value which -encodes one of the more complicated things such as \d. When UTF-8 is enabled, -a positive value greater than 255 may be returned. On entry, ptr is pointing at -the \. On exit, it is on the final character of the escape sequence. - -Arguments: - ptrptr points to the pattern position pointer - errorptr points to the pointer to the error message - bracount number of previous extracting brackets - options the options bits - isclass TRUE if inside a character class - -Returns: zero or positive => a data character - negative => a special escape sequence - on error, errorptr is set -*/ - -static int -check_escape(const uschar **ptrptr, const char **errorptr, int bracount, - int options, BOOL isclass) -{ -const uschar *ptr = *ptrptr; -int c, i; - -/* If backslash is at the end of the pattern, it's an error. */ - -c = *(++ptr); -if (c == 0) *errorptr = ERR1; - -/* Non-alphamerics are literals. For digits or letters, do an initial lookup in -a table. A non-zero result is something that can be returned immediately. -Otherwise further processing may be required. */ - -#if !EBCDIC /* ASCII coding */ -else if (c < '0' || c > 'z') {} /* Not alphameric */ -else if ((i = escapes[c - '0']) != 0) c = i; - -#else /* EBCDIC coding */ -else if (c < 'a' || (ebcdic_chartab[c] & 0x0E) == 0) {} /* Not alphameric */ -else if ((i = escapes[c - 0x48]) != 0) c = i; -#endif - -/* Escapes that need further processing, or are illegal. */ - -else - { - const uschar *oldptr; - switch (c) - { - /* A number of Perl escapes are not handled by PCRE. We give an explicit - error. */ - - case 'l': - case 'L': - case 'N': - case 'u': - case 'U': - *errorptr = ERR37; - break; - - /* The handling of escape sequences consisting of a string of digits - starting with one that is not zero is not straightforward. By experiment, - the way Perl works seems to be as follows: - - Outside a character class, the digits are read as a decimal number. If the - number is less than 10, or if there are that many previous extracting - left brackets, then it is a back reference. Otherwise, up to three octal - digits are read to form an escaped byte. Thus \123 is likely to be octal - 123 (cf \0123, which is octal 012 followed by the literal 3). If the octal - value is greater than 377, the least significant 8 bits are taken. Inside a - character class, \ followed by a digit is always an octal number. */ - - case '1': case '2': case '3': case '4': case '5': - case '6': case '7': case '8': case '9': - - if (!isclass) - { - oldptr = ptr; - c -= '0'; - while ((digitab[ptr[1]] & ctype_digit) != 0) - c = c * 10 + *(++ptr) - '0'; - if (c < 10 || c <= bracount) - { - c = -(ESC_REF + c); - break; - } - ptr = oldptr; /* Put the pointer back and fall through */ - } - - /* Handle an octal number following \. If the first digit is 8 or 9, Perl - generates a binary zero byte and treats the digit as a following literal. - Thus we have to pull back the pointer by one. */ - - if ((c = *ptr) >= '8') - { - ptr--; - c = 0; - break; - } - - /* \0 always starts an octal number, but we may drop through to here with a - larger first octal digit. */ - - case '0': - c -= '0'; - while(i++ < 2 && ptr[1] >= '0' && ptr[1] <= '7') - c = c * 8 + *(++ptr) - '0'; - c &= 255; /* Take least significant 8 bits */ - break; - - /* \x is complicated when UTF-8 is enabled. \x{ddd} is a character number - which can be greater than 0xff, but only if the ddd are hex digits. */ - - case 'x': -#ifdef SUPPORT_UTF8 - if (ptr[1] == '{' && (options & PCRE_UTF8) != 0) - { - const uschar *pt = ptr + 2; - register int count = 0; - c = 0; - while ((digitab[*pt] & ctype_xdigit) != 0) - { - int cc = *pt++; - count++; -#if !EBCDIC /* ASCII coding */ - if (cc >= 'a') cc -= 32; /* Convert to upper case */ - c = c * 16 + cc - ((cc < 'A')? '0' : ('A' - 10)); -#else /* EBCDIC coding */ - if (cc >= 'a' && cc <= 'z') cc += 64; /* Convert to upper case */ - c = c * 16 + cc - ((cc >= '0')? '0' : ('A' - 10)); -#endif - } - if (*pt == '}') - { - if (c < 0 || count > 8) *errorptr = ERR34; - ptr = pt; - break; - } - /* If the sequence of hex digits does not end with '}', then we don't - recognize this construct; fall through to the normal \x handling. */ - } -#endif - - /* Read just a single hex char */ - - c = 0; - while (i++ < 2 && (digitab[ptr[1]] & ctype_xdigit) != 0) - { - int cc; /* Some compilers don't like ++ */ - cc = *(++ptr); /* in initializers */ -#if !EBCDIC /* ASCII coding */ - if (cc >= 'a') cc -= 32; /* Convert to upper case */ - c = c * 16 + cc - ((cc < 'A')? '0' : ('A' - 10)); -#else /* EBCDIC coding */ - if (cc <= 'z') cc += 64; /* Convert to upper case */ - c = c * 16 + cc - ((cc >= '0')? '0' : ('A' - 10)); -#endif - } - break; - - /* Other special escapes not starting with a digit are straightforward */ - - case 'c': - c = *(++ptr); - if (c == 0) - { - *errorptr = ERR2; - return 0; - } - - /* A letter is upper-cased; then the 0x40 bit is flipped. This coding - is ASCII-specific, but then the whole concept of \cx is ASCII-specific. - (However, an EBCDIC equivalent has now been added.) */ - -#if !EBCDIC /* ASCII coding */ - if (c >= 'a' && c <= 'z') c -= 32; - c ^= 0x40; -#else /* EBCDIC coding */ - if (c >= 'a' && c <= 'z') c += 64; - c ^= 0xC0; -#endif - break; - - /* PCRE_EXTRA enables extensions to Perl in the matter of escapes. Any - other alphameric following \ is an error if PCRE_EXTRA was set; otherwise, - for Perl compatibility, it is a literal. This code looks a bit odd, but - there used to be some cases other than the default, and there may be again - in future, so I haven't "optimized" it. */ - - default: - if ((options & PCRE_EXTRA) != 0) switch(c) - { - default: - *errorptr = ERR3; - break; - } - break; - } - } - -*ptrptr = ptr; -return c; -} - - - -#ifdef SUPPORT_UCP -/************************************************* -* Handle \P and \p * -*************************************************/ - -/* This function is called after \P or \p has been encountered, provided that -PCRE is compiled with support for Unicode properties. On entry, ptrptr is -pointing at the P or p. On exit, it is pointing at the final character of the -escape sequence. - -Argument: - ptrptr points to the pattern position pointer - negptr points to a boolean that is set TRUE for negation else FALSE - errorptr points to the pointer to the error message - -Returns: value from ucp_type_table, or -1 for an invalid type -*/ - -static int -get_ucp(const uschar **ptrptr, BOOL *negptr, const char **errorptr) -{ -int c, i, bot, top; -const uschar *ptr = *ptrptr; -char name[4]; - -c = *(++ptr); -if (c == 0) goto ERROR_RETURN; - -*negptr = FALSE; - -/* \P or \p can be followed by a one- or two-character name in {}, optionally -preceded by ^ for negation. */ - -if (c == '{') - { - if (ptr[1] == '^') - { - *negptr = TRUE; - ptr++; - } - for (i = 0; i <= 2; i++) - { - c = *(++ptr); - if (c == 0) goto ERROR_RETURN; - if (c == '}') break; - name[i] = c; - } - if (c !='}') /* Try to distinguish error cases */ - { - while (*(++ptr) != 0 && *ptr != '}'); - if (*ptr == '}') goto UNKNOWN_RETURN; else goto ERROR_RETURN; - } - name[i] = 0; - } - -/* Otherwise there is just one following character */ - -else - { - name[0] = c; - name[1] = 0; - } - -*ptrptr = ptr; - -/* Search for a recognized property name using binary chop */ - -bot = 0; -top = sizeof(utt)/sizeof(ucp_type_table); - -while (bot < top) - { - i = (bot + top)/2; - c = strcmp(name, utt[i].name); - if (c == 0) return utt[i].value; - if (c > 0) bot = i + 1; else top = i; - } - -UNKNOWN_RETURN: -*errorptr = ERR47; -*ptrptr = ptr; -return -1; - -ERROR_RETURN: -*errorptr = ERR46; -*ptrptr = ptr; -return -1; -} -#endif - - - - -/************************************************* -* Check for counted repeat * -*************************************************/ - -/* This function is called when a '{' is encountered in a place where it might -start a quantifier. It looks ahead to see if it really is a quantifier or not. -It is only a quantifier if it is one of the forms {ddd} {ddd,} or {ddd,ddd} -where the ddds are digits. - -Arguments: - p pointer to the first char after '{' - -Returns: TRUE or FALSE -*/ - -static BOOL -is_counted_repeat(const uschar *p) -{ -if ((digitab[*p++] & ctype_digit) == 0) return FALSE; -while ((digitab[*p] & ctype_digit) != 0) p++; -if (*p == '}') return TRUE; - -if (*p++ != ',') return FALSE; -if (*p == '}') return TRUE; - -if ((digitab[*p++] & ctype_digit) == 0) return FALSE; -while ((digitab[*p] & ctype_digit) != 0) p++; - -return (*p == '}'); -} - - - -/************************************************* -* Read repeat counts * -*************************************************/ - -/* Read an item of the form {n,m} and return the values. This is called only -after is_counted_repeat() has confirmed that a repeat-count quantifier exists, -so the syntax is guaranteed to be correct, but we need to check the values. - -Arguments: - p pointer to first char after '{' - minp pointer to int for min - maxp pointer to int for max - returned as -1 if no max - errorptr points to pointer to error message - -Returns: pointer to '}' on success; - current ptr on error, with errorptr set -*/ - -static const uschar * -read_repeat_counts(const uschar *p, int *minp, int *maxp, const char **errorptr) -{ -int min = 0; -int max = -1; - -while ((digitab[*p] & ctype_digit) != 0) min = min * 10 + *p++ - '0'; - -if (*p == '}') max = min; else - { - if (*(++p) != '}') - { - max = 0; - while((digitab[*p] & ctype_digit) != 0) max = max * 10 + *p++ - '0'; - if (max < min) - { - *errorptr = ERR4; - return p; - } - } - } - -/* Do paranoid checks, then fill in the required variables, and pass back the -pointer to the terminating '}'. */ - -if (min > 65535 || max > 65535) - *errorptr = ERR5; -else - { - *minp = min; - *maxp = max; - } -return p; -} - - - -/************************************************* -* Find first significant op code * -*************************************************/ - -/* This is called by several functions that scan a compiled expression looking -for a fixed first character, or an anchoring op code etc. It skips over things -that do not influence this. For some calls, a change of option is important. -For some calls, it makes sense to skip negative forward and all backward -assertions, and also the \b assertion; for others it does not. - -Arguments: - code pointer to the start of the group - options pointer to external options - optbit the option bit whose changing is significant, or - zero if none are - skipassert TRUE if certain assertions are to be skipped - -Returns: pointer to the first significant opcode -*/ - -static const uschar* -first_significant_code(const uschar *code, int *options, int optbit, - BOOL skipassert) -{ -for (;;) - { - switch ((int)*code) - { - case OP_OPT: - if (optbit > 0 && ((int)code[1] & optbit) != (*options & optbit)) - *options = (int)code[1]; - code += 2; - break; - - case OP_ASSERT_NOT: - case OP_ASSERTBACK: - case OP_ASSERTBACK_NOT: - if (!skipassert) return code; - do code += GET(code, 1); while (*code == OP_ALT); - code += OP_lengths[*code]; - break; - - case OP_WORD_BOUNDARY: - case OP_NOT_WORD_BOUNDARY: - if (!skipassert) return code; - /* Fall through */ - - case OP_CALLOUT: - case OP_CREF: - case OP_BRANUMBER: - code += OP_lengths[*code]; - break; - - default: - return code; - } - } -/* Control never reaches here */ -} - - - - -/************************************************* -* Find the fixed length of a pattern * -*************************************************/ - -/* Scan a pattern and compute the fixed length of subject that will match it, -if the length is fixed. This is needed for dealing with backward assertions. -In UTF8 mode, the result is in characters rather than bytes. - -Arguments: - code points to the start of the pattern (the bracket) - options the compiling options - -Returns: the fixed length, or -1 if there is no fixed length, - or -2 if \C was encountered -*/ - -static int -find_fixedlength(uschar *code, int options) -{ -int length = -1; - -register int branchlength = 0; -register uschar *cc = code + 1 + LINK_SIZE; - -/* Scan along the opcodes for this branch. If we get to the end of the -branch, check the length against that of the other branches. */ - -for (;;) - { - int d; - register int op = *cc; - if (op >= OP_BRA) op = OP_BRA; - - switch (op) - { - case OP_BRA: - case OP_ONCE: - case OP_COND: - d = find_fixedlength(cc, options); - if (d < 0) return d; - branchlength += d; - do cc += GET(cc, 1); while (*cc == OP_ALT); - cc += 1 + LINK_SIZE; - break; - - /* Reached end of a branch; if it's a ket it is the end of a nested - call. If it's ALT it is an alternation in a nested call. If it is - END it's the end of the outer call. All can be handled by the same code. */ - - case OP_ALT: - case OP_KET: - case OP_KETRMAX: - case OP_KETRMIN: - case OP_END: - if (length < 0) length = branchlength; - else if (length != branchlength) return -1; - if (*cc != OP_ALT) return length; - cc += 1 + LINK_SIZE; - branchlength = 0; - break; - - /* Skip over assertive subpatterns */ - - case OP_ASSERT: - case OP_ASSERT_NOT: - case OP_ASSERTBACK: - case OP_ASSERTBACK_NOT: - do cc += GET(cc, 1); while (*cc == OP_ALT); - /* Fall through */ - - /* Skip over things that don't match chars */ - - case OP_REVERSE: - case OP_BRANUMBER: - case OP_CREF: - case OP_OPT: - case OP_CALLOUT: - case OP_SOD: - case OP_SOM: - case OP_EOD: - case OP_EODN: - case OP_CIRC: - case OP_DOLL: - case OP_NOT_WORD_BOUNDARY: - case OP_WORD_BOUNDARY: - cc += OP_lengths[*cc]; - break; - - /* Handle literal characters */ - - case OP_CHAR: - case OP_CHARNC: - branchlength++; - cc += 2; -#ifdef SUPPORT_UTF8 - if ((options & PCRE_UTF8) != 0) - { - while ((*cc & 0xc0) == 0x80) cc++; - } -#endif - break; - - /* Handle exact repetitions. The count is already in characters, but we - need to skip over a multibyte character in UTF8 mode. */ - - case OP_EXACT: - branchlength += GET2(cc,1); - cc += 4; -#ifdef SUPPORT_UTF8 - if ((options & PCRE_UTF8) != 0) - { - while((*cc & 0x80) == 0x80) cc++; - } -#endif - break; - - case OP_TYPEEXACT: - branchlength += GET2(cc,1); - cc += 4; - break; - - /* Handle single-char matchers */ - - case OP_PROP: - case OP_NOTPROP: - cc++; - /* Fall through */ - - case OP_NOT_DIGIT: - case OP_DIGIT: - case OP_NOT_WHITESPACE: - case OP_WHITESPACE: - case OP_NOT_WORDCHAR: - case OP_WORDCHAR: - case OP_ANY: - branchlength++; - cc++; - break; - - /* The single-byte matcher isn't allowed */ - - case OP_ANYBYTE: - return -2; - - /* Check a class for variable quantification */ - -#ifdef SUPPORT_UTF8 - case OP_XCLASS: - cc += GET(cc, 1) - 33; - /* Fall through */ -#endif - - case OP_CLASS: - case OP_NCLASS: - cc += 33; - - switch (*cc) - { - case OP_CRSTAR: - case OP_CRMINSTAR: - case OP_CRQUERY: - case OP_CRMINQUERY: - return -1; - - case OP_CRRANGE: - case OP_CRMINRANGE: - if (GET2(cc,1) != GET2(cc,3)) return -1; - branchlength += GET2(cc,1); - cc += 5; - break; - - default: - branchlength++; - } - break; - - /* Anything else is variable length */ - - default: - return -1; - } - } -/* Control never gets here */ -} - - - - -/************************************************* -* Scan compiled regex for numbered bracket * -*************************************************/ - -/* This little function scans through a compiled pattern until it finds a -capturing bracket with the given number. - -Arguments: - code points to start of expression - utf8 TRUE in UTF-8 mode - number the required bracket number - -Returns: pointer to the opcode for the bracket, or NULL if not found -*/ - -static const uschar * -find_bracket(const uschar *code, BOOL utf8, int number) -{ -#ifndef SUPPORT_UTF8 -utf8 = utf8; /* Stop pedantic compilers complaining */ -#endif - -for (;;) - { - register int c = *code; - if (c == OP_END) return NULL; - else if (c > OP_BRA) - { - int n = c - OP_BRA; - if (n > EXTRACT_BASIC_MAX) n = GET2(code, 2+LINK_SIZE); - if (n == number) return (uschar *)code; - code += OP_lengths[OP_BRA]; - } - else - { - code += OP_lengths[c]; - -#ifdef SUPPORT_UTF8 - - /* In UTF-8 mode, opcodes that are followed by a character may be followed - by a multi-byte character. The length in the table is a minimum, so we have - to scan along to skip the extra bytes. All opcodes are less than 128, so we - can use relatively efficient code. */ - - if (utf8) switch(c) - { - case OP_CHAR: - case OP_CHARNC: - case OP_EXACT: - case OP_UPTO: - case OP_MINUPTO: - case OP_STAR: - case OP_MINSTAR: - case OP_PLUS: - case OP_MINPLUS: - case OP_QUERY: - case OP_MINQUERY: - while ((*code & 0xc0) == 0x80) code++; - break; - - /* XCLASS is used for classes that cannot be represented just by a bit - map. This includes negated single high-valued characters. The length in - the table is zero; the actual length is stored in the compiled code. */ - - case OP_XCLASS: - code += GET(code, 1) + 1; - break; - } -#endif - } - } -} - - - -/************************************************* -* Scan compiled regex for recursion reference * -*************************************************/ - -/* This little function scans through a compiled pattern until it finds an -instance of OP_RECURSE. - -Arguments: - code points to start of expression - utf8 TRUE in UTF-8 mode - -Returns: pointer to the opcode for OP_RECURSE, or NULL if not found -*/ - -static const uschar * -find_recurse(const uschar *code, BOOL utf8) -{ -#ifndef SUPPORT_UTF8 -utf8 = utf8; /* Stop pedantic compilers complaining */ -#endif - -for (;;) - { - register int c = *code; - if (c == OP_END) return NULL; - else if (c == OP_RECURSE) return code; - else if (c > OP_BRA) - { - code += OP_lengths[OP_BRA]; - } - else - { - code += OP_lengths[c]; - -#ifdef SUPPORT_UTF8 - - /* In UTF-8 mode, opcodes that are followed by a character may be followed - by a multi-byte character. The length in the table is a minimum, so we have - to scan along to skip the extra bytes. All opcodes are less than 128, so we - can use relatively efficient code. */ - - if (utf8) switch(c) - { - case OP_CHAR: - case OP_CHARNC: - case OP_EXACT: - case OP_UPTO: - case OP_MINUPTO: - case OP_STAR: - case OP_MINSTAR: - case OP_PLUS: - case OP_MINPLUS: - case OP_QUERY: - case OP_MINQUERY: - while ((*code & 0xc0) == 0x80) code++; - break; - - /* XCLASS is used for classes that cannot be represented just by a bit - map. This includes negated single high-valued characters. The length in - the table is zero; the actual length is stored in the compiled code. */ - - case OP_XCLASS: - code += GET(code, 1) + 1; - break; - } -#endif - } - } -} - - - -/************************************************* -* Scan compiled branch for non-emptiness * -*************************************************/ - -/* This function scans through a branch of a compiled pattern to see whether it -can match the empty string or not. It is called only from could_be_empty() -below. Note that first_significant_code() skips over assertions. If we hit an -unclosed bracket, we return "empty" - this means we've struck an inner bracket -whose current branch will already have been scanned. - -Arguments: - code points to start of search - endcode points to where to stop - utf8 TRUE if in UTF8 mode - -Returns: TRUE if what is matched could be empty -*/ - -static BOOL -could_be_empty_branch(const uschar *code, const uschar *endcode, BOOL utf8) -{ -register int c; -for (code = first_significant_code(code + 1 + LINK_SIZE, NULL, 0, TRUE); - code < endcode; - code = first_significant_code(code + OP_lengths[c], NULL, 0, TRUE)) - { - const uschar *ccode; - - c = *code; - - if (c >= OP_BRA) - { - BOOL empty_branch; - if (GET(code, 1) == 0) return TRUE; /* Hit unclosed bracket */ - - /* Scan a closed bracket */ - - empty_branch = FALSE; - do - { - if (!empty_branch && could_be_empty_branch(code, endcode, utf8)) - empty_branch = TRUE; - code += GET(code, 1); - } - while (*code == OP_ALT); - if (!empty_branch) return FALSE; /* All branches are non-empty */ - code += 1 + LINK_SIZE; - c = *code; - } - - else switch (c) - { - /* Check for quantifiers after a class */ - -#ifdef SUPPORT_UTF8 - case OP_XCLASS: - ccode = code + GET(code, 1); - goto CHECK_CLASS_REPEAT; -#endif - - case OP_CLASS: - case OP_NCLASS: - ccode = code + 33; - -#ifdef SUPPORT_UTF8 - CHECK_CLASS_REPEAT: -#endif - - switch (*ccode) - { - case OP_CRSTAR: /* These could be empty; continue */ - case OP_CRMINSTAR: - case OP_CRQUERY: - case OP_CRMINQUERY: - break; - - default: /* Non-repeat => class must match */ - case OP_CRPLUS: /* These repeats aren't empty */ - case OP_CRMINPLUS: - return FALSE; - - case OP_CRRANGE: - case OP_CRMINRANGE: - if (GET2(ccode, 1) > 0) return FALSE; /* Minimum > 0 */ - break; - } - break; - - /* Opcodes that must match a character */ - - case OP_PROP: - case OP_NOTPROP: - case OP_EXTUNI: - case OP_NOT_DIGIT: - case OP_DIGIT: - case OP_NOT_WHITESPACE: - case OP_WHITESPACE: - case OP_NOT_WORDCHAR: - case OP_WORDCHAR: - case OP_ANY: - case OP_ANYBYTE: - case OP_CHAR: - case OP_CHARNC: - case OP_NOT: - case OP_PLUS: - case OP_MINPLUS: - case OP_EXACT: - case OP_NOTPLUS: - case OP_NOTMINPLUS: - case OP_NOTEXACT: - case OP_TYPEPLUS: - case OP_TYPEMINPLUS: - case OP_TYPEEXACT: - return FALSE; - - /* End of branch */ - - case OP_KET: - case OP_KETRMAX: - case OP_KETRMIN: - case OP_ALT: - return TRUE; - - /* In UTF-8 mode, STAR, MINSTAR, QUERY, MINQUERY, UPTO, and MINUPTO may be - followed by a multibyte character */ - -#ifdef SUPPORT_UTF8 - case OP_STAR: - case OP_MINSTAR: - case OP_QUERY: - case OP_MINQUERY: - case OP_UPTO: - case OP_MINUPTO: - if (utf8) while ((code[2] & 0xc0) == 0x80) code++; - break; -#endif - } - } - -return TRUE; -} - - - -/************************************************* -* Scan compiled regex for non-emptiness * -*************************************************/ - -/* This function is called to check for left recursive calls. We want to check -the current branch of the current pattern to see if it could match the empty -string. If it could, we must look outwards for branches at other levels, -stopping when we pass beyond the bracket which is the subject of the recursion. - -Arguments: - code points to start of the recursion - endcode points to where to stop (current RECURSE item) - bcptr points to the chain of current (unclosed) branch starts - utf8 TRUE if in UTF-8 mode - -Returns: TRUE if what is matched could be empty -*/ - -static BOOL -could_be_empty(const uschar *code, const uschar *endcode, branch_chain *bcptr, - BOOL utf8) -{ -while (bcptr != NULL && bcptr->current >= code) - { - if (!could_be_empty_branch(bcptr->current, endcode, utf8)) return FALSE; - bcptr = bcptr->outer; - } -return TRUE; -} - - - -/************************************************* -* Check for POSIX class syntax * -*************************************************/ - -/* This function is called when the sequence "[:" or "[." or "[=" is -encountered in a character class. It checks whether this is followed by an -optional ^ and then a sequence of letters, terminated by a matching ":]" or -".]" or "=]". - -Argument: - ptr pointer to the initial [ - endptr where to return the end pointer - cd pointer to compile data - -Returns: TRUE or FALSE -*/ - -static BOOL -check_posix_syntax(const uschar *ptr, const uschar **endptr, compile_data *cd) -{ -int terminator; /* Don't combine these lines; the Solaris cc */ -terminator = *(++ptr); /* compiler warns about "non-constant" initializer. */ -if (*(++ptr) == '^') ptr++; -while ((cd->ctypes[*ptr] & ctype_letter) != 0) ptr++; -if (*ptr == terminator && ptr[1] == ']') - { - *endptr = ptr; - return TRUE; - } -return FALSE; -} - - - - -/************************************************* -* Check POSIX class name * -*************************************************/ - -/* This function is called to check the name given in a POSIX-style class entry -such as [:alnum:]. - -Arguments: - ptr points to the first letter - len the length of the name - -Returns: a value representing the name, or -1 if unknown -*/ - -static int -check_posix_name(const uschar *ptr, int len) -{ -register int yield = 0; -while (posix_name_lengths[yield] != 0) - { - if (len == posix_name_lengths[yield] && - strncmp((const char *)ptr, posix_names[yield], len) == 0) return yield; - yield++; - } -return -1; -} - - -/************************************************* -* Adjust OP_RECURSE items in repeated group * -*************************************************/ - -/* OP_RECURSE items contain an offset from the start of the regex to the group -that is referenced. This means that groups can be replicated for fixed -repetition simply by copying (because the recursion is allowed to refer to -earlier groups that are outside the current group). However, when a group is -optional (i.e. the minimum quantifier is zero), OP_BRAZERO is inserted before -it, after it has been compiled. This means that any OP_RECURSE items within it -that refer to the group itself or any contained groups have to have their -offsets adjusted. That is the job of this function. Before it is called, the -partially compiled regex must be temporarily terminated with OP_END. - -Arguments: - group points to the start of the group - adjust the amount by which the group is to be moved - utf8 TRUE in UTF-8 mode - cd contains pointers to tables etc. - -Returns: nothing -*/ - -static void -adjust_recurse(uschar *group, int adjust, BOOL utf8, compile_data *cd) -{ -uschar *ptr = group; -while ((ptr = (uschar *)find_recurse(ptr, utf8)) != NULL) - { - int offset = GET(ptr, 1); - if (cd->start_code + offset >= group) PUT(ptr, 1, offset + adjust); - ptr += 1 + LINK_SIZE; - } -} - - - -/************************************************* -* Insert an automatic callout point * -*************************************************/ - -/* This function is called when the PCRE_AUTO_CALLOUT option is set, to insert -callout points before each pattern item. - -Arguments: - code current code pointer - ptr current pattern pointer - cd pointers to tables etc - -Returns: new code pointer -*/ - -static uschar * -auto_callout(uschar *code, const uschar *ptr, compile_data *cd) -{ -*code++ = OP_CALLOUT; -*code++ = 255; -PUT(code, 0, ptr - cd->start_pattern); /* Pattern offset */ -PUT(code, LINK_SIZE, 0); /* Default length */ -return code + 2*LINK_SIZE; -} - - - -/************************************************* -* Complete a callout item * -*************************************************/ - -/* A callout item contains the length of the next item in the pattern, which -we can't fill in till after we have reached the relevant point. This is used -for both automatic and manual callouts. - -Arguments: - previous_callout points to previous callout item - ptr current pattern pointer - cd pointers to tables etc - -Returns: nothing -*/ - -static void -complete_callout(uschar *previous_callout, const uschar *ptr, compile_data *cd) -{ -int length = ptr - cd->start_pattern - GET(previous_callout, 2); -PUT(previous_callout, 2 + LINK_SIZE, length); -} - - - -#ifdef SUPPORT_UCP -/************************************************* -* Get othercase range * -*************************************************/ - -/* This function is passed the start and end of a class range, in UTF-8 mode -with UCP support. It searches up the characters, looking for internal ranges of -characters in the "other" case. Each call returns the next one, updating the -start address. - -Arguments: - cptr points to starting character value; updated - d end value - ocptr where to put start of othercase range - odptr where to put end of othercase range - -Yield: TRUE when range returned; FALSE when no more -*/ - -static BOOL -get_othercase_range(int *cptr, int d, int *ocptr, int *odptr) -{ -int c, chartype, othercase, next; - -for (c = *cptr; c <= d; c++) - { - if (ucp_findchar(c, &chartype, &othercase) == ucp_L && othercase != 0) break; - } - -if (c > d) return FALSE; - -*ocptr = othercase; -next = othercase + 1; - -for (++c; c <= d; c++) - { - if (ucp_findchar(c, &chartype, &othercase) != ucp_L || othercase != next) - break; - next++; - } - -*odptr = next - 1; -*cptr = c; - -return TRUE; -} -#endif /* SUPPORT_UCP */ - - -/************************************************* -* Compile one branch * -*************************************************/ - -/* Scan the pattern, compiling it into the code vector. If the options are -changed during the branch, the pointer is used to change the external options -bits. - -Arguments: - optionsptr pointer to the option bits - brackets points to number of extracting brackets used - codeptr points to the pointer to the current code point - ptrptr points to the current pattern pointer - errorptr points to pointer to error message - firstbyteptr set to initial literal character, or < 0 (REQ_UNSET, REQ_NONE) - reqbyteptr set to the last literal character required, else < 0 - bcptr points to current branch chain - cd contains pointers to tables etc. - -Returns: TRUE on success - FALSE, with *errorptr set on error -*/ - -static BOOL -compile_branch(int *optionsptr, int *brackets, uschar **codeptr, - const uschar **ptrptr, const char **errorptr, int *firstbyteptr, - int *reqbyteptr, branch_chain *bcptr, compile_data *cd) -{ -int repeat_type, op_type; -int repeat_min = 0, repeat_max = 0; /* To please picky compilers */ -int bravalue = 0; -int greedy_default, greedy_non_default; -int firstbyte, reqbyte; -int zeroreqbyte, zerofirstbyte; -int req_caseopt, reqvary, tempreqvary; -int condcount = 0; -int options = *optionsptr; -int after_manual_callout = 0; -register int c; -register uschar *code = *codeptr; -uschar *tempcode; -BOOL inescq = FALSE; -BOOL groupsetfirstbyte = FALSE; -const uschar *ptr = *ptrptr; -const uschar *tempptr; -uschar *previous = NULL; -uschar *previous_callout = NULL; -uschar classbits[32]; - -#ifdef SUPPORT_UTF8 -BOOL class_utf8; -BOOL utf8 = (options & PCRE_UTF8) != 0; -uschar *class_utf8data; -uschar utf8_char[6]; -#else -BOOL utf8 = FALSE; -#endif - -/* Set up the default and non-default settings for greediness */ - -greedy_default = ((options & PCRE_UNGREEDY) != 0); -greedy_non_default = greedy_default ^ 1; - -/* Initialize no first byte, no required byte. REQ_UNSET means "no char -matching encountered yet". It gets changed to REQ_NONE if we hit something that -matches a non-fixed char first char; reqbyte just remains unset if we never -find one. - -When we hit a repeat whose minimum is zero, we may have to adjust these values -to take the zero repeat into account. This is implemented by setting them to -zerofirstbyte and zeroreqbyte when such a repeat is encountered. The individual -item types that can be repeated set these backoff variables appropriately. */ - -firstbyte = reqbyte = zerofirstbyte = zeroreqbyte = REQ_UNSET; - -/* The variable req_caseopt contains either the REQ_CASELESS value or zero, -according to the current setting of the caseless flag. REQ_CASELESS is a bit -value > 255. It is added into the firstbyte or reqbyte variables to record the -case status of the value. This is used only for ASCII characters. */ - -req_caseopt = ((options & PCRE_CASELESS) != 0)? REQ_CASELESS : 0; - -/* Switch on next character until the end of the branch */ - -for (;; ptr++) - { - BOOL negate_class; - BOOL possessive_quantifier; - BOOL is_quantifier; - int class_charcount; - int class_lastchar; - int newoptions; - int recno; - int skipbytes; - int subreqbyte; - int subfirstbyte; - int mclength; - uschar mcbuffer[8]; - - /* Next byte in the pattern */ - - c = *ptr; - - /* If in \Q...\E, check for the end; if not, we have a literal */ - - if (inescq && c != 0) - { - if (c == '\\' && ptr[1] == 'E') - { - inescq = FALSE; - ptr++; - continue; - } - else - { - if (previous_callout != NULL) - { - complete_callout(previous_callout, ptr, cd); - previous_callout = NULL; - } - if ((options & PCRE_AUTO_CALLOUT) != 0) - { - previous_callout = code; - code = auto_callout(code, ptr, cd); - } - goto NORMAL_CHAR; - } - } - - /* Fill in length of a previous callout, except when the next thing is - a quantifier. */ - - is_quantifier = c == '*' || c == '+' || c == '?' || - (c == '{' && is_counted_repeat(ptr+1)); - - if (!is_quantifier && previous_callout != NULL && - after_manual_callout-- <= 0) - { - complete_callout(previous_callout, ptr, cd); - previous_callout = NULL; - } - - /* In extended mode, skip white space and comments */ - - if ((options & PCRE_EXTENDED) != 0) - { - if ((cd->ctypes[c] & ctype_space) != 0) continue; - if (c == '#') - { - /* The space before the ; is to avoid a warning on a silly compiler - on the Macintosh. */ - while ((c = *(++ptr)) != 0 && c != NEWLINE) ; - if (c != 0) continue; /* Else fall through to handle end of string */ - } - } - - /* No auto callout for quantifiers. */ - - if ((options & PCRE_AUTO_CALLOUT) != 0 && !is_quantifier) - { - previous_callout = code; - code = auto_callout(code, ptr, cd); - } - - switch(c) - { - /* The branch terminates at end of string, |, or ). */ - - case 0: - case '|': - case ')': - *firstbyteptr = firstbyte; - *reqbyteptr = reqbyte; - *codeptr = code; - *ptrptr = ptr; - return TRUE; - - /* Handle single-character metacharacters. In multiline mode, ^ disables - the setting of any following char as a first character. */ - - case '^': - if ((options & PCRE_MULTILINE) != 0) - { - if (firstbyte == REQ_UNSET) firstbyte = REQ_NONE; - } - previous = NULL; - *code++ = OP_CIRC; - break; - - case '$': - previous = NULL; - *code++ = OP_DOLL; - break; - - /* There can never be a first char if '.' is first, whatever happens about - repeats. The value of reqbyte doesn't change either. */ - - case '.': - if (firstbyte == REQ_UNSET) firstbyte = REQ_NONE; - zerofirstbyte = firstbyte; - zeroreqbyte = reqbyte; - previous = code; - *code++ = OP_ANY; - break; - - /* Character classes. If the included characters are all < 255 in value, we - build a 32-byte bitmap of the permitted characters, except in the special - case where there is only one such character. For negated classes, we build - the map as usual, then invert it at the end. However, we use a different - opcode so that data characters > 255 can be handled correctly. - - If the class contains characters outside the 0-255 range, a different - opcode is compiled. It may optionally have a bit map for characters < 256, - but those above are are explicitly listed afterwards. A flag byte tells - whether the bitmap is present, and whether this is a negated class or not. - */ - - case '[': - previous = code; - - /* PCRE supports POSIX class stuff inside a class. Perl gives an error if - they are encountered at the top level, so we'll do that too. */ - - if ((ptr[1] == ':' || ptr[1] == '.' || ptr[1] == '=') && - check_posix_syntax(ptr, &tempptr, cd)) - { - *errorptr = (ptr[1] == ':')? ERR13 : ERR31; - goto FAILED; - } - - /* If the first character is '^', set the negation flag and skip it. */ - - if ((c = *(++ptr)) == '^') - { - negate_class = TRUE; - c = *(++ptr); - } - else - { - negate_class = FALSE; - } - - /* Keep a count of chars with values < 256 so that we can optimize the case - of just a single character (as long as it's < 256). For higher valued UTF-8 - characters, we don't yet do any optimization. */ - - class_charcount = 0; - class_lastchar = -1; - -#ifdef SUPPORT_UTF8 - class_utf8 = FALSE; /* No chars >= 256 */ - class_utf8data = code + LINK_SIZE + 34; /* For UTF-8 items */ -#endif - - /* Initialize the 32-char bit map to all zeros. We have to build the - map in a temporary bit of store, in case the class contains only 1 - character (< 256), because in that case the compiled code doesn't use the - bit map. */ - - memset(classbits, 0, 32 * sizeof(uschar)); - - /* Process characters until ] is reached. By writing this as a "do" it - means that an initial ] is taken as a data character. The first pass - through the regex checked the overall syntax, so we don't need to be very - strict here. At the start of the loop, c contains the first byte of the - character. */ - - do - { -#ifdef SUPPORT_UTF8 - if (utf8 && c > 127) - { /* Braces are required because the */ - GETCHARLEN(c, ptr, ptr); /* macro generates multiple statements */ - } -#endif - - /* Inside \Q...\E everything is literal except \E */ - - if (inescq) - { - if (c == '\\' && ptr[1] == 'E') - { - inescq = FALSE; - ptr++; - continue; - } - else goto LONE_SINGLE_CHARACTER; - } - - /* Handle POSIX class names. Perl allows a negation extension of the - form [:^name:]. A square bracket that doesn't match the syntax is - treated as a literal. We also recognize the POSIX constructions - [.ch.] and [=ch=] ("collating elements") and fault them, as Perl - 5.6 and 5.8 do. */ - - if (c == '[' && - (ptr[1] == ':' || ptr[1] == '.' || ptr[1] == '=') && - check_posix_syntax(ptr, &tempptr, cd)) - { - BOOL local_negate = FALSE; - int posix_class, i; - register const uschar *cbits = cd->cbits; - - if (ptr[1] != ':') - { - *errorptr = ERR31; - goto FAILED; - } - - ptr += 2; - if (*ptr == '^') - { - local_negate = TRUE; - ptr++; - } - - posix_class = check_posix_name(ptr, tempptr - ptr); - if (posix_class < 0) - { - *errorptr = ERR30; - goto FAILED; - } - - /* If matching is caseless, upper and lower are converted to - alpha. This relies on the fact that the class table starts with - alpha, lower, upper as the first 3 entries. */ - - if ((options & PCRE_CASELESS) != 0 && posix_class <= 2) - posix_class = 0; - - /* Or into the map we are building up to 3 of the static class - tables, or their negations. The [:blank:] class sets up the same - chars as the [:space:] class (all white space). We remove the vertical - white space chars afterwards. */ - - posix_class *= 3; - for (i = 0; i < 3; i++) - { - BOOL blankclass = strncmp((char *)ptr, "blank", 5) == 0; - int taboffset = posix_class_maps[posix_class + i]; - if (taboffset < 0) break; - if (local_negate) - { - if (i == 0) - for (c = 0; c < 32; c++) classbits[c] |= ~cbits[c+taboffset]; - else - for (c = 0; c < 32; c++) classbits[c] &= ~cbits[c+taboffset]; - if (blankclass) classbits[1] |= 0x3c; - } - else - { - for (c = 0; c < 32; c++) classbits[c] |= cbits[c+taboffset]; - if (blankclass) classbits[1] &= ~0x3c; - } - } - - ptr = tempptr + 1; - class_charcount = 10; /* Set > 1; assumes more than 1 per class */ - continue; /* End of POSIX syntax handling */ - } - - /* Backslash may introduce a single character, or it may introduce one - of the specials, which just set a flag. Escaped items are checked for - validity in the pre-compiling pass. The sequence \b is a special case. - Inside a class (and only there) it is treated as backspace. Elsewhere - it marks a word boundary. Other escapes have preset maps ready to - or into the one we are building. We assume they have more than one - character in them, so set class_charcount bigger than one. */ - - if (c == '\\') - { - c = check_escape(&ptr, errorptr, *brackets, options, TRUE); - - if (-c == ESC_b) c = '\b'; /* \b is backslash in a class */ - else if (-c == ESC_X) c = 'X'; /* \X is literal X in a class */ - else if (-c == ESC_Q) /* Handle start of quoted string */ - { - if (ptr[1] == '\\' && ptr[2] == 'E') - { - ptr += 2; /* avoid empty string */ - } - else inescq = TRUE; - continue; - } - - if (c < 0) - { - register const uschar *cbits = cd->cbits; - class_charcount += 2; /* Greater than 1 is what matters */ - switch (-c) - { - case ESC_d: - for (c = 0; c < 32; c++) classbits[c] |= cbits[c+cbit_digit]; - continue; - - case ESC_D: - for (c = 0; c < 32; c++) classbits[c] |= ~cbits[c+cbit_digit]; - continue; - - case ESC_w: - for (c = 0; c < 32; c++) classbits[c] |= cbits[c+cbit_word]; - continue; - - case ESC_W: - for (c = 0; c < 32; c++) classbits[c] |= ~cbits[c+cbit_word]; - continue; - - case ESC_s: - for (c = 0; c < 32; c++) classbits[c] |= cbits[c+cbit_space]; - classbits[1] &= ~0x08; /* Perl 5.004 onwards omits VT from \s */ - continue; - - case ESC_S: - for (c = 0; c < 32; c++) classbits[c] |= ~cbits[c+cbit_space]; - classbits[1] |= 0x08; /* Perl 5.004 onwards omits VT from \s */ - continue; - -#ifdef SUPPORT_UCP - case ESC_p: - case ESC_P: - { - BOOL negated; - int property = get_ucp(&ptr, &negated, errorptr); - if (property < 0) goto FAILED; - class_utf8 = TRUE; - *class_utf8data++ = ((-c == ESC_p) != negated)? - XCL_PROP : XCL_NOTPROP; - *class_utf8data++ = property; - class_charcount -= 2; /* Not a < 256 character */ - } - continue; -#endif - - /* Unrecognized escapes are faulted if PCRE is running in its - strict mode. By default, for compatibility with Perl, they are - treated as literals. */ - - default: - if ((options & PCRE_EXTRA) != 0) - { - *errorptr = ERR7; - goto FAILED; - } - c = *ptr; /* The final character */ - class_charcount -= 2; /* Undo the default count from above */ - } - } - - /* Fall through if we have a single character (c >= 0). This may be - > 256 in UTF-8 mode. */ - - } /* End of backslash handling */ - - /* A single character may be followed by '-' to form a range. However, - Perl does not permit ']' to be the end of the range. A '-' character - here is treated as a literal. */ - - if (ptr[1] == '-' && ptr[2] != ']') - { - int d; - ptr += 2; - -#ifdef SUPPORT_UTF8 - if (utf8) - { /* Braces are required because the */ - GETCHARLEN(d, ptr, ptr); /* macro generates multiple statements */ - } - else -#endif - d = *ptr; /* Not UTF-8 mode */ - - /* The second part of a range can be a single-character escape, but - not any of the other escapes. Perl 5.6 treats a hyphen as a literal - in such circumstances. */ - - if (d == '\\') - { - const uschar *oldptr = ptr; - d = check_escape(&ptr, errorptr, *brackets, options, TRUE); - - /* \b is backslash; \X is literal X; any other special means the '-' - was literal */ - - if (d < 0) - { - if (d == -ESC_b) d = '\b'; - else if (d == -ESC_X) d = 'X'; else - { - ptr = oldptr - 2; - goto LONE_SINGLE_CHARACTER; /* A few lines below */ - } - } - } - - /* The check that the two values are in the correct order happens in - the pre-pass. Optimize one-character ranges */ - - if (d == c) goto LONE_SINGLE_CHARACTER; /* A few lines below */ - - /* In UTF-8 mode, if the upper limit is > 255, or > 127 for caseless - matching, we have to use an XCLASS with extra data items. Caseless - matching for characters > 127 is available only if UCP support is - available. */ - -#ifdef SUPPORT_UTF8 - if (utf8 && (d > 255 || ((options & PCRE_CASELESS) != 0 && d > 127))) - { - class_utf8 = TRUE; - - /* With UCP support, we can find the other case equivalents of - the relevant characters. There may be several ranges. Optimize how - they fit with the basic range. */ - -#ifdef SUPPORT_UCP - if ((options & PCRE_CASELESS) != 0) - { - int occ, ocd; - int cc = c; - int origd = d; - while (get_othercase_range(&cc, origd, &occ, &ocd)) - { - if (occ >= c && ocd <= d) continue; /* Skip embedded ranges */ - - if (occ < c && ocd >= c - 1) /* Extend the basic range */ - { /* if there is overlap, */ - c = occ; /* noting that if occ < c */ - continue; /* we can't have ocd > d */ - } /* because a subrange is */ - if (ocd > d && occ <= d + 1) /* always shorter than */ - { /* the basic range. */ - d = ocd; - continue; - } - - if (occ == ocd) - { - *class_utf8data++ = XCL_SINGLE; - } - else - { - *class_utf8data++ = XCL_RANGE; - class_utf8data += ord2utf8(occ, class_utf8data); - } - class_utf8data += ord2utf8(ocd, class_utf8data); - } - } -#endif /* SUPPORT_UCP */ - - /* Now record the original range, possibly modified for UCP caseless - overlapping ranges. */ - - *class_utf8data++ = XCL_RANGE; - class_utf8data += ord2utf8(c, class_utf8data); - class_utf8data += ord2utf8(d, class_utf8data); - - /* With UCP support, we are done. Without UCP support, there is no - caseless matching for UTF-8 characters > 127; we can use the bit map - for the smaller ones. */ - -#ifdef SUPPORT_UCP - continue; /* With next character in the class */ -#else - if ((options & PCRE_CASELESS) == 0 || c > 127) continue; - - /* Adjust upper limit and fall through to set up the map */ - - d = 127; - -#endif /* SUPPORT_UCP */ - } -#endif /* SUPPORT_UTF8 */ - - /* We use the bit map for all cases when not in UTF-8 mode; else - ranges that lie entirely within 0-127 when there is UCP support; else - for partial ranges without UCP support. */ - - for (; c <= d; c++) - { - classbits[c/8] |= (1 << (c&7)); - if ((options & PCRE_CASELESS) != 0) - { - int uc = cd->fcc[c]; /* flip case */ - classbits[uc/8] |= (1 << (uc&7)); - } - class_charcount++; /* in case a one-char range */ - class_lastchar = c; - } - - continue; /* Go get the next char in the class */ - } - - /* Handle a lone single character - we can get here for a normal - non-escape char, or after \ that introduces a single character or for an - apparent range that isn't. */ - - LONE_SINGLE_CHARACTER: - - /* Handle a character that cannot go in the bit map */ - -#ifdef SUPPORT_UTF8 - if (utf8 && (c > 255 || ((options & PCRE_CASELESS) != 0 && c > 127))) - { - class_utf8 = TRUE; - *class_utf8data++ = XCL_SINGLE; - class_utf8data += ord2utf8(c, class_utf8data); - -#ifdef SUPPORT_UCP - if ((options & PCRE_CASELESS) != 0) - { - int chartype; - int othercase; - if (ucp_findchar(c, &chartype, &othercase) >= 0 && othercase > 0) - { - *class_utf8data++ = XCL_SINGLE; - class_utf8data += ord2utf8(othercase, class_utf8data); - } - } -#endif /* SUPPORT_UCP */ - - } - else -#endif /* SUPPORT_UTF8 */ - - /* Handle a single-byte character */ - { - classbits[c/8] |= (1 << (c&7)); - if ((options & PCRE_CASELESS) != 0) - { - c = cd->fcc[c]; /* flip case */ - classbits[c/8] |= (1 << (c&7)); - } - class_charcount++; - class_lastchar = c; - } - } - - /* Loop until ']' reached; the check for end of string happens inside the - loop. This "while" is the end of the "do" above. */ - - while ((c = *(++ptr)) != ']' || inescq); - - /* If class_charcount is 1, we saw precisely one character whose value is - less than 256. In non-UTF-8 mode we can always optimize. In UTF-8 mode, we - can optimize the negative case only if there were no characters >= 128 - because OP_NOT and the related opcodes like OP_NOTSTAR operate on - single-bytes only. This is an historical hangover. Maybe one day we can - tidy these opcodes to handle multi-byte characters. - - The optimization throws away the bit map. We turn the item into a - 1-character OP_CHAR[NC] if it's positive, or OP_NOT if it's negative. Note - that OP_NOT does not support multibyte characters. In the positive case, it - can cause firstbyte to be set. Otherwise, there can be no first char if - this item is first, whatever repeat count may follow. In the case of - reqbyte, save the previous value for reinstating. */ - -#ifdef SUPPORT_UTF8 - if (class_charcount == 1 && - (!utf8 || - (!class_utf8 && (!negate_class || class_lastchar < 128)))) - -#else - if (class_charcount == 1) -#endif - { - zeroreqbyte = reqbyte; - - /* The OP_NOT opcode works on one-byte characters only. */ - - if (negate_class) - { - if (firstbyte == REQ_UNSET) firstbyte = REQ_NONE; - zerofirstbyte = firstbyte; - *code++ = OP_NOT; - *code++ = class_lastchar; - break; - } - - /* For a single, positive character, get the value into mcbuffer, and - then we can handle this with the normal one-character code. */ - -#ifdef SUPPORT_UTF8 - if (utf8 && class_lastchar > 127) - mclength = ord2utf8(class_lastchar, mcbuffer); - else -#endif - { - mcbuffer[0] = class_lastchar; - mclength = 1; - } - goto ONE_CHAR; - } /* End of 1-char optimization */ - - /* The general case - not the one-char optimization. If this is the first - thing in the branch, there can be no first char setting, whatever the - repeat count. Any reqbyte setting must remain unchanged after any kind of - repeat. */ - - if (firstbyte == REQ_UNSET) firstbyte = REQ_NONE; - zerofirstbyte = firstbyte; - zeroreqbyte = reqbyte; - - /* If there are characters with values > 255, we have to compile an - extended class, with its own opcode. If there are no characters < 256, - we can omit the bitmap. */ - -#ifdef SUPPORT_UTF8 - if (class_utf8) - { - *class_utf8data++ = XCL_END; /* Marks the end of extra data */ - *code++ = OP_XCLASS; - code += LINK_SIZE; - *code = negate_class? XCL_NOT : 0; - - /* If the map is required, install it, and move on to the end of - the extra data */ - - if (class_charcount > 0) - { - *code++ |= XCL_MAP; - memcpy(code, classbits, 32); - code = class_utf8data; - } - - /* If the map is not required, slide down the extra data. */ - - else - { - int len = class_utf8data - (code + 33); - memmove(code + 1, code + 33, len); - code += len + 1; - } - - /* Now fill in the complete length of the item */ - - PUT(previous, 1, code - previous); - break; /* End of class handling */ - } -#endif - - /* If there are no characters > 255, negate the 32-byte map if necessary, - and copy it into the code vector. If this is the first thing in the branch, - there can be no first char setting, whatever the repeat count. Any reqbyte - setting must remain unchanged after any kind of repeat. */ - - if (negate_class) - { - *code++ = OP_NCLASS; - for (c = 0; c < 32; c++) code[c] = ~classbits[c]; - } - else - { - *code++ = OP_CLASS; - memcpy(code, classbits, 32); - } - code += 32; - break; - - /* Various kinds of repeat; '{' is not necessarily a quantifier, but this - has been tested above. */ - - case '{': - if (!is_quantifier) goto NORMAL_CHAR; - ptr = read_repeat_counts(ptr+1, &repeat_min, &repeat_max, errorptr); - if (*errorptr != NULL) goto FAILED; - goto REPEAT; - - case '*': - repeat_min = 0; - repeat_max = -1; - goto REPEAT; - - case '+': - repeat_min = 1; - repeat_max = -1; - goto REPEAT; - - case '?': - repeat_min = 0; - repeat_max = 1; - - REPEAT: - if (previous == NULL) - { - *errorptr = ERR9; - goto FAILED; - } - - if (repeat_min == 0) - { - firstbyte = zerofirstbyte; /* Adjust for zero repeat */ - reqbyte = zeroreqbyte; /* Ditto */ - } - - /* Remember whether this is a variable length repeat */ - - reqvary = (repeat_min == repeat_max)? 0 : REQ_VARY; - - op_type = 0; /* Default single-char op codes */ - possessive_quantifier = FALSE; /* Default not possessive quantifier */ - - /* Save start of previous item, in case we have to move it up to make space - for an inserted OP_ONCE for the additional '+' extension. */ - - tempcode = previous; - - /* If the next character is '+', we have a possessive quantifier. This - implies greediness, whatever the setting of the PCRE_UNGREEDY option. - If the next character is '?' this is a minimizing repeat, by default, - but if PCRE_UNGREEDY is set, it works the other way round. We change the - repeat type to the non-default. */ - - if (ptr[1] == '+') - { - repeat_type = 0; /* Force greedy */ - possessive_quantifier = TRUE; - ptr++; - } - else if (ptr[1] == '?') - { - repeat_type = greedy_non_default; - ptr++; - } - else repeat_type = greedy_default; - - /* If previous was a recursion, we need to wrap it inside brackets so that - it can be replicated if necessary. */ - - if (*previous == OP_RECURSE) - { - memmove(previous + 1 + LINK_SIZE, previous, 1 + LINK_SIZE); - code += 1 + LINK_SIZE; - *previous = OP_BRA; - PUT(previous, 1, code - previous); - *code = OP_KET; - PUT(code, 1, code - previous); - code += 1 + LINK_SIZE; - } - - /* If previous was a character match, abolish the item and generate a - repeat item instead. If a char item has a minumum of more than one, ensure - that it is set in reqbyte - it might not be if a sequence such as x{3} is - the first thing in a branch because the x will have gone into firstbyte - instead. */ - - if (*previous == OP_CHAR || *previous == OP_CHARNC) - { - /* Deal with UTF-8 characters that take up more than one byte. It's - easier to write this out separately than try to macrify it. Use c to - hold the length of the character in bytes, plus 0x80 to flag that it's a - length rather than a small character. */ - -#ifdef SUPPORT_UTF8 - if (utf8 && (code[-1] & 0x80) != 0) - { - uschar *lastchar = code - 1; - while((*lastchar & 0xc0) == 0x80) lastchar--; - c = code - lastchar; /* Length of UTF-8 character */ - memcpy(utf8_char, lastchar, c); /* Save the char */ - c |= 0x80; /* Flag c as a length */ - } - else -#endif - - /* Handle the case of a single byte - either with no UTF8 support, or - with UTF-8 disabled, or for a UTF-8 character < 128. */ - - { - c = code[-1]; - if (repeat_min > 1) reqbyte = c | req_caseopt | cd->req_varyopt; - } - - goto OUTPUT_SINGLE_REPEAT; /* Code shared with single character types */ - } - - /* If previous was a single negated character ([^a] or similar), we use - one of the special opcodes, replacing it. The code is shared with single- - character repeats by setting opt_type to add a suitable offset into - repeat_type. OP_NOT is currently used only for single-byte chars. */ - - else if (*previous == OP_NOT) - { - op_type = OP_NOTSTAR - OP_STAR; /* Use "not" opcodes */ - c = previous[1]; - goto OUTPUT_SINGLE_REPEAT; - } - - /* If previous was a character type match (\d or similar), abolish it and - create a suitable repeat item. The code is shared with single-character - repeats by setting op_type to add a suitable offset into repeat_type. Note - the the Unicode property types will be present only when SUPPORT_UCP is - defined, but we don't wrap the little bits of code here because it just - makes it horribly messy. */ - - else if (*previous < OP_EODN) - { - uschar *oldcode; - int prop_type; - op_type = OP_TYPESTAR - OP_STAR; /* Use type opcodes */ - c = *previous; - - OUTPUT_SINGLE_REPEAT: - prop_type = (*previous == OP_PROP || *previous == OP_NOTPROP)? - previous[1] : -1; - - oldcode = code; - code = previous; /* Usually overwrite previous item */ - - /* If the maximum is zero then the minimum must also be zero; Perl allows - this case, so we do too - by simply omitting the item altogether. */ - - if (repeat_max == 0) goto END_REPEAT; - - /* All real repeats make it impossible to handle partial matching (maybe - one day we will be able to remove this restriction). */ - - if (repeat_max != 1) cd->nopartial = TRUE; - - /* Combine the op_type with the repeat_type */ - - repeat_type += op_type; - - /* A minimum of zero is handled either as the special case * or ?, or as - an UPTO, with the maximum given. */ - - if (repeat_min == 0) - { - if (repeat_max == -1) *code++ = OP_STAR + repeat_type; - else if (repeat_max == 1) *code++ = OP_QUERY + repeat_type; - else - { - *code++ = OP_UPTO + repeat_type; - PUT2INC(code, 0, repeat_max); - } - } - - /* A repeat minimum of 1 is optimized into some special cases. If the - maximum is unlimited, we use OP_PLUS. Otherwise, the original item it - left in place and, if the maximum is greater than 1, we use OP_UPTO with - one less than the maximum. */ - - else if (repeat_min == 1) - { - if (repeat_max == -1) - *code++ = OP_PLUS + repeat_type; - else - { - code = oldcode; /* leave previous item in place */ - if (repeat_max == 1) goto END_REPEAT; - *code++ = OP_UPTO + repeat_type; - PUT2INC(code, 0, repeat_max - 1); - } - } - - /* The case {n,n} is just an EXACT, while the general case {n,m} is - handled as an EXACT followed by an UPTO. */ - - else - { - *code++ = OP_EXACT + op_type; /* NB EXACT doesn't have repeat_type */ - PUT2INC(code, 0, repeat_min); - - /* If the maximum is unlimited, insert an OP_STAR. Before doing so, - we have to insert the character for the previous code. For a repeated - Unicode property match, there is an extra byte that defines the - required property. In UTF-8 mode, long characters have their length in - c, with the 0x80 bit as a flag. */ - - if (repeat_max < 0) - { -#ifdef SUPPORT_UTF8 - if (utf8 && c >= 128) - { - memcpy(code, utf8_char, c & 7); - code += c & 7; - } - else -#endif - { - *code++ = c; - if (prop_type >= 0) *code++ = prop_type; - } - *code++ = OP_STAR + repeat_type; - } - - /* Else insert an UPTO if the max is greater than the min, again - preceded by the character, for the previously inserted code. */ - - else if (repeat_max != repeat_min) - { -#ifdef SUPPORT_UTF8 - if (utf8 && c >= 128) - { - memcpy(code, utf8_char, c & 7); - code += c & 7; - } - else -#endif - *code++ = c; - if (prop_type >= 0) *code++ = prop_type; - repeat_max -= repeat_min; - *code++ = OP_UPTO + repeat_type; - PUT2INC(code, 0, repeat_max); - } - } - - /* The character or character type itself comes last in all cases. */ - -#ifdef SUPPORT_UTF8 - if (utf8 && c >= 128) - { - memcpy(code, utf8_char, c & 7); - code += c & 7; - } - else -#endif - *code++ = c; - - /* For a repeated Unicode property match, there is an extra byte that - defines the required property. */ - -#ifdef SUPPORT_UCP - if (prop_type >= 0) *code++ = prop_type; -#endif - } - - /* If previous was a character class or a back reference, we put the repeat - stuff after it, but just skip the item if the repeat was {0,0}. */ - - else if (*previous == OP_CLASS || - *previous == OP_NCLASS || -#ifdef SUPPORT_UTF8 - *previous == OP_XCLASS || -#endif - *previous == OP_REF) - { - if (repeat_max == 0) - { - code = previous; - goto END_REPEAT; - } - - /* All real repeats make it impossible to handle partial matching (maybe - one day we will be able to remove this restriction). */ - - if (repeat_max != 1) cd->nopartial = TRUE; - - if (repeat_min == 0 && repeat_max == -1) - *code++ = OP_CRSTAR + repeat_type; - else if (repeat_min == 1 && repeat_max == -1) - *code++ = OP_CRPLUS + repeat_type; - else if (repeat_min == 0 && repeat_max == 1) - *code++ = OP_CRQUERY + repeat_type; - else - { - *code++ = OP_CRRANGE + repeat_type; - PUT2INC(code, 0, repeat_min); - if (repeat_max == -1) repeat_max = 0; /* 2-byte encoding for max */ - PUT2INC(code, 0, repeat_max); - } - } - - /* If previous was a bracket group, we may have to replicate it in certain - cases. */ - - else if (*previous >= OP_BRA || *previous == OP_ONCE || - *previous == OP_COND) - { - register int i; - int ketoffset = 0; - int len = code - previous; - uschar *bralink = NULL; - - /* If the maximum repeat count is unlimited, find the end of the bracket - by scanning through from the start, and compute the offset back to it - from the current code pointer. There may be an OP_OPT setting following - the final KET, so we can't find the end just by going back from the code - pointer. */ - - if (repeat_max == -1) - { - register uschar *ket = previous; - do ket += GET(ket, 1); while (*ket != OP_KET); - ketoffset = code - ket; - } - - /* The case of a zero minimum is special because of the need to stick - OP_BRAZERO in front of it, and because the group appears once in the - data, whereas in other cases it appears the minimum number of times. For - this reason, it is simplest to treat this case separately, as otherwise - the code gets far too messy. There are several special subcases when the - minimum is zero. */ - - if (repeat_min == 0) - { - /* If the maximum is also zero, we just omit the group from the output - altogether. */ - - if (repeat_max == 0) - { - code = previous; - goto END_REPEAT; - } - - /* If the maximum is 1 or unlimited, we just have to stick in the - BRAZERO and do no more at this point. However, we do need to adjust - any OP_RECURSE calls inside the group that refer to the group itself or - any internal group, because the offset is from the start of the whole - regex. Temporarily terminate the pattern while doing this. */ - - if (repeat_max <= 1) - { - *code = OP_END; - adjust_recurse(previous, 1, utf8, cd); - memmove(previous+1, previous, len); - code++; - *previous++ = OP_BRAZERO + repeat_type; - } - - /* If the maximum is greater than 1 and limited, we have to replicate - in a nested fashion, sticking OP_BRAZERO before each set of brackets. - The first one has to be handled carefully because it's the original - copy, which has to be moved up. The remainder can be handled by code - that is common with the non-zero minimum case below. We have to - adjust the value or repeat_max, since one less copy is required. Once - again, we may have to adjust any OP_RECURSE calls inside the group. */ - - else - { - int offset; - *code = OP_END; - adjust_recurse(previous, 2 + LINK_SIZE, utf8, cd); - memmove(previous + 2 + LINK_SIZE, previous, len); - code += 2 + LINK_SIZE; - *previous++ = OP_BRAZERO + repeat_type; - *previous++ = OP_BRA; - - /* We chain together the bracket offset fields that have to be - filled in later when the ends of the brackets are reached. */ - - offset = (bralink == NULL)? 0 : previous - bralink; - bralink = previous; - PUTINC(previous, 0, offset); - } - - repeat_max--; - } - - /* If the minimum is greater than zero, replicate the group as many - times as necessary, and adjust the maximum to the number of subsequent - copies that we need. If we set a first char from the group, and didn't - set a required char, copy the latter from the former. */ - - else - { - if (repeat_min > 1) - { - if (groupsetfirstbyte && reqbyte < 0) reqbyte = firstbyte; - for (i = 1; i < repeat_min; i++) - { - memcpy(code, previous, len); - code += len; - } - } - if (repeat_max > 0) repeat_max -= repeat_min; - } - - /* This code is common to both the zero and non-zero minimum cases. If - the maximum is limited, it replicates the group in a nested fashion, - remembering the bracket starts on a stack. In the case of a zero minimum, - the first one was set up above. In all cases the repeat_max now specifies - the number of additional copies needed. */ - - if (repeat_max >= 0) - { - for (i = repeat_max - 1; i >= 0; i--) - { - *code++ = OP_BRAZERO + repeat_type; - - /* All but the final copy start a new nesting, maintaining the - chain of brackets outstanding. */ - - if (i != 0) - { - int offset; - *code++ = OP_BRA; - offset = (bralink == NULL)? 0 : code - bralink; - bralink = code; - PUTINC(code, 0, offset); - } - - memcpy(code, previous, len); - code += len; - } - - /* Now chain through the pending brackets, and fill in their length - fields (which are holding the chain links pro tem). */ - - while (bralink != NULL) - { - int oldlinkoffset; - int offset = code - bralink + 1; - uschar *bra = code - offset; - oldlinkoffset = GET(bra, 1); - bralink = (oldlinkoffset == 0)? NULL : bralink - oldlinkoffset; - *code++ = OP_KET; - PUTINC(code, 0, offset); - PUT(bra, 1, offset); - } - } - - /* If the maximum is unlimited, set a repeater in the final copy. We - can't just offset backwards from the current code point, because we - don't know if there's been an options resetting after the ket. The - correct offset was computed above. */ - - else code[-ketoffset] = OP_KETRMAX + repeat_type; - } - - /* Else there's some kind of shambles */ - - else - { - *errorptr = ERR11; - goto FAILED; - } - - /* If the character following a repeat is '+', we wrap the entire repeated - item inside OP_ONCE brackets. This is just syntactic sugar, taken from - Sun's Java package. The repeated item starts at tempcode, not at previous, - which might be the first part of a string whose (former) last char we - repeated. However, we don't support '+' after a greediness '?'. */ - - if (possessive_quantifier) - { - int len = code - tempcode; - memmove(tempcode + 1+LINK_SIZE, tempcode, len); - code += 1 + LINK_SIZE; - len += 1 + LINK_SIZE; - tempcode[0] = OP_ONCE; - *code++ = OP_KET; - PUTINC(code, 0, len); - PUT(tempcode, 1, len); - } - - /* In all case we no longer have a previous item. We also set the - "follows varying string" flag for subsequently encountered reqbytes if - it isn't already set and we have just passed a varying length item. */ - - END_REPEAT: - previous = NULL; - cd->req_varyopt |= reqvary; - break; - - - /* Start of nested bracket sub-expression, or comment or lookahead or - lookbehind or option setting or condition. First deal with special things - that can come after a bracket; all are introduced by ?, and the appearance - of any of them means that this is not a referencing group. They were - checked for validity in the first pass over the string, so we don't have to - check for syntax errors here. */ - - case '(': - newoptions = options; - skipbytes = 0; - - if (*(++ptr) == '?') - { - int set, unset; - int *optset; - - switch (*(++ptr)) - { - case '#': /* Comment; skip to ket */ - ptr++; - while (*ptr != ')') ptr++; - continue; - - case ':': /* Non-extracting bracket */ - bravalue = OP_BRA; - ptr++; - break; - - case '(': - bravalue = OP_COND; /* Conditional group */ - - /* Condition to test for recursion */ - - if (ptr[1] == 'R') - { - code[1+LINK_SIZE] = OP_CREF; - PUT2(code, 2+LINK_SIZE, CREF_RECURSE); - skipbytes = 3; - ptr += 3; - } - - /* Condition to test for a numbered subpattern match. We know that - if a digit follows ( then there will just be digits until ) because - the syntax was checked in the first pass. */ - - else if ((digitab[ptr[1]] && ctype_digit) != 0) - { - int condref; /* Don't amalgamate; some compilers */ - condref = *(++ptr) - '0'; /* grumble at autoincrement in declaration */ - while (*(++ptr) != ')') condref = condref*10 + *ptr - '0'; - if (condref == 0) - { - *errorptr = ERR35; - goto FAILED; - } - ptr++; - code[1+LINK_SIZE] = OP_CREF; - PUT2(code, 2+LINK_SIZE, condref); - skipbytes = 3; - } - /* For conditions that are assertions, we just fall through, having - set bravalue above. */ - break; - - case '=': /* Positive lookahead */ - bravalue = OP_ASSERT; - ptr++; - break; - - case '!': /* Negative lookahead */ - bravalue = OP_ASSERT_NOT; - ptr++; - break; - - case '<': /* Lookbehinds */ - switch (*(++ptr)) - { - case '=': /* Positive lookbehind */ - bravalue = OP_ASSERTBACK; - ptr++; - break; - - case '!': /* Negative lookbehind */ - bravalue = OP_ASSERTBACK_NOT; - ptr++; - break; - } - break; - - case '>': /* One-time brackets */ - bravalue = OP_ONCE; - ptr++; - break; - - case 'C': /* Callout - may be followed by digits; */ - previous_callout = code; /* Save for later completion */ - after_manual_callout = 1; /* Skip one item before completing */ - *code++ = OP_CALLOUT; /* Already checked that the terminating */ - { /* closing parenthesis is present. */ - int n = 0; - while ((digitab[*(++ptr)] & ctype_digit) != 0) - n = n * 10 + *ptr - '0'; - if (n > 255) - { - *errorptr = ERR38; - goto FAILED; - } - *code++ = n; - PUT(code, 0, ptr - cd->start_pattern + 1); /* Pattern offset */ - PUT(code, LINK_SIZE, 0); /* Default length */ - code += 2 * LINK_SIZE; - } - previous = NULL; - continue; - - case 'P': /* Named subpattern handling */ - if (*(++ptr) == '<') /* Definition */ - { - int i, namelen; - uschar *slot = cd->name_table; - const uschar *name; /* Don't amalgamate; some compilers */ - name = ++ptr; /* grumble at autoincrement in declaration */ - - while (*ptr++ != '>'); - namelen = ptr - name - 1; - - for (i = 0; i < cd->names_found; i++) - { - int crc = memcmp(name, slot+2, namelen); - if (crc == 0) - { - if (slot[2+namelen] == 0) - { - *errorptr = ERR43; - goto FAILED; - } - crc = -1; /* Current name is substring */ - } - if (crc < 0) - { - memmove(slot + cd->name_entry_size, slot, - (cd->names_found - i) * cd->name_entry_size); - break; - } - slot += cd->name_entry_size; - } - - PUT2(slot, 0, *brackets + 1); - memcpy(slot + 2, name, namelen); - slot[2+namelen] = 0; - cd->names_found++; - goto NUMBERED_GROUP; - } - - if (*ptr == '=' || *ptr == '>') /* Reference or recursion */ - { - int i, namelen; - int type = *ptr++; - const uschar *name = ptr; - uschar *slot = cd->name_table; - - while (*ptr != ')') ptr++; - namelen = ptr - name; - - for (i = 0; i < cd->names_found; i++) - { - if (strncmp((char *)name, (char *)slot+2, namelen) == 0) break; - slot += cd->name_entry_size; - } - if (i >= cd->names_found) - { - *errorptr = ERR15; - goto FAILED; - } - - recno = GET2(slot, 0); - - if (type == '>') goto HANDLE_RECURSION; /* A few lines below */ - - /* Back reference */ - - previous = code; - *code++ = OP_REF; - PUT2INC(code, 0, recno); - cd->backref_map |= (recno < 32)? (1 << recno) : 1; - if (recno > cd->top_backref) cd->top_backref = recno; - continue; - } - - /* Should never happen */ - break; - - case 'R': /* Pattern recursion */ - ptr++; /* Same as (?0) */ - /* Fall through */ - - /* Recursion or "subroutine" call */ - - case '0': case '1': case '2': case '3': case '4': - case '5': case '6': case '7': case '8': case '9': - { - const uschar *called; - recno = 0; - while((digitab[*ptr] & ctype_digit) != 0) - recno = recno * 10 + *ptr++ - '0'; - - /* Come here from code above that handles a named recursion */ - - HANDLE_RECURSION: - - previous = code; - - /* Find the bracket that is being referenced. Temporarily end the - regex in case it doesn't exist. */ - - *code = OP_END; - called = (recno == 0)? - cd->start_code : find_bracket(cd->start_code, utf8, recno); - - if (called == NULL) - { - *errorptr = ERR15; - goto FAILED; - } - - /* If the subpattern is still open, this is a recursive call. We - check to see if this is a left recursion that could loop for ever, - and diagnose that case. */ - - if (GET(called, 1) == 0 && could_be_empty(called, code, bcptr, utf8)) - { - *errorptr = ERR40; - goto FAILED; - } - - /* Insert the recursion/subroutine item */ - - *code = OP_RECURSE; - PUT(code, 1, called - cd->start_code); - code += 1 + LINK_SIZE; - } - continue; - - /* Character after (? not specially recognized */ - - default: /* Option setting */ - set = unset = 0; - optset = &set; - - while (*ptr != ')' && *ptr != ':') - { - switch (*ptr++) - { - case '-': optset = &unset; break; - - case 'i': *optset |= PCRE_CASELESS; break; - case 'm': *optset |= PCRE_MULTILINE; break; - case 's': *optset |= PCRE_DOTALL; break; - case 'x': *optset |= PCRE_EXTENDED; break; - case 'U': *optset |= PCRE_UNGREEDY; break; - case 'X': *optset |= PCRE_EXTRA; break; - } - } - - /* Set up the changed option bits, but don't change anything yet. */ - - newoptions = (options | set) & (~unset); - - /* If the options ended with ')' this is not the start of a nested - group with option changes, so the options change at this level. Compile - code to change the ims options if this setting actually changes any of - them. We also pass the new setting back so that it can be put at the - start of any following branches, and when this group ends (if we are in - a group), a resetting item can be compiled. - - Note that if this item is right at the start of the pattern, the - options will have been abstracted and made global, so there will be no - change to compile. */ - - if (*ptr == ')') - { - if ((options & PCRE_IMS) != (newoptions & PCRE_IMS)) - { - *code++ = OP_OPT; - *code++ = newoptions & PCRE_IMS; - } - - /* Change options at this level, and pass them back for use - in subsequent branches. Reset the greedy defaults and the case - value for firstbyte and reqbyte. */ - - *optionsptr = options = newoptions; - greedy_default = ((newoptions & PCRE_UNGREEDY) != 0); - greedy_non_default = greedy_default ^ 1; - req_caseopt = ((options & PCRE_CASELESS) != 0)? REQ_CASELESS : 0; - - previous = NULL; /* This item can't be repeated */ - continue; /* It is complete */ - } - - /* If the options ended with ':' we are heading into a nested group - with possible change of options. Such groups are non-capturing and are - not assertions of any kind. All we need to do is skip over the ':'; - the newoptions value is handled below. */ - - bravalue = OP_BRA; - ptr++; - } - } - - /* If PCRE_NO_AUTO_CAPTURE is set, all unadorned brackets become - non-capturing and behave like (?:...) brackets */ - - else if ((options & PCRE_NO_AUTO_CAPTURE) != 0) - { - bravalue = OP_BRA; - } - - /* Else we have a referencing group; adjust the opcode. If the bracket - number is greater than EXTRACT_BASIC_MAX, we set the opcode one higher, and - arrange for the true number to follow later, in an OP_BRANUMBER item. */ - - else - { - NUMBERED_GROUP: - if (++(*brackets) > EXTRACT_BASIC_MAX) - { - bravalue = OP_BRA + EXTRACT_BASIC_MAX + 1; - code[1+LINK_SIZE] = OP_BRANUMBER; - PUT2(code, 2+LINK_SIZE, *brackets); - skipbytes = 3; - } - else bravalue = OP_BRA + *brackets; - } - - /* Process nested bracketed re. Assertions may not be repeated, but other - kinds can be. We copy code into a non-register variable in order to be able - to pass its address because some compilers complain otherwise. Pass in a - new setting for the ims options if they have changed. */ - - previous = (bravalue >= OP_ONCE)? code : NULL; - *code = bravalue; - tempcode = code; - tempreqvary = cd->req_varyopt; /* Save value before bracket */ - - if (!compile_regex( - newoptions, /* The complete new option state */ - options & PCRE_IMS, /* The previous ims option state */ - brackets, /* Extracting bracket count */ - &tempcode, /* Where to put code (updated) */ - &ptr, /* Input pointer (updated) */ - errorptr, /* Where to put an error message */ - (bravalue == OP_ASSERTBACK || - bravalue == OP_ASSERTBACK_NOT), /* TRUE if back assert */ - skipbytes, /* Skip over OP_COND/OP_BRANUMBER */ - &subfirstbyte, /* For possible first char */ - &subreqbyte, /* For possible last char */ - bcptr, /* Current branch chain */ - cd)) /* Tables block */ - goto FAILED; - - /* At the end of compiling, code is still pointing to the start of the - group, while tempcode has been updated to point past the end of the group - and any option resetting that may follow it. The pattern pointer (ptr) - is on the bracket. */ - - /* If this is a conditional bracket, check that there are no more than - two branches in the group. */ - - else if (bravalue == OP_COND) - { - uschar *tc = code; - condcount = 0; - - do { - condcount++; - tc += GET(tc,1); - } - while (*tc != OP_KET); - - if (condcount > 2) - { - *errorptr = ERR27; - goto FAILED; - } - - /* If there is just one branch, we must not make use of its firstbyte or - reqbyte, because this is equivalent to an empty second branch. */ - - if (condcount == 1) subfirstbyte = subreqbyte = REQ_NONE; - } - - /* Handle updating of the required and first characters. Update for normal - brackets of all kinds, and conditions with two branches (see code above). - If the bracket is followed by a quantifier with zero repeat, we have to - back off. Hence the definition of zeroreqbyte and zerofirstbyte outside the - main loop so that they can be accessed for the back off. */ - - zeroreqbyte = reqbyte; - zerofirstbyte = firstbyte; - groupsetfirstbyte = FALSE; - - if (bravalue >= OP_BRA || bravalue == OP_ONCE || bravalue == OP_COND) - { - /* If we have not yet set a firstbyte in this branch, take it from the - subpattern, remembering that it was set here so that a repeat of more - than one can replicate it as reqbyte if necessary. If the subpattern has - no firstbyte, set "none" for the whole branch. In both cases, a zero - repeat forces firstbyte to "none". */ - - if (firstbyte == REQ_UNSET) - { - if (subfirstbyte >= 0) - { - firstbyte = subfirstbyte; - groupsetfirstbyte = TRUE; - } - else firstbyte = REQ_NONE; - zerofirstbyte = REQ_NONE; - } - - /* If firstbyte was previously set, convert the subpattern's firstbyte - into reqbyte if there wasn't one, using the vary flag that was in - existence beforehand. */ - - else if (subfirstbyte >= 0 && subreqbyte < 0) - subreqbyte = subfirstbyte | tempreqvary; - - /* If the subpattern set a required byte (or set a first byte that isn't - really the first byte - see above), set it. */ - - if (subreqbyte >= 0) reqbyte = subreqbyte; - } - - /* For a forward assertion, we take the reqbyte, if set. This can be - helpful if the pattern that follows the assertion doesn't set a different - char. For example, it's useful for /(?=abcde).+/. We can't set firstbyte - for an assertion, however because it leads to incorrect effect for patterns - such as /(?=a)a.+/ when the "real" "a" would then become a reqbyte instead - of a firstbyte. This is overcome by a scan at the end if there's no - firstbyte, looking for an asserted first char. */ - - else if (bravalue == OP_ASSERT && subreqbyte >= 0) reqbyte = subreqbyte; - - /* Now update the main code pointer to the end of the group. */ - - code = tempcode; - - /* Error if hit end of pattern */ - - if (*ptr != ')') - { - *errorptr = ERR14; - goto FAILED; - } - break; - - /* Check \ for being a real metacharacter; if not, fall through and handle - it as a data character at the start of a string. Escape items are checked - for validity in the pre-compiling pass. */ - - case '\\': - tempptr = ptr; - c = check_escape(&ptr, errorptr, *brackets, options, FALSE); - - /* Handle metacharacters introduced by \. For ones like \d, the ESC_ values - are arranged to be the negation of the corresponding OP_values. For the - back references, the values are ESC_REF plus the reference number. Only - back references and those types that consume a character may be repeated. - We can test for values between ESC_b and ESC_Z for the latter; this may - have to change if any new ones are ever created. */ - - if (c < 0) - { - if (-c == ESC_Q) /* Handle start of quoted string */ - { - if (ptr[1] == '\\' && ptr[2] == 'E') ptr += 2; /* avoid empty string */ - else inescq = TRUE; - continue; - } - - /* For metasequences that actually match a character, we disable the - setting of a first character if it hasn't already been set. */ - - if (firstbyte == REQ_UNSET && -c > ESC_b && -c < ESC_Z) - firstbyte = REQ_NONE; - - /* Set values to reset to if this is followed by a zero repeat. */ - - zerofirstbyte = firstbyte; - zeroreqbyte = reqbyte; - - /* Back references are handled specially */ - - if (-c >= ESC_REF) - { - int number = -c - ESC_REF; - previous = code; - *code++ = OP_REF; - PUT2INC(code, 0, number); - } - - /* So are Unicode property matches, if supported. We know that get_ucp - won't fail because it was tested in the pre-pass. */ - -#ifdef SUPPORT_UCP - else if (-c == ESC_P || -c == ESC_p) - { - BOOL negated; - int value = get_ucp(&ptr, &negated, errorptr); - previous = code; - *code++ = ((-c == ESC_p) != negated)? OP_PROP : OP_NOTPROP; - *code++ = value; - } -#endif - - /* For the rest, we can obtain the OP value by negating the escape - value */ - - else - { - previous = (-c > ESC_b && -c < ESC_Z)? code : NULL; - *code++ = -c; - } - continue; - } - - /* We have a data character whose value is in c. In UTF-8 mode it may have - a value > 127. We set its representation in the length/buffer, and then - handle it as a data character. */ - -#ifdef SUPPORT_UTF8 - if (utf8 && c > 127) - mclength = ord2utf8(c, mcbuffer); - else -#endif - - { - mcbuffer[0] = c; - mclength = 1; - } - - goto ONE_CHAR; - - /* Handle a literal character. It is guaranteed not to be whitespace or # - when the extended flag is set. If we are in UTF-8 mode, it may be a - multi-byte literal character. */ - - default: - NORMAL_CHAR: - mclength = 1; - mcbuffer[0] = c; - -#ifdef SUPPORT_UTF8 - if (utf8 && (c & 0xc0) == 0xc0) - { - while ((ptr[1] & 0xc0) == 0x80) - mcbuffer[mclength++] = *(++ptr); - } -#endif - - /* At this point we have the character's bytes in mcbuffer, and the length - in mclength. When not in UTF-8 mode, the length is always 1. */ - - ONE_CHAR: - previous = code; - *code++ = ((options & PCRE_CASELESS) != 0)? OP_CHARNC : OP_CHAR; - for (c = 0; c < mclength; c++) *code++ = mcbuffer[c]; - - /* Set the first and required bytes appropriately. If no previous first - byte, set it from this character, but revert to none on a zero repeat. - Otherwise, leave the firstbyte value alone, and don't change it on a zero - repeat. */ - - if (firstbyte == REQ_UNSET) - { - zerofirstbyte = REQ_NONE; - zeroreqbyte = reqbyte; - - /* If the character is more than one byte long, we can set firstbyte - only if it is not to be matched caselessly. */ - - if (mclength == 1 || req_caseopt == 0) - { - firstbyte = mcbuffer[0] | req_caseopt; - if (mclength != 1) reqbyte = code[-1] | cd->req_varyopt; - } - else firstbyte = reqbyte = REQ_NONE; - } - - /* firstbyte was previously set; we can set reqbyte only the length is - 1 or the matching is caseful. */ - - else - { - zerofirstbyte = firstbyte; - zeroreqbyte = reqbyte; - if (mclength == 1 || req_caseopt == 0) - reqbyte = code[-1] | req_caseopt | cd->req_varyopt; - } - - break; /* End of literal character handling */ - } - } /* end of big loop */ - -/* Control never reaches here by falling through, only by a goto for all the -error states. Pass back the position in the pattern so that it can be displayed -to the user for diagnosing the error. */ - -FAILED: -*ptrptr = ptr; -return FALSE; -} - - - - -/************************************************* -* Compile sequence of alternatives * -*************************************************/ - -/* On entry, ptr is pointing past the bracket character, but on return -it points to the closing bracket, or vertical bar, or end of string. -The code variable is pointing at the byte into which the BRA operator has been -stored. If the ims options are changed at the start (for a (?ims: group) or -during any branch, we need to insert an OP_OPT item at the start of every -following branch to ensure they get set correctly at run time, and also pass -the new options into every subsequent branch compile. - -Argument: - options option bits, including any changes for this subpattern - oldims previous settings of ims option bits - brackets -> int containing the number of extracting brackets used - codeptr -> the address of the current code pointer - ptrptr -> the address of the current pattern pointer - errorptr -> pointer to error message - lookbehind TRUE if this is a lookbehind assertion - skipbytes skip this many bytes at start (for OP_COND, OP_BRANUMBER) - firstbyteptr place to put the first required character, or a negative number - reqbyteptr place to put the last required character, or a negative number - bcptr pointer to the chain of currently open branches - cd points to the data block with tables pointers etc. - -Returns: TRUE on success -*/ - -static BOOL -compile_regex(int options, int oldims, int *brackets, uschar **codeptr, - const uschar **ptrptr, const char **errorptr, BOOL lookbehind, int skipbytes, - int *firstbyteptr, int *reqbyteptr, branch_chain *bcptr, compile_data *cd) -{ -const uschar *ptr = *ptrptr; -uschar *code = *codeptr; -uschar *last_branch = code; -uschar *start_bracket = code; -uschar *reverse_count = NULL; -int firstbyte, reqbyte; -int branchfirstbyte, branchreqbyte; -branch_chain bc; - -bc.outer = bcptr; -bc.current = code; - -firstbyte = reqbyte = REQ_UNSET; - -/* Offset is set zero to mark that this bracket is still open */ - -PUT(code, 1, 0); -code += 1 + LINK_SIZE + skipbytes; - -/* Loop for each alternative branch */ - -for (;;) - { - /* Handle a change of ims options at the start of the branch */ - - if ((options & PCRE_IMS) != oldims) - { - *code++ = OP_OPT; - *code++ = options & PCRE_IMS; - } - - /* Set up dummy OP_REVERSE if lookbehind assertion */ - - if (lookbehind) - { - *code++ = OP_REVERSE; - reverse_count = code; - PUTINC(code, 0, 0); - } - - /* Now compile the branch */ - - if (!compile_branch(&options, brackets, &code, &ptr, errorptr, - &branchfirstbyte, &branchreqbyte, &bc, cd)) - { - *ptrptr = ptr; - return FALSE; - } - - /* If this is the first branch, the firstbyte and reqbyte values for the - branch become the values for the regex. */ - - if (*last_branch != OP_ALT) - { - firstbyte = branchfirstbyte; - reqbyte = branchreqbyte; - } - - /* If this is not the first branch, the first char and reqbyte have to - match the values from all the previous branches, except that if the previous - value for reqbyte didn't have REQ_VARY set, it can still match, and we set - REQ_VARY for the regex. */ - - else - { - /* If we previously had a firstbyte, but it doesn't match the new branch, - we have to abandon the firstbyte for the regex, but if there was previously - no reqbyte, it takes on the value of the old firstbyte. */ - - if (firstbyte >= 0 && firstbyte != branchfirstbyte) - { - if (reqbyte < 0) reqbyte = firstbyte; - firstbyte = REQ_NONE; - } - - /* If we (now or from before) have no firstbyte, a firstbyte from the - branch becomes a reqbyte if there isn't a branch reqbyte. */ - - if (firstbyte < 0 && branchfirstbyte >= 0 && branchreqbyte < 0) - branchreqbyte = branchfirstbyte; - - /* Now ensure that the reqbytes match */ - - if ((reqbyte & ~REQ_VARY) != (branchreqbyte & ~REQ_VARY)) - reqbyte = REQ_NONE; - else reqbyte |= branchreqbyte; /* To "or" REQ_VARY */ - } - - /* If lookbehind, check that this branch matches a fixed-length string, - and put the length into the OP_REVERSE item. Temporarily mark the end of - the branch with OP_END. */ - - if (lookbehind) - { - int length; - *code = OP_END; - length = find_fixedlength(last_branch, options); - DPRINTF(("fixed length = %d\n", length)); - if (length < 0) - { - *errorptr = (length == -2)? ERR36 : ERR25; - *ptrptr = ptr; - return FALSE; - } - PUT(reverse_count, 0, length); - } - - /* Reached end of expression, either ')' or end of pattern. Go back through - the alternative branches and reverse the chain of offsets, with the field in - the BRA item now becoming an offset to the first alternative. If there are - no alternatives, it points to the end of the group. The length in the - terminating ket is always the length of the whole bracketed item. If any of - the ims options were changed inside the group, compile a resetting op-code - following, except at the very end of the pattern. Return leaving the pointer - at the terminating char. */ - - if (*ptr != '|') - { - int length = code - last_branch; - do - { - int prev_length = GET(last_branch, 1); - PUT(last_branch, 1, length); - length = prev_length; - last_branch -= length; - } - while (length > 0); - - /* Fill in the ket */ - - *code = OP_KET; - PUT(code, 1, code - start_bracket); - code += 1 + LINK_SIZE; - - /* Resetting option if needed */ - - if ((options & PCRE_IMS) != oldims && *ptr == ')') - { - *code++ = OP_OPT; - *code++ = oldims; - } - - /* Set values to pass back */ - - *codeptr = code; - *ptrptr = ptr; - *firstbyteptr = firstbyte; - *reqbyteptr = reqbyte; - return TRUE; - } - - /* Another branch follows; insert an "or" node. Its length field points back - to the previous branch while the bracket remains open. At the end the chain - is reversed. It's done like this so that the start of the bracket has a - zero offset until it is closed, making it possible to detect recursion. */ - - *code = OP_ALT; - PUT(code, 1, code - last_branch); - bc.current = last_branch = code; - code += 1 + LINK_SIZE; - ptr++; - } -/* Control never reaches here */ -} - - - - -/************************************************* -* Check for anchored expression * -*************************************************/ - -/* Try to find out if this is an anchored regular expression. Consider each -alternative branch. If they all start with OP_SOD or OP_CIRC, or with a bracket -all of whose alternatives start with OP_SOD or OP_CIRC (recurse ad lib), then -it's anchored. However, if this is a multiline pattern, then only OP_SOD -counts, since OP_CIRC can match in the middle. - -We can also consider a regex to be anchored if OP_SOM starts all its branches. -This is the code for \G, which means "match at start of match position, taking -into account the match offset". - -A branch is also implicitly anchored if it starts with .* and DOTALL is set, -because that will try the rest of the pattern at all possible matching points, -so there is no point trying again.... er .... - -.... except when the .* appears inside capturing parentheses, and there is a -subsequent back reference to those parentheses. We haven't enough information -to catch that case precisely. - -At first, the best we could do was to detect when .* was in capturing brackets -and the highest back reference was greater than or equal to that level. -However, by keeping a bitmap of the first 31 back references, we can catch some -of the more common cases more precisely. - -Arguments: - code points to start of expression (the bracket) - options points to the options setting - bracket_map a bitmap of which brackets we are inside while testing; this - handles up to substring 31; after that we just have to take - the less precise approach - backref_map the back reference bitmap - -Returns: TRUE or FALSE -*/ - -static BOOL -is_anchored(register const uschar *code, int *options, unsigned int bracket_map, - unsigned int backref_map) -{ -do { - const uschar *scode = - first_significant_code(code + 1+LINK_SIZE, options, PCRE_MULTILINE, FALSE); - register int op = *scode; - - /* Capturing brackets */ - - if (op > OP_BRA) - { - int new_map; - op -= OP_BRA; - if (op > EXTRACT_BASIC_MAX) op = GET2(scode, 2+LINK_SIZE); - new_map = bracket_map | ((op < 32)? (1 << op) : 1); - if (!is_anchored(scode, options, new_map, backref_map)) return FALSE; - } - - /* Other brackets */ - - else if (op == OP_BRA || op == OP_ASSERT || op == OP_ONCE || op == OP_COND) - { - if (!is_anchored(scode, options, bracket_map, backref_map)) return FALSE; - } - - /* .* is not anchored unless DOTALL is set and it isn't in brackets that - are or may be referenced. */ - - else if ((op == OP_TYPESTAR || op == OP_TYPEMINSTAR) && - (*options & PCRE_DOTALL) != 0) - { - if (scode[1] != OP_ANY || (bracket_map & backref_map) != 0) return FALSE; - } - - /* Check for explicit anchoring */ - - else if (op != OP_SOD && op != OP_SOM && - ((*options & PCRE_MULTILINE) != 0 || op != OP_CIRC)) - return FALSE; - code += GET(code, 1); - } -while (*code == OP_ALT); /* Loop for each alternative */ -return TRUE; -} - - - -/************************************************* -* Check for starting with ^ or .* * -*************************************************/ - -/* This is called to find out if every branch starts with ^ or .* so that -"first char" processing can be done to speed things up in multiline -matching and for non-DOTALL patterns that start with .* (which must start at -the beginning or after \n). As in the case of is_anchored() (see above), we -have to take account of back references to capturing brackets that contain .* -because in that case we can't make the assumption. - -Arguments: - code points to start of expression (the bracket) - bracket_map a bitmap of which brackets we are inside while testing; this - handles up to substring 31; after that we just have to take - the less precise approach - backref_map the back reference bitmap - -Returns: TRUE or FALSE -*/ - -static BOOL -is_startline(const uschar *code, unsigned int bracket_map, - unsigned int backref_map) -{ -do { - const uschar *scode = first_significant_code(code + 1+LINK_SIZE, NULL, 0, - FALSE); - register int op = *scode; - - /* Capturing brackets */ - - if (op > OP_BRA) - { - int new_map; - op -= OP_BRA; - if (op > EXTRACT_BASIC_MAX) op = GET2(scode, 2+LINK_SIZE); - new_map = bracket_map | ((op < 32)? (1 << op) : 1); - if (!is_startline(scode, new_map, backref_map)) return FALSE; - } - - /* Other brackets */ - - else if (op == OP_BRA || op == OP_ASSERT || op == OP_ONCE || op == OP_COND) - { if (!is_startline(scode, bracket_map, backref_map)) return FALSE; } - - /* .* means "start at start or after \n" if it isn't in brackets that - may be referenced. */ - - else if (op == OP_TYPESTAR || op == OP_TYPEMINSTAR) - { - if (scode[1] != OP_ANY || (bracket_map & backref_map) != 0) return FALSE; - } - - /* Check for explicit circumflex */ - - else if (op != OP_CIRC) return FALSE; - - /* Move on to the next alternative */ - - code += GET(code, 1); - } -while (*code == OP_ALT); /* Loop for each alternative */ -return TRUE; -} - - - -/************************************************* -* Check for asserted fixed first char * -*************************************************/ - -/* During compilation, the "first char" settings from forward assertions are -discarded, because they can cause conflicts with actual literals that follow. -However, if we end up without a first char setting for an unanchored pattern, -it is worth scanning the regex to see if there is an initial asserted first -char. If all branches start with the same asserted char, or with a bracket all -of whose alternatives start with the same asserted char (recurse ad lib), then -we return that char, otherwise -1. - -Arguments: - code points to start of expression (the bracket) - options pointer to the options (used to check casing changes) - inassert TRUE if in an assertion - -Returns: -1 or the fixed first char -*/ - -static int -find_firstassertedchar(const uschar *code, int *options, BOOL inassert) -{ -register int c = -1; -do { - int d; - const uschar *scode = - first_significant_code(code + 1+LINK_SIZE, options, PCRE_CASELESS, TRUE); - register int op = *scode; - - if (op >= OP_BRA) op = OP_BRA; - - switch(op) - { - default: - return -1; - - case OP_BRA: - case OP_ASSERT: - case OP_ONCE: - case OP_COND: - if ((d = find_firstassertedchar(scode, options, op == OP_ASSERT)) < 0) - return -1; - if (c < 0) c = d; else if (c != d) return -1; - break; - - case OP_EXACT: /* Fall through */ - scode += 2; - - case OP_CHAR: - case OP_CHARNC: - case OP_PLUS: - case OP_MINPLUS: - if (!inassert) return -1; - if (c < 0) - { - c = scode[1]; - if ((*options & PCRE_CASELESS) != 0) c |= REQ_CASELESS; - } - else if (c != scode[1]) return -1; - break; - } - - code += GET(code, 1); - } -while (*code == OP_ALT); -return c; -} - - - - -#ifdef SUPPORT_UTF8 -/************************************************* -* Validate a UTF-8 string * -*************************************************/ - -/* This function is called (optionally) at the start of compile or match, to -validate that a supposed UTF-8 string is actually valid. The early check means -that subsequent code can assume it is dealing with a valid string. The check -can be turned off for maximum performance, but then consequences of supplying -an invalid string are then undefined. - -Arguments: - string points to the string - length length of string, or -1 if the string is zero-terminated - -Returns: < 0 if the string is a valid UTF-8 string - >= 0 otherwise; the value is the offset of the bad byte -*/ - -static int -valid_utf8(const uschar *string, int length) -{ -register const uschar *p; - -if (length < 0) - { - for (p = string; *p != 0; p++); - length = p - string; - } - -for (p = string; length-- > 0; p++) - { - register int ab; - register int c = *p; - if (c < 128) continue; - if ((c & 0xc0) != 0xc0) return p - string; - ab = utf8_table4[c & 0x3f]; /* Number of additional bytes */ - if (length < ab) return p - string; - length -= ab; - - /* Check top bits in the second byte */ - if ((*(++p) & 0xc0) != 0x80) return p - string; - - /* Check for overlong sequences for each different length */ - switch (ab) - { - /* Check for xx00 000x */ - case 1: - if ((c & 0x3e) == 0) return p - string; - continue; /* We know there aren't any more bytes to check */ - - /* Check for 1110 0000, xx0x xxxx */ - case 2: - if (c == 0xe0 && (*p & 0x20) == 0) return p - string; - break; - - /* Check for 1111 0000, xx00 xxxx */ - case 3: - if (c == 0xf0 && (*p & 0x30) == 0) return p - string; - break; - - /* Check for 1111 1000, xx00 0xxx */ - case 4: - if (c == 0xf8 && (*p & 0x38) == 0) return p - string; - break; - - /* Check for leading 0xfe or 0xff, and then for 1111 1100, xx00 00xx */ - case 5: - if (c == 0xfe || c == 0xff || - (c == 0xfc && (*p & 0x3c) == 0)) return p - string; - break; - } - - /* Check for valid bytes after the 2nd, if any; all must start 10 */ - while (--ab > 0) - { - if ((*(++p) & 0xc0) != 0x80) return p - string; - } - } - -return -1; -} -#endif - - - -/************************************************* -* Compile a Regular Expression * -*************************************************/ - -/* This function takes a string and returns a pointer to a block of store -holding a compiled version of the expression. - -Arguments: - pattern the regular expression - options various option bits - errorptr pointer to pointer to error text - erroroffset ptr offset in pattern where error was detected - tables pointer to character tables or NULL - -Returns: pointer to compiled data block, or NULL on error, - with errorptr and erroroffset set -*/ - -EXPORT pcre * -pcre_compile(const char *pattern, int options, const char **errorptr, - int *erroroffset, const unsigned char *tables) -{ -real_pcre *re; -int length = 1 + LINK_SIZE; /* For initial BRA plus length */ -//int runlength; -int c, firstbyte, reqbyte; -int bracount = 0; -int branch_extra = 0; -int branch_newextra; -int item_count = -1; -int name_count = 0; -int max_name_size = 0; -int lastitemlength = 0; -#ifdef SUPPORT_UTF8 -BOOL utf8; -BOOL class_utf8; -#endif -BOOL inescq = FALSE; -unsigned int brastackptr = 0; -size_t size; -uschar *code; -const uschar *codestart; -const uschar *ptr; -compile_data compile_block; -int brastack[BRASTACK_SIZE]; -uschar bralenstack[BRASTACK_SIZE]; - -/* We can't pass back an error message if errorptr is NULL; I guess the best we -can do is just return NULL. */ - -if (errorptr == NULL) return NULL; -*errorptr = NULL; - -/* However, we can give a message for this error */ - -if (erroroffset == NULL) - { - *errorptr = ERR16; - return NULL; - } -*erroroffset = 0; - -/* Can't support UTF8 unless PCRE has been compiled to include the code. */ - -#ifdef SUPPORT_UTF8 -utf8 = (options & PCRE_UTF8) != 0; -if (utf8 && (options & PCRE_NO_UTF8_CHECK) == 0 && - (*erroroffset = valid_utf8((uschar *)pattern, -1)) >= 0) - { - *errorptr = ERR44; - return NULL; - } -#else -if ((options & PCRE_UTF8) != 0) - { - *errorptr = ERR32; - return NULL; - } -#endif - -if ((options & ~PUBLIC_OPTIONS) != 0) - { - *errorptr = ERR17; - return NULL; - } - -/* Set up pointers to the individual character tables */ - -if (tables == NULL) tables = pcre_default_tables; -compile_block.lcc = tables + lcc_offset; -compile_block.fcc = tables + fcc_offset; -compile_block.cbits = tables + cbits_offset; -compile_block.ctypes = tables + ctypes_offset; - -/* Maximum back reference and backref bitmap. This is updated for numeric -references during the first pass, but for named references during the actual -compile pass. The bitmap records up to 31 back references to help in deciding -whether (.*) can be treated as anchored or not. */ - -compile_block.top_backref = 0; -compile_block.backref_map = 0; - -/* Reflect pattern for debugging output */ - -DPRINTF(("------------------------------------------------------------------\n")); -DPRINTF(("%s\n", pattern)); - -/* The first thing to do is to make a pass over the pattern to compute the -amount of store required to hold the compiled code. This does not have to be -perfect as long as errors are overestimates. At the same time we can detect any -flag settings right at the start, and extract them. Make an attempt to correct -for any counted white space if an "extended" flag setting appears late in the -pattern. We can't be so clever for #-comments. */ - -ptr = (const uschar *)(pattern - 1); -while ((c = *(++ptr)) != 0) - { - int min, max; - int class_optcount; - int bracket_length; - int duplength; - - /* If we are inside a \Q...\E sequence, all chars are literal */ - - if (inescq) - { - if ((options & PCRE_AUTO_CALLOUT) != 0) length += 2 + 2*LINK_SIZE; - goto NORMAL_CHAR; - } - - /* Otherwise, first check for ignored whitespace and comments */ - - if ((options & PCRE_EXTENDED) != 0) - { - if ((compile_block.ctypes[c] & ctype_space) != 0) continue; - if (c == '#') - { - /* The space before the ; is to avoid a warning on a silly compiler - on the Macintosh. */ - while ((c = *(++ptr)) != 0 && c != NEWLINE) ; - if (c == 0) break; - continue; - } - } - - item_count++; /* Is zero for the first non-comment item */ - - /* Allow space for auto callout before every item except quantifiers. */ - - if ((options & PCRE_AUTO_CALLOUT) != 0 && - c != '*' && c != '+' && c != '?' && - (c != '{' || !is_counted_repeat(ptr + 1))) - length += 2 + 2*LINK_SIZE; - - switch(c) - { - /* A backslashed item may be an escaped data character or it may be a - character type. */ - - case '\\': - c = check_escape(&ptr, errorptr, bracount, options, FALSE); - if (*errorptr != NULL) goto PCRE_ERROR_RETURN; - - lastitemlength = 1; /* Default length of last item for repeats */ - - if (c >= 0) /* Data character */ - { - length += 2; /* For a one-byte character */ - -#ifdef SUPPORT_UTF8 - if (utf8 && c > 127) - { - int i; - for (i = 0; i < sizeof(utf8_table1)/sizeof(int); i++) - if (c <= utf8_table1[i]) break; - length += i; - lastitemlength += i; - } -#endif - - continue; - } - - /* If \Q, enter "literal" mode */ - - if (-c == ESC_Q) - { - inescq = TRUE; - continue; - } - - /* \X is supported only if Unicode property support is compiled */ - -#ifndef SUPPORT_UCP - if (-c == ESC_X) - { - *errorptr = ERR45; - goto PCRE_ERROR_RETURN; - } -#endif - - /* \P and \p are for Unicode properties, but only when the support has - been compiled. Each item needs 2 bytes. */ - - else if (-c == ESC_P || -c == ESC_p) - { -#ifdef SUPPORT_UCP - BOOL negated; - length += 2; - lastitemlength = 2; - if (get_ucp(&ptr, &negated, errorptr) < 0) goto PCRE_ERROR_RETURN; - continue; -#else - *errorptr = ERR45; - goto PCRE_ERROR_RETURN; -#endif - } - - /* Other escapes need one byte */ - - length++; - - /* A back reference needs an additional 2 bytes, plus either one or 5 - bytes for a repeat. We also need to keep the value of the highest - back reference. */ - - if (c <= -ESC_REF) - { - int refnum = -c - ESC_REF; - compile_block.backref_map |= (refnum < 32)? (1 << refnum) : 1; - if (refnum > compile_block.top_backref) - compile_block.top_backref = refnum; - length += 2; /* For single back reference */ - if (ptr[1] == '{' && is_counted_repeat(ptr+2)) - { - ptr = read_repeat_counts(ptr+2, &min, &max, errorptr); - if (*errorptr != NULL) goto PCRE_ERROR_RETURN; - if ((min == 0 && (max == 1 || max == -1)) || - (min == 1 && max == -1)) - length++; - else length += 5; - if (ptr[1] == '?') ptr++; - } - } - continue; - - case '^': /* Single-byte metacharacters */ - case '.': - case '$': - length++; - lastitemlength = 1; - continue; - - case '*': /* These repeats won't be after brackets; */ - case '+': /* those are handled separately */ - case '?': - length++; - goto POSESSIVE; /* A few lines below */ - - /* This covers the cases of braced repeats after a single char, metachar, - class, or back reference. */ - - case '{': - if (!is_counted_repeat(ptr+1)) goto NORMAL_CHAR; - ptr = read_repeat_counts(ptr+1, &min, &max, errorptr); - if (*errorptr != NULL) goto PCRE_ERROR_RETURN; - - /* These special cases just insert one extra opcode */ - - if ((min == 0 && (max == 1 || max == -1)) || - (min == 1 && max == -1)) - length++; - - /* These cases might insert additional copies of a preceding character. */ - - else - { - if (min != 1) - { - length -= lastitemlength; /* Uncount the original char or metachar */ - if (min > 0) length += 3 + lastitemlength; - } - length += lastitemlength + ((max > 0)? 3 : 1); - } - - if (ptr[1] == '?') ptr++; /* Needs no extra length */ - - POSESSIVE: /* Test for possessive quantifier */ - if (ptr[1] == '+') - { - ptr++; - length += 2 + 2*LINK_SIZE; /* Allow for atomic brackets */ - } - continue; - - /* An alternation contains an offset to the next branch or ket. If any ims - options changed in the previous branch(es), and/or if we are in a - lookbehind assertion, extra space will be needed at the start of the - branch. This is handled by branch_extra. */ - - case '|': - length += 1 + LINK_SIZE + branch_extra; - continue; - - /* A character class uses 33 characters provided that all the character - values are less than 256. Otherwise, it uses a bit map for low valued - characters, and individual items for others. Don't worry about character - types that aren't allowed in classes - they'll get picked up during the - compile. A character class that contains only one single-byte character - uses 2 or 3 bytes, depending on whether it is negated or not. Notice this - where we can. (In UTF-8 mode we can do this only for chars < 128.) */ - - case '[': - if (*(++ptr) == '^') - { - class_optcount = 10; /* Greater than one */ - ptr++; - } - else class_optcount = 0; - -#ifdef SUPPORT_UTF8 - class_utf8 = FALSE; -#endif - - /* Written as a "do" so that an initial ']' is taken as data */ - - if (*ptr != 0) do - { - /* Inside \Q...\E everything is literal except \E */ - - if (inescq) - { - if (*ptr != '\\' || ptr[1] != 'E') goto GET_ONE_CHARACTER; - inescq = FALSE; - ptr += 1; - continue; - } - - /* Outside \Q...\E, check for escapes */ - - if (*ptr == '\\') - { - c = check_escape(&ptr, errorptr, bracount, options, TRUE); - if (*errorptr != NULL) goto PCRE_ERROR_RETURN; - - /* \b is backspace inside a class; \X is literal */ - - if (-c == ESC_b) c = '\b'; - else if (-c == ESC_X) c = 'X'; - - /* \Q enters quoting mode */ - - else if (-c == ESC_Q) - { - inescq = TRUE; - continue; - } - - /* Handle escapes that turn into characters */ - - if (c >= 0) goto NON_SPECIAL_CHARACTER; - - /* Escapes that are meta-things. The normal ones just affect the - bit map, but Unicode properties require an XCLASS extended item. */ - - else - { - class_optcount = 10; /* \d, \s etc; make sure > 1 */ -#ifdef SUPPORT_UTF8 - if (-c == ESC_p || -c == ESC_P) - { - if (!class_utf8) - { - class_utf8 = TRUE; - length += LINK_SIZE + 2; - } - length += 2; - } -#endif - } - } - - /* Check the syntax for POSIX stuff. The bits we actually handle are - checked during the real compile phase. */ - - else if (*ptr == '[' && check_posix_syntax(ptr, &ptr, &compile_block)) - { - ptr++; - class_optcount = 10; /* Make sure > 1 */ - } - - /* Anything else increments the possible optimization count. We have to - detect ranges here so that we can compute the number of extra ranges for - caseless wide characters when UCP support is available. If there are wide - characters, we are going to have to use an XCLASS, even for single - characters. */ - - else - { - int d; - - GET_ONE_CHARACTER: - -#ifdef SUPPORT_UTF8 - if (utf8) - { - int extra = 0; - GETCHARLEN(c, ptr, extra); - ptr += extra; - } - else c = *ptr; -#else - c = *ptr; -#endif - - /* Come here from handling \ above when it escapes to a char value */ - - NON_SPECIAL_CHARACTER: - class_optcount++; - - d = -1; - if (ptr[1] == '-') - { - uschar const *hyptr = ptr++; - if (ptr[1] == '\\') - { - ptr++; - d = check_escape(&ptr, errorptr, bracount, options, TRUE); - if (*errorptr != NULL) goto PCRE_ERROR_RETURN; - if (-d == ESC_b) d = '\b'; /* backspace */ - else if (-d == ESC_X) d = 'X'; /* literal X in a class */ - } - else if (ptr[1] != 0 && ptr[1] != ']') - { - ptr++; -#ifdef SUPPORT_UTF8 - if (utf8) - { - int extra = 0; - GETCHARLEN(d, ptr, extra); - ptr += extra; - } - else -#endif - d = *ptr; - } - if (d < 0) ptr = hyptr; /* go back to hyphen as data */ - } - - /* If d >= 0 we have a range. In UTF-8 mode, if the end is > 255, or > - 127 for caseless matching, we will need to use an XCLASS. */ - - if (d >= 0) - { - class_optcount = 10; /* Ensure > 1 */ - if (d < c) - { - *errorptr = ERR8; - goto PCRE_ERROR_RETURN; - } - -#ifdef SUPPORT_UTF8 - if (utf8 && (d > 255 || ((options & PCRE_CASELESS) != 0 && d > 127))) - { - uschar buffer[6]; - if (!class_utf8) /* Allow for XCLASS overhead */ - { - class_utf8 = TRUE; - length += LINK_SIZE + 2; - } - -#ifdef SUPPORT_UCP - /* If we have UCP support, find out how many extra ranges are - needed to map the other case of characters within this range. We - have to mimic the range optimization here, because extending the - range upwards might push d over a boundary that makes is use - another byte in the UTF-8 representation. */ - - if ((options & PCRE_CASELESS) != 0) - { - int occ, ocd; - int cc = c; - int origd = d; - while (get_othercase_range(&cc, origd, &occ, &ocd)) - { - if (occ >= c && ocd <= d) continue; /* Skip embedded */ - - if (occ < c && ocd >= c - 1) /* Extend the basic range */ - { /* if there is overlap, */ - c = occ; /* noting that if occ < c */ - continue; /* we can't have ocd > d */ - } /* because a subrange is */ - if (ocd > d && occ <= d + 1) /* always shorter than */ - { /* the basic range. */ - d = ocd; - continue; - } - - /* An extra item is needed */ - - length += 1 + ord2utf8(occ, buffer) + - ((occ == ocd)? 0 : ord2utf8(ocd, buffer)); - } - } -#endif /* SUPPORT_UCP */ - - /* The length of the (possibly extended) range */ - - length += 1 + ord2utf8(c, buffer) + ord2utf8(d, buffer); - } -#endif /* SUPPORT_UTF8 */ - - } - - /* We have a single character. There is nothing to be done unless we - are in UTF-8 mode. If the char is > 255, or 127 when caseless, we must - allow for an XCL_SINGLE item, doubled for caselessness if there is UCP - support. */ - - else - { -#ifdef SUPPORT_UTF8 - if (utf8 && (c > 255 || ((options & PCRE_CASELESS) != 0 && c > 127))) - { - uschar buffer[6]; - class_optcount = 10; /* Ensure > 1 */ - if (!class_utf8) /* Allow for XCLASS overhead */ - { - class_utf8 = TRUE; - length += LINK_SIZE + 2; - } -#ifdef SUPPORT_UCP - length += (((options & PCRE_CASELESS) != 0)? 2 : 1) * - (1 + ord2utf8(c, buffer)); -#else /* SUPPORT_UCP */ - length += 1 + ord2utf8(c, buffer); -#endif /* SUPPORT_UCP */ - } -#endif /* SUPPORT_UTF8 */ - } - } - } - while (*(++ptr) != 0 && (inescq || *ptr != ']')); /* Concludes "do" above */ - - if (*ptr == 0) /* Missing terminating ']' */ - { - *errorptr = ERR6; - goto PCRE_ERROR_RETURN; - } - - /* We can optimize when there was only one optimizable character. Repeats - for positive and negated single one-byte chars are handled by the general - code. Here, we handle repeats for the class opcodes. */ - - if (class_optcount == 1) length += 3; else - { - length += 33; - - /* A repeat needs either 1 or 5 bytes. If it is a possessive quantifier, - we also need extra for wrapping the whole thing in a sub-pattern. */ - - if (*ptr != 0 && ptr[1] == '{' && is_counted_repeat(ptr+2)) - { - ptr = read_repeat_counts(ptr+2, &min, &max, errorptr); - if (*errorptr != NULL) goto PCRE_ERROR_RETURN; - if ((min == 0 && (max == 1 || max == -1)) || - (min == 1 && max == -1)) - length++; - else length += 5; - if (ptr[1] == '+') - { - ptr++; - length += 2 + 2*LINK_SIZE; - } - else if (ptr[1] == '?') ptr++; - } - } - continue; - - /* Brackets may be genuine groups or special things */ - - case '(': - branch_newextra = 0; - bracket_length = 1 + LINK_SIZE; - - /* Handle special forms of bracket, which all start (? */ - - if (ptr[1] == '?') - { - int set, unset; - int *optset; - - switch (c = ptr[2]) - { - /* Skip over comments entirely */ - case '#': - ptr += 3; - while (*ptr != 0 && *ptr != ')') ptr++; - if (*ptr == 0) - { - *errorptr = ERR18; - goto PCRE_ERROR_RETURN; - } - continue; - - /* Non-referencing groups and lookaheads just move the pointer on, and - then behave like a non-special bracket, except that they don't increment - the count of extracting brackets. Ditto for the "once only" bracket, - which is in Perl from version 5.005. */ - - case ':': - case '=': - case '!': - case '>': - ptr += 2; - break; - - /* (?R) specifies a recursive call to the regex, which is an extension - to provide the facility which can be obtained by (?p{perl-code}) in - Perl 5.6. In Perl 5.8 this has become (??{perl-code}). - - From PCRE 4.00, items such as (?3) specify subroutine-like "calls" to - the appropriate numbered brackets. This includes both recursive and - non-recursive calls. (?R) is now synonymous with (?0). */ - - case 'R': - ptr++; - - case '0': case '1': case '2': case '3': case '4': - case '5': case '6': case '7': case '8': case '9': - ptr += 2; - if (c != 'R') - while ((digitab[*(++ptr)] & ctype_digit) != 0); - if (*ptr != ')') - { - *errorptr = ERR29; - goto PCRE_ERROR_RETURN; - } - length += 1 + LINK_SIZE; - - /* If this item is quantified, it will get wrapped inside brackets so - as to use the code for quantified brackets. We jump down and use the - code that handles this for real brackets. */ - - if (ptr[1] == '+' || ptr[1] == '*' || ptr[1] == '?' || ptr[1] == '{') - { - length += 2 + 2 * LINK_SIZE; /* to make bracketed */ - duplength = 5 + 3 * LINK_SIZE; - goto HANDLE_QUANTIFIED_BRACKETS; - } - continue; - - /* (?C) is an extension which provides "callout" - to provide a bit of - the functionality of the Perl (?{...}) feature. An optional number may - follow (default is zero). */ - - case 'C': - ptr += 2; - while ((digitab[*(++ptr)] & ctype_digit) != 0); - if (*ptr != ')') - { - *errorptr = ERR39; - goto PCRE_ERROR_RETURN; - } - length += 2 + 2*LINK_SIZE; - continue; - - /* Named subpatterns are an extension copied from Python */ - - case 'P': - ptr += 3; - if (*ptr == '<') - { - const uschar *p; /* Don't amalgamate; some compilers */ - p = ++ptr; /* grumble at autoincrement in declaration */ - while ((compile_block.ctypes[*ptr] & ctype_word) != 0) ptr++; - if (*ptr != '>') - { - *errorptr = ERR42; - goto PCRE_ERROR_RETURN; - } - name_count++; - if (ptr - p > max_name_size) max_name_size = (ptr - p); - break; - } - - if (*ptr == '=' || *ptr == '>') - { - while ((compile_block.ctypes[*(++ptr)] & ctype_word) != 0); - if (*ptr != ')') - { - *errorptr = ERR42; - goto PCRE_ERROR_RETURN; - } - break; - } - - /* Unknown character after (?P */ - - *errorptr = ERR41; - goto PCRE_ERROR_RETURN; - - /* Lookbehinds are in Perl from version 5.005 */ - - case '<': - ptr += 3; - if (*ptr == '=' || *ptr == '!') - { - branch_newextra = 1 + LINK_SIZE; - length += 1 + LINK_SIZE; /* For the first branch */ - break; - } - *errorptr = ERR24; - goto PCRE_ERROR_RETURN; - - /* Conditionals are in Perl from version 5.005. The bracket must either - be followed by a number (for bracket reference) or by an assertion - group, or (a PCRE extension) by 'R' for a recursion test. */ - - case '(': - if (ptr[3] == 'R' && ptr[4] == ')') - { - ptr += 4; - length += 3; - } - else if ((digitab[ptr[3]] & ctype_digit) != 0) - { - ptr += 4; - length += 3; - while ((digitab[*ptr] & ctype_digit) != 0) ptr++; - if (*ptr != ')') - { - *errorptr = ERR26; - goto PCRE_ERROR_RETURN; - } - } - else /* An assertion must follow */ - { - ptr++; /* Can treat like ':' as far as spacing is concerned */ - if (ptr[2] != '?' || - (ptr[3] != '=' && ptr[3] != '!' && ptr[3] != '<') ) - { - ptr += 2; /* To get right offset in message */ - *errorptr = ERR28; - goto PCRE_ERROR_RETURN; - } - } - break; - - /* Else loop checking valid options until ) is met. Anything else is an - error. If we are without any brackets, i.e. at top level, the settings - act as if specified in the options, so massage the options immediately. - This is for backward compatibility with Perl 5.004. */ - - default: - set = unset = 0; - optset = &set; - ptr += 2; - - for (;; ptr++) - { - c = *ptr; - switch (c) - { - case 'i': - *optset |= PCRE_CASELESS; - continue; - - case 'm': - *optset |= PCRE_MULTILINE; - continue; - - case 's': - *optset |= PCRE_DOTALL; - continue; - - case 'x': - *optset |= PCRE_EXTENDED; - continue; - - case 'X': - *optset |= PCRE_EXTRA; - continue; - - case 'U': - *optset |= PCRE_UNGREEDY; - continue; - - case '-': - optset = &unset; - continue; - - /* A termination by ')' indicates an options-setting-only item; if - this is at the very start of the pattern (indicated by item_count - being zero), we use it to set the global options. This is helpful - when analyzing the pattern for first characters, etc. Otherwise - nothing is done here and it is handled during the compiling - process. - - [Historical note: Up to Perl 5.8, options settings at top level - were always global settings, wherever they appeared in the pattern. - That is, they were equivalent to an external setting. From 5.8 - onwards, they apply only to what follows (which is what you might - expect).] */ - - case ')': - if (item_count == 0) - { - options = (options | set) & (~unset); - set = unset = 0; /* To save length */ - item_count--; /* To allow for several */ - } - - /* Fall through */ - - /* A termination by ':' indicates the start of a nested group with - the given options set. This is again handled at compile time, but - we must allow for compiled space if any of the ims options are - set. We also have to allow for resetting space at the end of - the group, which is why 4 is added to the length and not just 2. - If there are several changes of options within the same group, this - will lead to an over-estimate on the length, but this shouldn't - matter very much. We also have to allow for resetting options at - the start of any alternations, which we do by setting - branch_newextra to 2. Finally, we record whether the case-dependent - flag ever changes within the regex. This is used by the "required - character" code. */ - - case ':': - if (((set|unset) & PCRE_IMS) != 0) - { - length += 4; - branch_newextra = 2; - if (((set|unset) & PCRE_CASELESS) != 0) options |= PCRE_ICHANGED; - } - goto END_OPTIONS; - - /* Unrecognized option character */ - - default: - *errorptr = ERR12; - goto PCRE_ERROR_RETURN; - } - } - - /* If we hit a closing bracket, that's it - this is a freestanding - option-setting. We need to ensure that branch_extra is updated if - necessary. The only values branch_newextra can have here are 0 or 2. - If the value is 2, then branch_extra must either be 2 or 5, depending - on whether this is a lookbehind group or not. */ - - END_OPTIONS: - if (c == ')') - { - if (branch_newextra == 2 && - (branch_extra == 0 || branch_extra == 1+LINK_SIZE)) - branch_extra += branch_newextra; - continue; - } - - /* If options were terminated by ':' control comes here. Fall through - to handle the group below. */ - } - } - - /* Extracting brackets must be counted so we can process escapes in a - Perlish way. If the number exceeds EXTRACT_BASIC_MAX we are going to - need an additional 3 bytes of store per extracting bracket. However, if - PCRE_NO_AUTO)CAPTURE is set, unadorned brackets become non-capturing, so we - must leave the count alone (it will aways be zero). */ - - else if ((options & PCRE_NO_AUTO_CAPTURE) == 0) - { - bracount++; - if (bracount > EXTRACT_BASIC_MAX) bracket_length += 3; - } - - /* Save length for computing whole length at end if there's a repeat that - requires duplication of the group. Also save the current value of - branch_extra, and start the new group with the new value. If non-zero, this - will either be 2 for a (?imsx: group, or 3 for a lookbehind assertion. */ - - if (brastackptr >= sizeof(brastack)/sizeof(int)) - { - *errorptr = ERR19; - goto PCRE_ERROR_RETURN; - } - - bralenstack[brastackptr] = branch_extra; - branch_extra = branch_newextra; - - brastack[brastackptr++] = length; - length += bracket_length; - continue; - - /* Handle ket. Look for subsequent max/min; for certain sets of values we - have to replicate this bracket up to that many times. If brastackptr is - 0 this is an unmatched bracket which will generate an error, but take care - not to try to access brastack[-1] when computing the length and restoring - the branch_extra value. */ - - case ')': - length += 1 + LINK_SIZE; - if (brastackptr > 0) - { - duplength = length - brastack[--brastackptr]; - branch_extra = bralenstack[brastackptr]; - } - else duplength = 0; - - /* The following code is also used when a recursion such as (?3) is - followed by a quantifier, because in that case, it has to be wrapped inside - brackets so that the quantifier works. The value of duplength must be - set before arrival. */ - - HANDLE_QUANTIFIED_BRACKETS: - - /* Leave ptr at the final char; for read_repeat_counts this happens - automatically; for the others we need an increment. */ - - if ((c = ptr[1]) == '{' && is_counted_repeat(ptr+2)) - { - ptr = read_repeat_counts(ptr+2, &min, &max, errorptr); - if (*errorptr != NULL) goto PCRE_ERROR_RETURN; - } - else if (c == '*') { min = 0; max = -1; ptr++; } - else if (c == '+') { min = 1; max = -1; ptr++; } - else if (c == '?') { min = 0; max = 1; ptr++; } - else { min = 1; max = 1; } - - /* If the minimum is zero, we have to allow for an OP_BRAZERO before the - group, and if the maximum is greater than zero, we have to replicate - maxval-1 times; each replication acquires an OP_BRAZERO plus a nesting - bracket set. */ - - if (min == 0) - { - length++; - if (max > 0) length += (max - 1) * (duplength + 3 + 2*LINK_SIZE); - } - - /* When the minimum is greater than zero, we have to replicate up to - minval-1 times, with no additions required in the copies. Then, if there - is a limited maximum we have to replicate up to maxval-1 times allowing - for a BRAZERO item before each optional copy and nesting brackets for all - but one of the optional copies. */ - - else - { - length += (min - 1) * duplength; - if (max > min) /* Need this test as max=-1 means no limit */ - length += (max - min) * (duplength + 3 + 2*LINK_SIZE) - - (2 + 2*LINK_SIZE); - } - - /* Allow space for once brackets for "possessive quantifier" */ - - if (ptr[1] == '+') - { - ptr++; - length += 2 + 2*LINK_SIZE; - } - continue; - - /* Non-special character. It won't be space or # in extended mode, so it is - always a genuine character. If we are in a \Q...\E sequence, check for the - end; if not, we have a literal. */ - - default: - NORMAL_CHAR: - - if (inescq && c == '\\' && ptr[1] == 'E') - { - inescq = FALSE; - ptr++; - continue; - } - - length += 2; /* For a one-byte character */ - lastitemlength = 1; /* Default length of last item for repeats */ - - /* In UTF-8 mode, check for additional bytes. */ - -#ifdef SUPPORT_UTF8 - if (utf8 && (c & 0xc0) == 0xc0) - { - while ((ptr[1] & 0xc0) == 0x80) /* Can't flow over the end */ - { /* because the end is marked */ - lastitemlength++; /* by a zero byte. */ - length++; - ptr++; - } - } -#endif - - continue; - } - } - -length += 2 + LINK_SIZE; /* For final KET and END */ - -if ((options & PCRE_AUTO_CALLOUT) != 0) - length += 2 + 2*LINK_SIZE; /* For final callout */ - -if (length > MAX_PATTERN_SIZE) - { - *errorptr = ERR20; - return NULL; - } - -/* Compute the size of data block needed and get it, either from malloc or -externally provided function. */ - -size = length + sizeof(real_pcre) + name_count * (max_name_size + 3); -re = (real_pcre *)(pcre_malloc)(size); - -if (re == NULL) - { - *errorptr = ERR21; - return NULL; - } - -/* Put in the magic number, and save the sizes, options, and character table -pointer. NULL is used for the default character tables. The nullpad field is at -the end; it's there to help in the case when a regex compiled on a system with -4-byte pointers is run on another with 8-byte pointers. */ - -re->magic_number = MAGIC_NUMBER; -re->size = size; -re->options = options; -re->dummy1 = re->dummy2 = 0; -re->name_table_offset = sizeof(real_pcre); -re->name_entry_size = max_name_size + 3; -re->name_count = name_count; -re->tables = (tables == pcre_default_tables)? NULL : tables; -re->nullpad = NULL; - -/* The starting points of the name/number translation table and of the code are -passed around in the compile data block. */ - -compile_block.names_found = 0; -compile_block.name_entry_size = max_name_size + 3; -compile_block.name_table = (uschar *)re + re->name_table_offset; -codestart = compile_block.name_table + re->name_entry_size * re->name_count; -compile_block.start_code = codestart; -compile_block.start_pattern = (const uschar *)pattern; -compile_block.req_varyopt = 0; -compile_block.nopartial = FALSE; - -/* Set up a starting, non-extracting bracket, then compile the expression. On -error, *errorptr will be set non-NULL, so we don't need to look at the result -of the function here. */ - -ptr = (const uschar *)pattern; -code = (uschar *)codestart; -*code = OP_BRA; -bracount = 0; -(void)compile_regex(options, options & PCRE_IMS, &bracount, &code, &ptr, - errorptr, FALSE, 0, &firstbyte, &reqbyte, NULL, &compile_block); -re->top_bracket = bracount; -re->top_backref = compile_block.top_backref; - -if (compile_block.nopartial) re->options |= PCRE_NOPARTIAL; - -/* If not reached end of pattern on success, there's an excess bracket. */ - -if (*errorptr == NULL && *ptr != 0) *errorptr = ERR22; - -/* Fill in the terminating state and check for disastrous overflow, but -if debugging, leave the test till after things are printed out. */ - -*code++ = OP_END; - -#ifndef DEBUG -if (code - codestart > length) *errorptr = ERR23; -#endif - -/* Give an error if there's back reference to a non-existent capturing -subpattern. */ - -if (re->top_backref > re->top_bracket) *errorptr = ERR15; - -/* Failed to compile, or error while post-processing */ - -if (*errorptr != NULL) - { - (pcre_free)(re); - PCRE_ERROR_RETURN: - *erroroffset = ptr - (const uschar *)pattern; - return NULL; - } - -/* If the anchored option was not passed, set the flag if we can determine that -the pattern is anchored by virtue of ^ characters or \A or anything else (such -as starting with .* when DOTALL is set). - -Otherwise, if we know what the first character has to be, save it, because that -speeds up unanchored matches no end. If not, see if we can set the -PCRE_STARTLINE flag. This is helpful for multiline matches when all branches -start with ^. and also when all branches start with .* for non-DOTALL matches. -*/ - -if ((options & PCRE_ANCHORED) == 0) - { - int temp_options = options; - if (is_anchored(codestart, &temp_options, 0, compile_block.backref_map)) - re->options |= PCRE_ANCHORED; - else - { - if (firstbyte < 0) - firstbyte = find_firstassertedchar(codestart, &temp_options, FALSE); - if (firstbyte >= 0) /* Remove caseless flag for non-caseable chars */ - { - int ch = firstbyte & 255; - re->first_byte = ((firstbyte & REQ_CASELESS) != 0 && - compile_block.fcc[ch] == ch)? ch : firstbyte; - re->options |= PCRE_FIRSTSET; - } - else if (is_startline(codestart, 0, compile_block.backref_map)) - re->options |= PCRE_STARTLINE; - } - } - -/* For an anchored pattern, we use the "required byte" only if it follows a -variable length item in the regex. Remove the caseless flag for non-caseable -bytes. */ - -if (reqbyte >= 0 && - ((re->options & PCRE_ANCHORED) == 0 || (reqbyte & REQ_VARY) != 0)) - { - int ch = reqbyte & 255; - re->req_byte = ((reqbyte & REQ_CASELESS) != 0 && - compile_block.fcc[ch] == ch)? (reqbyte & ~REQ_CASELESS) : reqbyte; - re->options |= PCRE_REQCHSET; - } - -/* Print out the compiled data for debugging */ - -#ifdef DEBUG - -printf("Length = %d top_bracket = %d top_backref = %d\n", - length, re->top_bracket, re->top_backref); - -if (re->options != 0) - { - printf("%s%s%s%s%s%s%s%s%s%s\n", - ((re->options & PCRE_NOPARTIAL) != 0)? "nopartial " : "", - ((re->options & PCRE_ANCHORED) != 0)? "anchored " : "", - ((re->options & PCRE_CASELESS) != 0)? "caseless " : "", - ((re->options & PCRE_ICHANGED) != 0)? "case state changed " : "", - ((re->options & PCRE_EXTENDED) != 0)? "extended " : "", - ((re->options & PCRE_MULTILINE) != 0)? "multiline " : "", - ((re->options & PCRE_DOTALL) != 0)? "dotall " : "", - ((re->options & PCRE_DOLLAR_ENDONLY) != 0)? "endonly " : "", - ((re->options & PCRE_EXTRA) != 0)? "extra " : "", - ((re->options & PCRE_UNGREEDY) != 0)? "ungreedy " : ""); - } - -if ((re->options & PCRE_FIRSTSET) != 0) - { - int ch = re->first_byte & 255; - const char *caseless = ((re->first_byte & REQ_CASELESS) == 0)? "" : " (caseless)"; - if (isprint(ch)) printf("First char = %c%s\n", ch, caseless); - else printf("First char = \\x%02x%s\n", ch, caseless); - } - -if ((re->options & PCRE_REQCHSET) != 0) - { - int ch = re->req_byte & 255; - const char *caseless = ((re->req_byte & REQ_CASELESS) == 0)? "" : " (caseless)"; - if (isprint(ch)) printf("Req char = %c%s\n", ch, caseless); - else printf("Req char = \\x%02x%s\n", ch, caseless); - } - -print_internals(re, stdout); - -/* This check is done here in the debugging case so that the code that -was compiled can be seen. */ - -if (code - codestart > length) - { - *errorptr = ERR23; - (pcre_free)(re); - *erroroffset = ptr - (uschar *)pattern; - return NULL; - } -#endif - -return (pcre *)re; -} - - - -/************************************************* -* Match a back-reference * -*************************************************/ - -/* If a back reference hasn't been set, the length that is passed is greater -than the number of characters left in the string, so the match fails. - -Arguments: - offset index into the offset vector - eptr points into the subject - length length to be matched - md points to match data block - ims the ims flags - -Returns: TRUE if matched -*/ - -static BOOL -match_ref(int offset, register const uschar *eptr, int length, match_data *md, - unsigned long int ims) -{ -const uschar *p = md->start_subject + md->offset_vector[offset]; - -#ifdef DEBUG -if (eptr >= md->end_subject) - printf("matching subject "); -else - { - printf("matching subject "); - pchars(eptr, length, TRUE, md); - } -printf(" against backref "); -pchars(p, length, FALSE, md); -printf("\n"); -#endif - -/* Always fail if not enough characters left */ - -if (length > md->end_subject - eptr) return FALSE; - -/* Separate the caselesss case for speed */ - -if ((ims & PCRE_CASELESS) != 0) - { - while (length-- > 0) - if (md->lcc[*p++] != md->lcc[*eptr++]) return FALSE; - } -else - { while (length-- > 0) if (*p++ != *eptr++) return FALSE; } - -return TRUE; -} - - -#ifdef SUPPORT_UTF8 -/************************************************* -* Match character against an XCLASS * -*************************************************/ - -/* This function is called from within the XCLASS code below, to match a -character against an extended class which might match values > 255. - -Arguments: - c the character - data points to the flag byte of the XCLASS data - -Returns: TRUE if character matches, else FALSE -*/ - -static BOOL -match_xclass(int c, const uschar *data) -{ -int t; -BOOL negated = (*data & XCL_NOT) != 0; - -/* Character values < 256 are matched against a bitmap, if one is present. If -not, we still carry on, because there may be ranges that start below 256 in the -additional data. */ - -if (c < 256) - { - if ((*data & XCL_MAP) != 0 && (data[1 + c/8] & (1 << (c&7))) != 0) - return !negated; /* char found */ - } - -/* First skip the bit map if present. Then match against the list of Unicode -properties or large chars or ranges that end with a large char. We won't ever -encounter XCL_PROP or XCL_NOTPROP when UCP support is not compiled. */ - -if ((*data++ & XCL_MAP) != 0) data += 32; - -while ((t = *data++) != XCL_END) - { - int x, y; - if (t == XCL_SINGLE) - { - GETCHARINC(x, data); - if (c == x) return !negated; - } - else if (t == XCL_RANGE) - { - GETCHARINC(x, data); - GETCHARINC(y, data); - if (c >= x && c <= y) return !negated; - } - -#ifdef SUPPORT_UCP - else /* XCL_PROP & XCL_NOTPROP */ - { - int chartype, othercase; - int rqdtype = *data++; - int category = ucp_findchar(c, &chartype, &othercase); - if (rqdtype >= 128) - { - if ((rqdtype - 128 == category) == (t == XCL_PROP)) return !negated; - } - else - { - if ((rqdtype == chartype) == (t == XCL_PROP)) return !negated; - } - } -#endif /* SUPPORT_UCP */ - } - -return negated; /* char did not match */ -} -#endif - - -/*************************************************************************** -**************************************************************************** - RECURSION IN THE match() FUNCTION - -The match() function is highly recursive. Some regular expressions can cause -it to recurse thousands of times. I was writing for Unix, so I just let it -call itself recursively. This uses the stack for saving everything that has -to be saved for a recursive call. On Unix, the stack can be large, and this -works fine. - -It turns out that on non-Unix systems there are problems with programs that -use a lot of stack. (This despite the fact that every last chip has oodles -of memory these days, and techniques for extending the stack have been known -for decades.) So.... - -There is a fudge, triggered by defining NO_RECURSE, which avoids recursive -calls by keeping local variables that need to be preserved in blocks of memory -obtained from malloc instead instead of on the stack. Macros are used to -achieve this so that the actual code doesn't look very different to what it -always used to. -**************************************************************************** -***************************************************************************/ - - -/* These versions of the macros use the stack, as normal */ - -#ifndef NO_RECURSE -#define REGISTER register -#define RMATCH(rx,ra,rb,rc,rd,re,rf,rg) rx = match(ra,rb,rc,rd,re,rf,rg) -#define RRETURN(ra) return ra -#else - - -/* These versions of the macros manage a private stack on the heap. Note -that the rd argument of RMATCH isn't actually used. It's the md argument of -match(), which never changes. */ - -#define REGISTER - -#define RMATCH(rx,ra,rb,rc,rd,re,rf,rg)\ - {\ - heapframe *newframe = (pcre_stack_malloc)(sizeof(heapframe));\ - if (setjmp(frame->Xwhere) == 0)\ - {\ - newframe->Xeptr = ra;\ - newframe->Xecode = rb;\ - newframe->Xoffset_top = rc;\ - newframe->Xims = re;\ - newframe->Xeptrb = rf;\ - newframe->Xflags = rg;\ - newframe->Xprevframe = frame;\ - frame = newframe;\ - DPRINTF(("restarting from line %d\n", __LINE__));\ - goto HEAP_RECURSE;\ - }\ - else\ - {\ - DPRINTF(("longjumped back to line %d\n", __LINE__));\ - frame = md->thisframe;\ - rx = frame->Xresult;\ - }\ - } - -#define RRETURN(ra)\ - {\ - heapframe *newframe = frame;\ - frame = newframe->Xprevframe;\ - (pcre_stack_free)(newframe);\ - if (frame != NULL)\ - {\ - frame->Xresult = ra;\ - md->thisframe = frame;\ - longjmp(frame->Xwhere, 1);\ - }\ - return ra;\ - } - - -/* Structure for remembering the local variables in a private frame */ - -typedef struct heapframe { - struct heapframe *Xprevframe; - - /* Function arguments that may change */ - - const uschar *Xeptr; - const uschar *Xecode; - int Xoffset_top; - long int Xims; - eptrblock *Xeptrb; - int Xflags; - - /* Function local variables */ - - const uschar *Xcallpat; - const uschar *Xcharptr; - const uschar *Xdata; - const uschar *Xnext; - const uschar *Xpp; - const uschar *Xprev; - const uschar *Xsaved_eptr; - - recursion_info Xnew_recursive; - - BOOL Xcur_is_word; - BOOL Xcondition; - BOOL Xminimize; - BOOL Xprev_is_word; - - unsigned long int Xoriginal_ims; - -#ifdef SUPPORT_UCP - int Xprop_type; - int Xprop_fail_result; - int Xprop_category; - int Xprop_chartype; - int Xprop_othercase; - int Xprop_test_against; - int *Xprop_test_variable; -#endif - - int Xctype; - int Xfc; - int Xfi; - int Xlength; - int Xmax; - int Xmin; - int Xnumber; - int Xoffset; - int Xop; - int Xsave_capture_last; - int Xsave_offset1, Xsave_offset2, Xsave_offset3; - int Xstacksave[REC_STACK_SAVE_MAX]; - - eptrblock Xnewptrb; - - /* Place to pass back result, and where to jump back to */ - - int Xresult; - jmp_buf Xwhere; - -} heapframe; - -#endif - - -/*************************************************************************** -***************************************************************************/ - - - -/************************************************* -* Match from current position * -*************************************************/ - -/* On entry ecode points to the first opcode, and eptr to the first character -in the subject string, while eptrb holds the value of eptr at the start of the -last bracketed group - used for breaking infinite loops matching zero-length -strings. This function is called recursively in many circumstances. Whenever it -returns a negative (error) response, the outer incarnation must also return the -same response. - -Performance note: It might be tempting to extract commonly used fields from the -md structure (e.g. utf8, end_subject) into individual variables to improve -performance. Tests using gcc on a SPARC disproved this; in the first case, it -made performance worse. - -Arguments: - eptr pointer in subject - ecode position in code - offset_top current top pointer - md pointer to "static" info for the match - ims current /i, /m, and /s options - eptrb pointer to chain of blocks containing eptr at start of - brackets - for testing for empty matches - flags can contain - match_condassert - this is an assertion condition - match_isgroup - this is the start of a bracketed group - -Returns: MATCH_MATCH if matched ) these values are >= 0 - MATCH_NOMATCH if failed to match ) - a negative PCRE_ERROR_xxx value if aborted by an error condition - (e.g. stopped by recursion limit) -*/ - -static int -match(REGISTER const uschar *eptr, REGISTER const uschar *ecode, - int offset_top, match_data *md, unsigned long int ims, eptrblock *eptrb, - int flags) -{ -/* These variables do not need to be preserved over recursion in this function, -so they can be ordinary variables in all cases. Mark them with "register" -because they are used a lot in loops. */ - -register int rrc; /* Returns from recursive calls */ -register int i; /* Used for loops not involving calls to RMATCH() */ -register int c; /* Character values not kept over RMATCH() calls */ - -/* When recursion is not being used, all "local" variables that have to be -preserved over calls to RMATCH() are part of a "frame" which is obtained from -heap storage. Set up the top-level frame here; others are obtained from the -heap whenever RMATCH() does a "recursion". See the macro definitions above. */ - -#ifdef NO_RECURSE -heapframe *frame = (pcre_stack_malloc)(sizeof(heapframe)); -frame->Xprevframe = NULL; /* Marks the top level */ - -/* Copy in the original argument variables */ - -frame->Xeptr = eptr; -frame->Xecode = ecode; -frame->Xoffset_top = offset_top; -frame->Xims = ims; -frame->Xeptrb = eptrb; -frame->Xflags = flags; - -/* This is where control jumps back to to effect "recursion" */ - -HEAP_RECURSE: - -/* Macros make the argument variables come from the current frame */ - -#define eptr frame->Xeptr -#define ecode frame->Xecode -#define offset_top frame->Xoffset_top -#define ims frame->Xims -#define eptrb frame->Xeptrb -#define flags frame->Xflags - -/* Ditto for the local variables */ - -#ifdef SUPPORT_UTF8 -#define charptr frame->Xcharptr -#endif -#define callpat frame->Xcallpat -#define data frame->Xdata -#define next frame->Xnext -#define pp frame->Xpp -#define prev frame->Xprev -#define saved_eptr frame->Xsaved_eptr - -#define new_recursive frame->Xnew_recursive - -#define cur_is_word frame->Xcur_is_word -#define condition frame->Xcondition -#define minimize frame->Xminimize -#define prev_is_word frame->Xprev_is_word - -#define original_ims frame->Xoriginal_ims - -#ifdef SUPPORT_UCP -#define prop_type frame->Xprop_type -#define prop_fail_result frame->Xprop_fail_result -#define prop_category frame->Xprop_category -#define prop_chartype frame->Xprop_chartype -#define prop_othercase frame->Xprop_othercase -#define prop_test_against frame->Xprop_test_against -#define prop_test_variable frame->Xprop_test_variable -#endif - -#define ctype frame->Xctype -#define fc frame->Xfc -#define fi frame->Xfi -#define length frame->Xlength -#define max frame->Xmax -#define min frame->Xmin -#define number frame->Xnumber -#define offset frame->Xoffset -#define op frame->Xop -#define save_capture_last frame->Xsave_capture_last -#define save_offset1 frame->Xsave_offset1 -#define save_offset2 frame->Xsave_offset2 -#define save_offset3 frame->Xsave_offset3 -#define stacksave frame->Xstacksave - -#define newptrb frame->Xnewptrb - -/* When recursion is being used, local variables are allocated on the stack and -get preserved during recursion in the normal way. In this environment, fi and -i, and fc and c, can be the same variables. */ - -#else -#define fi i -#define fc c - - -#ifdef SUPPORT_UTF8 /* Many of these variables are used ony */ -const uschar *charptr; /* small blocks of the code. My normal */ -#endif /* style of coding would have declared */ -const uschar *callpat; /* them within each of those blocks. */ -const uschar *data; /* However, in order to accommodate the */ -const uschar *next; /* version of this code that uses an */ -const uschar *pp; /* external "stack" implemented on the */ -const uschar *prev; /* heap, it is easier to declare them */ -const uschar *saved_eptr; /* all here, so the declarations can */ - /* be cut out in a block. The only */ -recursion_info new_recursive; /* declarations within blocks below are */ - /* for variables that do not have to */ -BOOL cur_is_word; /* be preserved over a recursive call */ -BOOL condition; /* to RMATCH(). */ -BOOL minimize; -BOOL prev_is_word; - -unsigned long int original_ims; - -#ifdef SUPPORT_UCP -int prop_type; -int prop_fail_result; -int prop_category; -int prop_chartype; -int prop_othercase; -int prop_test_against; -int *prop_test_variable; -#endif - -int ctype; -int length; -int max; -int min; -int number; -int offset; -int op; -int save_capture_last; -int save_offset1, save_offset2, save_offset3; -int stacksave[REC_STACK_SAVE_MAX]; - -eptrblock newptrb; -#endif - -/* These statements are here to stop the compiler complaining about unitialized -variables. */ - -#ifdef SUPPORT_UCP -prop_fail_result = 0; -prop_test_against = 0; -prop_test_variable = NULL; -#endif - -/* OK, now we can get on with the real code of the function. Recursion is -specified by the macros RMATCH and RRETURN. When NO_RECURSE is *not* defined, -these just turn into a recursive call to match() and a "return", respectively. -However, RMATCH isn't like a function call because it's quite a complicated -macro. It has to be used in one particular way. This shouldn't, however, impact -performance when true recursion is being used. */ - -if (md->match_call_count++ >= md->match_limit) RRETURN(PCRE_ERROR_MATCHLIMIT); - -original_ims = ims; /* Save for resetting on ')' */ - -/* At the start of a bracketed group, add the current subject pointer to the -stack of such pointers, to be re-instated at the end of the group when we hit -the closing ket. When match() is called in other circumstances, we don't add to -this stack. */ - -if ((flags & match_isgroup) != 0) - { - newptrb.epb_prev = eptrb; - newptrb.epb_saved_eptr = eptr; - eptrb = &newptrb; - } - -/* Now start processing the operations. */ - -for (;;) - { - op = *ecode; - minimize = FALSE; - - /* For partial matching, remember if we ever hit the end of the subject after - matching at least one subject character. */ - - if (md->partial && - eptr >= md->end_subject && - eptr > md->start_match) - md->hitend = TRUE; - - /* Opening capturing bracket. If there is space in the offset vector, save - the current subject position in the working slot at the top of the vector. We - mustn't change the current values of the data slot, because they may be set - from a previous iteration of this group, and be referred to by a reference - inside the group. - - If the bracket fails to match, we need to restore this value and also the - values of the final offsets, in case they were set by a previous iteration of - the same bracket. - - If there isn't enough space in the offset vector, treat this as if it were a - non-capturing bracket. Don't worry about setting the flag for the error case - here; that is handled in the code for KET. */ - - if (op > OP_BRA) - { - number = op - OP_BRA; - - /* For extended extraction brackets (large number), we have to fish out the - number from a dummy opcode at the start. */ - - if (number > EXTRACT_BASIC_MAX) - number = GET2(ecode, 2+LINK_SIZE); - offset = number << 1; - -#ifdef DEBUG - printf("start bracket %d subject=", number); - pchars(eptr, 16, TRUE, md); - printf("\n"); -#endif - - if (offset < md->offset_max) - { - save_offset1 = md->offset_vector[offset]; - save_offset2 = md->offset_vector[offset+1]; - save_offset3 = md->offset_vector[md->offset_end - number]; - save_capture_last = md->capture_last; - - DPRINTF(("saving %d %d %d\n", save_offset1, save_offset2, save_offset3)); - md->offset_vector[md->offset_end - number] = eptr - md->start_subject; - - do - { - RMATCH(rrc, eptr, ecode + 1 + LINK_SIZE, offset_top, md, ims, eptrb, - match_isgroup); - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - md->capture_last = save_capture_last; - ecode += GET(ecode, 1); - } - while (*ecode == OP_ALT); - - DPRINTF(("bracket %d failed\n", number)); - - md->offset_vector[offset] = save_offset1; - md->offset_vector[offset+1] = save_offset2; - md->offset_vector[md->offset_end - number] = save_offset3; - - RRETURN(MATCH_NOMATCH); - } - - /* Insufficient room for saving captured contents */ - - else op = OP_BRA; - } - - /* Other types of node can be handled by a switch */ - - switch(op) - { - case OP_BRA: /* Non-capturing bracket: optimized */ - DPRINTF(("start bracket 0\n")); - do - { - RMATCH(rrc, eptr, ecode + 1 + LINK_SIZE, offset_top, md, ims, eptrb, - match_isgroup); - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - ecode += GET(ecode, 1); - } - while (*ecode == OP_ALT); - DPRINTF(("bracket 0 failed\n")); - RRETURN(MATCH_NOMATCH); - - /* Conditional group: compilation checked that there are no more than - two branches. If the condition is false, skipping the first branch takes us - past the end if there is only one branch, but that's OK because that is - exactly what going to the ket would do. */ - - case OP_COND: - if (ecode[LINK_SIZE+1] == OP_CREF) /* Condition extract or recurse test */ - { - offset = GET2(ecode, LINK_SIZE+2) << 1; /* Doubled ref number */ - condition = (offset == CREF_RECURSE * 2)? - (md->recursive != NULL) : - (offset < offset_top && md->offset_vector[offset] >= 0); - RMATCH(rrc, eptr, ecode + (condition? - (LINK_SIZE + 4) : (LINK_SIZE + 1 + GET(ecode, 1))), - offset_top, md, ims, eptrb, match_isgroup); - RRETURN(rrc); - } - - /* The condition is an assertion. Call match() to evaluate it - setting - the final argument TRUE causes it to stop at the end of an assertion. */ - - else - { - RMATCH(rrc, eptr, ecode + 1 + LINK_SIZE, offset_top, md, ims, NULL, - match_condassert | match_isgroup); - if (rrc == MATCH_MATCH) - { - ecode += 1 + LINK_SIZE + GET(ecode, LINK_SIZE+2); - while (*ecode == OP_ALT) ecode += GET(ecode, 1); - } - else if (rrc != MATCH_NOMATCH) - { - RRETURN(rrc); /* Need braces because of following else */ - } - else ecode += GET(ecode, 1); - RMATCH(rrc, eptr, ecode + 1 + LINK_SIZE, offset_top, md, ims, eptrb, - match_isgroup); - RRETURN(rrc); - } - /* Control never reaches here */ - - /* Skip over conditional reference or large extraction number data if - encountered. */ - - case OP_CREF: - case OP_BRANUMBER: - ecode += 3; - break; - - /* End of the pattern. If we are in a recursion, we should restore the - offsets appropriately and continue from after the call. */ - - case OP_END: - if (md->recursive != NULL && md->recursive->group_num == 0) - { - recursion_info *rec = md->recursive; - DPRINTF(("Hit the end in a (?0) recursion\n")); - md->recursive = rec->prevrec; - memmove(md->offset_vector, rec->offset_save, - rec->saved_max * sizeof(int)); - md->start_match = rec->save_start; - ims = original_ims; - ecode = rec->after_call; - break; - } - - /* Otherwise, if PCRE_NOTEMPTY is set, fail if we have matched an empty - string - backtracking will then try other alternatives, if any. */ - - if (md->notempty && eptr == md->start_match) RRETURN(MATCH_NOMATCH); - md->end_match_ptr = eptr; /* Record where we ended */ - md->end_offset_top = offset_top; /* and how many extracts were taken */ - RRETURN(MATCH_MATCH); - - /* Change option settings */ - - case OP_OPT: - ims = ecode[1]; - ecode += 2; - DPRINTF(("ims set to %02lx\n", ims)); - break; - - /* Assertion brackets. Check the alternative branches in turn - the - matching won't pass the KET for an assertion. If any one branch matches, - the assertion is true. Lookbehind assertions have an OP_REVERSE item at the - start of each branch to move the current point backwards, so the code at - this level is identical to the lookahead case. */ - - case OP_ASSERT: - case OP_ASSERTBACK: - do - { - RMATCH(rrc, eptr, ecode + 1 + LINK_SIZE, offset_top, md, ims, NULL, - match_isgroup); - if (rrc == MATCH_MATCH) break; - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - ecode += GET(ecode, 1); - } - while (*ecode == OP_ALT); - if (*ecode == OP_KET) RRETURN(MATCH_NOMATCH); - - /* If checking an assertion for a condition, return MATCH_MATCH. */ - - if ((flags & match_condassert) != 0) RRETURN(MATCH_MATCH); - - /* Continue from after the assertion, updating the offsets high water - mark, since extracts may have been taken during the assertion. */ - - do ecode += GET(ecode,1); while (*ecode == OP_ALT); - ecode += 1 + LINK_SIZE; - offset_top = md->end_offset_top; - continue; - - /* Negative assertion: all branches must fail to match */ - - case OP_ASSERT_NOT: - case OP_ASSERTBACK_NOT: - do - { - RMATCH(rrc, eptr, ecode + 1 + LINK_SIZE, offset_top, md, ims, NULL, - match_isgroup); - if (rrc == MATCH_MATCH) RRETURN(MATCH_NOMATCH); - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - ecode += GET(ecode,1); - } - while (*ecode == OP_ALT); - - if ((flags & match_condassert) != 0) RRETURN(MATCH_MATCH); - - ecode += 1 + LINK_SIZE; - continue; - - /* Move the subject pointer back. This occurs only at the start of - each branch of a lookbehind assertion. If we are too close to the start to - move back, this match function fails. When working with UTF-8 we move - back a number of characters, not bytes. */ - - case OP_REVERSE: -#ifdef SUPPORT_UTF8 - if (md->utf8) - { - c = GET(ecode,1); - for (i = 0; i < c; i++) - { - eptr--; - if (eptr < md->start_subject) RRETURN(MATCH_NOMATCH); - BACKCHAR(eptr) - } - } - else -#endif - - /* No UTF-8 support, or not in UTF-8 mode: count is byte count */ - - { - eptr -= GET(ecode,1); - if (eptr < md->start_subject) RRETURN(MATCH_NOMATCH); - } - - /* Skip to next op code */ - - ecode += 1 + LINK_SIZE; - break; - - /* The callout item calls an external function, if one is provided, passing - details of the match so far. This is mainly for debugging, though the - function is able to force a failure. */ - - case OP_CALLOUT: - if (pcre_callout != NULL) - { - pcre_callout_block cb; - cb.version = 1; /* Version 1 of the callout block */ - cb.callout_number = ecode[1]; - cb.offset_vector = md->offset_vector; - cb.subject = (const char *)md->start_subject; - cb.subject_length = md->end_subject - md->start_subject; - cb.start_match = md->start_match - md->start_subject; - cb.current_position = eptr - md->start_subject; - cb.pattern_position = GET(ecode, 2); - cb.next_item_length = GET(ecode, 2 + LINK_SIZE); - cb.capture_top = offset_top/2; - cb.capture_last = md->capture_last; - cb.callout_data = md->callout_data; - if ((rrc = (*pcre_callout)(&cb)) > 0) RRETURN(MATCH_NOMATCH); - if (rrc < 0) RRETURN(rrc); - } - ecode += 2 + 2*LINK_SIZE; - break; - - /* Recursion either matches the current regex, or some subexpression. The - offset data is the offset to the starting bracket from the start of the - whole pattern. (This is so that it works from duplicated subpatterns.) - - If there are any capturing brackets started but not finished, we have to - save their starting points and reinstate them after the recursion. However, - we don't know how many such there are (offset_top records the completed - total) so we just have to save all the potential data. There may be up to - 65535 such values, which is too large to put on the stack, but using malloc - for small numbers seems expensive. As a compromise, the stack is used when - there are no more than REC_STACK_SAVE_MAX values to store; otherwise malloc - is used. A problem is what to do if the malloc fails ... there is no way of - returning to the top level with an error. Save the top REC_STACK_SAVE_MAX - values on the stack, and accept that the rest may be wrong. - - There are also other values that have to be saved. We use a chained - sequence of blocks that actually live on the stack. Thanks to Robin Houston - for the original version of this logic. */ - - case OP_RECURSE: - { - callpat = md->start_code + GET(ecode, 1); - new_recursive.group_num = *callpat - OP_BRA; - - /* For extended extraction brackets (large number), we have to fish out - the number from a dummy opcode at the start. */ - - if (new_recursive.group_num > EXTRACT_BASIC_MAX) - new_recursive.group_num = GET2(callpat, 2+LINK_SIZE); - - /* Add to "recursing stack" */ - - new_recursive.prevrec = md->recursive; - md->recursive = &new_recursive; - - /* Find where to continue from afterwards */ - - ecode += 1 + LINK_SIZE; - new_recursive.after_call = ecode; - - /* Now save the offset data. */ - - new_recursive.saved_max = md->offset_end; - if (new_recursive.saved_max <= REC_STACK_SAVE_MAX) - new_recursive.offset_save = stacksave; - else - { - new_recursive.offset_save = - (int *)(pcre_malloc)(new_recursive.saved_max * sizeof(int)); - if (new_recursive.offset_save == NULL) RRETURN(PCRE_ERROR_NOMEMORY); - } - - memcpy(new_recursive.offset_save, md->offset_vector, - new_recursive.saved_max * sizeof(int)); - new_recursive.save_start = md->start_match; - md->start_match = eptr; - - /* OK, now we can do the recursion. For each top-level alternative we - restore the offset and recursion data. */ - - DPRINTF(("Recursing into group %d\n", new_recursive.group_num)); - do - { - RMATCH(rrc, eptr, callpat + 1 + LINK_SIZE, offset_top, md, ims, - eptrb, match_isgroup); - if (rrc == MATCH_MATCH) - { - md->recursive = new_recursive.prevrec; - if (new_recursive.offset_save != stacksave) - (pcre_free)(new_recursive.offset_save); - RRETURN(MATCH_MATCH); - } - else if (rrc != MATCH_NOMATCH) RRETURN(rrc); - - md->recursive = &new_recursive; - memcpy(md->offset_vector, new_recursive.offset_save, - new_recursive.saved_max * sizeof(int)); - callpat += GET(callpat, 1); - } - while (*callpat == OP_ALT); - - DPRINTF(("Recursion didn't match\n")); - md->recursive = new_recursive.prevrec; - if (new_recursive.offset_save != stacksave) - (pcre_free)(new_recursive.offset_save); - RRETURN(MATCH_NOMATCH); - } - /* Control never reaches here */ - - /* "Once" brackets are like assertion brackets except that after a match, - the point in the subject string is not moved back. Thus there can never be - a move back into the brackets. Friedl calls these "atomic" subpatterns. - Check the alternative branches in turn - the matching won't pass the KET - for this kind of subpattern. If any one branch matches, we carry on as at - the end of a normal bracket, leaving the subject pointer. */ - - case OP_ONCE: - { - prev = ecode; - saved_eptr = eptr; - - do - { - RMATCH(rrc, eptr, ecode + 1 + LINK_SIZE, offset_top, md, ims, - eptrb, match_isgroup); - if (rrc == MATCH_MATCH) break; - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - ecode += GET(ecode,1); - } - while (*ecode == OP_ALT); - - /* If hit the end of the group (which could be repeated), fail */ - - if (*ecode != OP_ONCE && *ecode != OP_ALT) RRETURN(MATCH_NOMATCH); - - /* Continue as from after the assertion, updating the offsets high water - mark, since extracts may have been taken. */ - - do ecode += GET(ecode,1); while (*ecode == OP_ALT); - - offset_top = md->end_offset_top; - eptr = md->end_match_ptr; - - /* For a non-repeating ket, just continue at this level. This also - happens for a repeating ket if no characters were matched in the group. - This is the forcible breaking of infinite loops as implemented in Perl - 5.005. If there is an options reset, it will get obeyed in the normal - course of events. */ - - if (*ecode == OP_KET || eptr == saved_eptr) - { - ecode += 1+LINK_SIZE; - break; - } - - /* The repeating kets try the rest of the pattern or restart from the - preceding bracket, in the appropriate order. We need to reset any options - that changed within the bracket before re-running it, so check the next - opcode. */ - - if (ecode[1+LINK_SIZE] == OP_OPT) - { - ims = (ims & ~PCRE_IMS) | ecode[4]; - DPRINTF(("ims set to %02lx at group repeat\n", ims)); - } - - if (*ecode == OP_KETRMIN) - { - RMATCH(rrc, eptr, ecode + 1 + LINK_SIZE, offset_top, md, ims, eptrb, 0); - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - RMATCH(rrc, eptr, prev, offset_top, md, ims, eptrb, match_isgroup); - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - } - else /* OP_KETRMAX */ - { - RMATCH(rrc, eptr, prev, offset_top, md, ims, eptrb, match_isgroup); - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - RMATCH(rrc, eptr, ecode + 1+LINK_SIZE, offset_top, md, ims, eptrb, 0); - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - } - } - RRETURN(MATCH_NOMATCH); - - /* An alternation is the end of a branch; scan along to find the end of the - bracketed group and go to there. */ - - case OP_ALT: - do ecode += GET(ecode,1); while (*ecode == OP_ALT); - break; - - /* BRAZERO and BRAMINZERO occur just before a bracket group, indicating - that it may occur zero times. It may repeat infinitely, or not at all - - i.e. it could be ()* or ()? in the pattern. Brackets with fixed upper - repeat limits are compiled as a number of copies, with the optional ones - preceded by BRAZERO or BRAMINZERO. */ - - case OP_BRAZERO: - { - next = ecode+1; - RMATCH(rrc, eptr, next, offset_top, md, ims, eptrb, match_isgroup); - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - do next += GET(next,1); while (*next == OP_ALT); - ecode = next + 1+LINK_SIZE; - } - break; - - case OP_BRAMINZERO: - { - next = ecode+1; - do next += GET(next,1); while (*next == OP_ALT); - RMATCH(rrc, eptr, next + 1+LINK_SIZE, offset_top, md, ims, eptrb, - match_isgroup); - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - ecode++; - } - break; - - /* End of a group, repeated or non-repeating. If we are at the end of - an assertion "group", stop matching and return MATCH_MATCH, but record the - current high water mark for use by positive assertions. Do this also - for the "once" (not-backup up) groups. */ - - case OP_KET: - case OP_KETRMIN: - case OP_KETRMAX: - { - prev = ecode - GET(ecode, 1); - saved_eptr = eptrb->epb_saved_eptr; - - /* Back up the stack of bracket start pointers. */ - - eptrb = eptrb->epb_prev; - - if (*prev == OP_ASSERT || *prev == OP_ASSERT_NOT || - *prev == OP_ASSERTBACK || *prev == OP_ASSERTBACK_NOT || - *prev == OP_ONCE) - { - md->end_match_ptr = eptr; /* For ONCE */ - md->end_offset_top = offset_top; - RRETURN(MATCH_MATCH); - } - - /* In all other cases except a conditional group we have to check the - group number back at the start and if necessary complete handling an - extraction by setting the offsets and bumping the high water mark. */ - - if (*prev != OP_COND) - { - number = *prev - OP_BRA; - - /* For extended extraction brackets (large number), we have to fish out - the number from a dummy opcode at the start. */ - - if (number > EXTRACT_BASIC_MAX) number = GET2(prev, 2+LINK_SIZE); - offset = number << 1; - -#ifdef DEBUG - printf("end bracket %d", number); - printf("\n"); -#endif - - /* Test for a numbered group. This includes groups called as a result - of recursion. Note that whole-pattern recursion is coded as a recurse - into group 0, so it won't be picked up here. Instead, we catch it when - the OP_END is reached. */ - - if (number > 0) - { - md->capture_last = number; - if (offset >= md->offset_max) md->offset_overflow = TRUE; else - { - md->offset_vector[offset] = - md->offset_vector[md->offset_end - number]; - md->offset_vector[offset+1] = eptr - md->start_subject; - if (offset_top <= offset) offset_top = offset + 2; - } - - /* Handle a recursively called group. Restore the offsets - appropriately and continue from after the call. */ - - if (md->recursive != NULL && md->recursive->group_num == number) - { - recursion_info *rec = md->recursive; - DPRINTF(("Recursion (%d) succeeded - continuing\n", number)); - md->recursive = rec->prevrec; - md->start_match = rec->save_start; - memcpy(md->offset_vector, rec->offset_save, - rec->saved_max * sizeof(int)); - ecode = rec->after_call; - ims = original_ims; - break; - } - } - } - - /* Reset the value of the ims flags, in case they got changed during - the group. */ - - ims = original_ims; - DPRINTF(("ims reset to %02lx\n", ims)); - - /* For a non-repeating ket, just continue at this level. This also - happens for a repeating ket if no characters were matched in the group. - This is the forcible breaking of infinite loops as implemented in Perl - 5.005. If there is an options reset, it will get obeyed in the normal - course of events. */ - - if (*ecode == OP_KET || eptr == saved_eptr) - { - ecode += 1 + LINK_SIZE; - break; - } - - /* The repeating kets try the rest of the pattern or restart from the - preceding bracket, in the appropriate order. */ - - if (*ecode == OP_KETRMIN) - { - RMATCH(rrc, eptr, ecode + 1+LINK_SIZE, offset_top, md, ims, eptrb, 0); - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - RMATCH(rrc, eptr, prev, offset_top, md, ims, eptrb, match_isgroup); - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - } - else /* OP_KETRMAX */ - { - RMATCH(rrc, eptr, prev, offset_top, md, ims, eptrb, match_isgroup); - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - RMATCH(rrc, eptr, ecode + 1+LINK_SIZE, offset_top, md, ims, eptrb, 0); - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - } - } - - RRETURN(MATCH_NOMATCH); - - /* Start of subject unless notbol, or after internal newline if multiline */ - - case OP_CIRC: - if (md->notbol && eptr == md->start_subject) RRETURN(MATCH_NOMATCH); - if ((ims & PCRE_MULTILINE) != 0) - { - if (eptr != md->start_subject && eptr[-1] != NEWLINE) - RRETURN(MATCH_NOMATCH); - ecode++; - break; - } - /* ... else fall through */ - - /* Start of subject assertion */ - - case OP_SOD: - if (eptr != md->start_subject) RRETURN(MATCH_NOMATCH); - ecode++; - break; - - /* Start of match assertion */ - - case OP_SOM: - if (eptr != md->start_subject + md->start_offset) RRETURN(MATCH_NOMATCH); - ecode++; - break; - - /* Assert before internal newline if multiline, or before a terminating - newline unless endonly is set, else end of subject unless noteol is set. */ - - case OP_DOLL: - if ((ims & PCRE_MULTILINE) != 0) - { - if (eptr < md->end_subject) - { if (*eptr != NEWLINE) RRETURN(MATCH_NOMATCH); } - else - { if (md->noteol) RRETURN(MATCH_NOMATCH); } - ecode++; - break; - } - else - { - if (md->noteol) RRETURN(MATCH_NOMATCH); - if (!md->endonly) - { - if (eptr < md->end_subject - 1 || - (eptr == md->end_subject - 1 && *eptr != NEWLINE)) - RRETURN(MATCH_NOMATCH); - ecode++; - break; - } - } - /* ... else fall through */ - - /* End of subject assertion (\z) */ - - case OP_EOD: - if (eptr < md->end_subject) RRETURN(MATCH_NOMATCH); - ecode++; - break; - - /* End of subject or ending \n assertion (\Z) */ - - case OP_EODN: - if (eptr < md->end_subject - 1 || - (eptr == md->end_subject - 1 && *eptr != NEWLINE)) RRETURN(MATCH_NOMATCH); - ecode++; - break; - - /* Word boundary assertions */ - - case OP_NOT_WORD_BOUNDARY: - case OP_WORD_BOUNDARY: - { - - /* Find out if the previous and current characters are "word" characters. - It takes a bit more work in UTF-8 mode. Characters > 255 are assumed to - be "non-word" characters. */ - -#ifdef SUPPORT_UTF8 - if (md->utf8) - { - if (eptr == md->start_subject) prev_is_word = FALSE; else - { - const uschar *lastptr = eptr - 1; - while((*lastptr & 0xc0) == 0x80) lastptr--; - GETCHAR(c, lastptr); - prev_is_word = c < 256 && (md->ctypes[c] & ctype_word) != 0; - } - if (eptr >= md->end_subject) cur_is_word = FALSE; else - { - GETCHAR(c, eptr); - cur_is_word = c < 256 && (md->ctypes[c] & ctype_word) != 0; - } - } - else -#endif - - /* More streamlined when not in UTF-8 mode */ - - { - prev_is_word = (eptr != md->start_subject) && - ((md->ctypes[eptr[-1]] & ctype_word) != 0); - cur_is_word = (eptr < md->end_subject) && - ((md->ctypes[*eptr] & ctype_word) != 0); - } - - /* Now see if the situation is what we want */ - - if ((*ecode++ == OP_WORD_BOUNDARY)? - cur_is_word == prev_is_word : cur_is_word != prev_is_word) - RRETURN(MATCH_NOMATCH); - } - break; - - /* Match a single character type; inline for speed */ - - case OP_ANY: - if ((ims & PCRE_DOTALL) == 0 && eptr < md->end_subject && *eptr == NEWLINE) - RRETURN(MATCH_NOMATCH); - if (eptr++ >= md->end_subject) RRETURN(MATCH_NOMATCH); -#ifdef SUPPORT_UTF8 - if (md->utf8) - while (eptr < md->end_subject && (*eptr & 0xc0) == 0x80) eptr++; -#endif - ecode++; - break; - - /* Match a single byte, even in UTF-8 mode. This opcode really does match - any byte, even newline, independent of the setting of PCRE_DOTALL. */ - - case OP_ANYBYTE: - if (eptr++ >= md->end_subject) RRETURN(MATCH_NOMATCH); - ecode++; - break; - - case OP_NOT_DIGIT: - if (eptr >= md->end_subject) RRETURN(MATCH_NOMATCH); - GETCHARINCTEST(c, eptr); - if ( -#ifdef SUPPORT_UTF8 - c < 256 && -#endif - (md->ctypes[c] & ctype_digit) != 0 - ) - RRETURN(MATCH_NOMATCH); - ecode++; - break; - - case OP_DIGIT: - if (eptr >= md->end_subject) RRETURN(MATCH_NOMATCH); - GETCHARINCTEST(c, eptr); - if ( -#ifdef SUPPORT_UTF8 - c >= 256 || -#endif - (md->ctypes[c] & ctype_digit) == 0 - ) - RRETURN(MATCH_NOMATCH); - ecode++; - break; - - case OP_NOT_WHITESPACE: - if (eptr >= md->end_subject) RRETURN(MATCH_NOMATCH); - GETCHARINCTEST(c, eptr); - if ( -#ifdef SUPPORT_UTF8 - c < 256 && -#endif - (md->ctypes[c] & ctype_space) != 0 - ) - RRETURN(MATCH_NOMATCH); - ecode++; - break; - - case OP_WHITESPACE: - if (eptr >= md->end_subject) RRETURN(MATCH_NOMATCH); - GETCHARINCTEST(c, eptr); - if ( -#ifdef SUPPORT_UTF8 - c >= 256 || -#endif - (md->ctypes[c] & ctype_space) == 0 - ) - RRETURN(MATCH_NOMATCH); - ecode++; - break; - - case OP_NOT_WORDCHAR: - if (eptr >= md->end_subject) RRETURN(MATCH_NOMATCH); - GETCHARINCTEST(c, eptr); - if ( -#ifdef SUPPORT_UTF8 - c < 256 && -#endif - (md->ctypes[c] & ctype_word) != 0 - ) - RRETURN(MATCH_NOMATCH); - ecode++; - break; - - case OP_WORDCHAR: - if (eptr >= md->end_subject) RRETURN(MATCH_NOMATCH); - GETCHARINCTEST(c, eptr); - if ( -#ifdef SUPPORT_UTF8 - c >= 256 || -#endif - (md->ctypes[c] & ctype_word) == 0 - ) - RRETURN(MATCH_NOMATCH); - ecode++; - break; - -#ifdef SUPPORT_UCP - /* Check the next character by Unicode property. We will get here only - if the support is in the binary; otherwise a compile-time error occurs. */ - - case OP_PROP: - case OP_NOTPROP: - if (eptr >= md->end_subject) RRETURN(MATCH_NOMATCH); - GETCHARINCTEST(c, eptr); - { - int chartype, rqdtype; - int othercase; - int category = ucp_findchar(c, &chartype, &othercase); - - rqdtype = *(++ecode); - ecode++; - - if (rqdtype >= 128) - { - if ((rqdtype - 128 != category) == (op == OP_PROP)) - RRETURN(MATCH_NOMATCH); - } - else - { - if ((rqdtype != chartype) == (op == OP_PROP)) - RRETURN(MATCH_NOMATCH); - } - } - break; - - /* Match an extended Unicode sequence. We will get here only if the support - is in the binary; otherwise a compile-time error occurs. */ - - case OP_EXTUNI: - if (eptr >= md->end_subject) RRETURN(MATCH_NOMATCH); - GETCHARINCTEST(c, eptr); - { - int chartype; - int othercase; - int category = ucp_findchar(c, &chartype, &othercase); - if (category == ucp_M) RRETURN(MATCH_NOMATCH); - while (eptr < md->end_subject) - { - int len = 1; - if (!md->utf8) c = *eptr; else - { - GETCHARLEN(c, eptr, len); - } - category = ucp_findchar(c, &chartype, &othercase); - if (category != ucp_M) break; - eptr += len; - } - } - ecode++; - break; -#endif - - - /* Match a back reference, possibly repeatedly. Look past the end of the - item to see if there is repeat information following. The code is similar - to that for character classes, but repeated for efficiency. Then obey - similar code to character type repeats - written out again for speed. - However, if the referenced string is the empty string, always treat - it as matched, any number of times (otherwise there could be infinite - loops). */ - - case OP_REF: - { - offset = GET2(ecode, 1) << 1; /* Doubled ref number */ - ecode += 3; /* Advance past item */ - - /* If the reference is unset, set the length to be longer than the amount - of subject left; this ensures that every attempt at a match fails. We - can't just fail here, because of the possibility of quantifiers with zero - minima. */ - - length = (offset >= offset_top || md->offset_vector[offset] < 0)? - md->end_subject - eptr + 1 : - md->offset_vector[offset+1] - md->offset_vector[offset]; - - /* Set up for repetition, or handle the non-repeated case */ - - switch (*ecode) - { - case OP_CRSTAR: - case OP_CRMINSTAR: - case OP_CRPLUS: - case OP_CRMINPLUS: - case OP_CRQUERY: - case OP_CRMINQUERY: - c = *ecode++ - OP_CRSTAR; - minimize = (c & 1) != 0; - min = rep_min[c]; /* Pick up values from tables; */ - max = rep_max[c]; /* zero for max => infinity */ - if (max == 0) max = INT_MAX; - break; - - case OP_CRRANGE: - case OP_CRMINRANGE: - minimize = (*ecode == OP_CRMINRANGE); - min = GET2(ecode, 1); - max = GET2(ecode, 3); - if (max == 0) max = INT_MAX; - ecode += 5; - break; - - default: /* No repeat follows */ - if (!match_ref(offset, eptr, length, md, ims)) RRETURN(MATCH_NOMATCH); - eptr += length; - continue; /* With the main loop */ - } - - /* If the length of the reference is zero, just continue with the - main loop. */ - - if (length == 0) continue; - - /* First, ensure the minimum number of matches are present. We get back - the length of the reference string explicitly rather than passing the - address of eptr, so that eptr can be a register variable. */ - - for (i = 1; i <= min; i++) - { - if (!match_ref(offset, eptr, length, md, ims)) RRETURN(MATCH_NOMATCH); - eptr += length; - } - - /* If min = max, continue at the same level without recursion. - They are not both allowed to be zero. */ - - if (min == max) continue; - - /* If minimizing, keep trying and advancing the pointer */ - - if (minimize) - { - for (fi = min;; fi++) - { - RMATCH(rrc, eptr, ecode, offset_top, md, ims, eptrb, 0); - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - if (fi >= max || !match_ref(offset, eptr, length, md, ims)) - RRETURN(MATCH_NOMATCH); - eptr += length; - } - /* Control never gets here */ - } - - /* If maximizing, find the longest string and work backwards */ - - else - { - pp = eptr; - for (i = min; i < max; i++) - { - if (!match_ref(offset, eptr, length, md, ims)) break; - eptr += length; - } - while (eptr >= pp) - { - RMATCH(rrc, eptr, ecode, offset_top, md, ims, eptrb, 0); - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - eptr -= length; - } - RRETURN(MATCH_NOMATCH); - } - } - /* Control never gets here */ - - - - /* Match a bit-mapped character class, possibly repeatedly. This op code is - used when all the characters in the class have values in the range 0-255, - and either the matching is caseful, or the characters are in the range - 0-127 when UTF-8 processing is enabled. The only difference between - OP_CLASS and OP_NCLASS occurs when a data character outside the range is - encountered. - - First, look past the end of the item to see if there is repeat information - following. Then obey similar code to character type repeats - written out - again for speed. */ - - case OP_NCLASS: - case OP_CLASS: - { - data = ecode + 1; /* Save for matching */ - ecode += 33; /* Advance past the item */ - - switch (*ecode) - { - case OP_CRSTAR: - case OP_CRMINSTAR: - case OP_CRPLUS: - case OP_CRMINPLUS: - case OP_CRQUERY: - case OP_CRMINQUERY: - c = *ecode++ - OP_CRSTAR; - minimize = (c & 1) != 0; - min = rep_min[c]; /* Pick up values from tables; */ - max = rep_max[c]; /* zero for max => infinity */ - if (max == 0) max = INT_MAX; - break; - - case OP_CRRANGE: - case OP_CRMINRANGE: - minimize = (*ecode == OP_CRMINRANGE); - min = GET2(ecode, 1); - max = GET2(ecode, 3); - if (max == 0) max = INT_MAX; - ecode += 5; - break; - - default: /* No repeat follows */ - min = max = 1; - break; - } - - /* First, ensure the minimum number of matches are present. */ - -#ifdef SUPPORT_UTF8 - /* UTF-8 mode */ - if (md->utf8) - { - for (i = 1; i <= min; i++) - { - if (eptr >= md->end_subject) RRETURN(MATCH_NOMATCH); - GETCHARINC(c, eptr); - if (c > 255) - { - if (op == OP_CLASS) RRETURN(MATCH_NOMATCH); - } - else - { - if ((data[c/8] & (1 << (c&7))) == 0) RRETURN(MATCH_NOMATCH); - } - } - } - else -#endif - /* Not UTF-8 mode */ - { - for (i = 1; i <= min; i++) - { - if (eptr >= md->end_subject) RRETURN(MATCH_NOMATCH); - c = *eptr++; - if ((data[c/8] & (1 << (c&7))) == 0) RRETURN(MATCH_NOMATCH); - } - } - - /* If max == min we can continue with the main loop without the - need to recurse. */ - - if (min == max) continue; - - /* If minimizing, keep testing the rest of the expression and advancing - the pointer while it matches the class. */ - - if (minimize) - { -#ifdef SUPPORT_UTF8 - /* UTF-8 mode */ - if (md->utf8) - { - for (fi = min;; fi++) - { - RMATCH(rrc, eptr, ecode, offset_top, md, ims, eptrb, 0); - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - if (fi >= max || eptr >= md->end_subject) RRETURN(MATCH_NOMATCH); - GETCHARINC(c, eptr); - if (c > 255) - { - if (op == OP_CLASS) RRETURN(MATCH_NOMATCH); - } - else - { - if ((data[c/8] & (1 << (c&7))) == 0) RRETURN(MATCH_NOMATCH); - } - } - } - else -#endif - /* Not UTF-8 mode */ - { - for (fi = min;; fi++) - { - RMATCH(rrc, eptr, ecode, offset_top, md, ims, eptrb, 0); - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - if (fi >= max || eptr >= md->end_subject) RRETURN(MATCH_NOMATCH); - c = *eptr++; - if ((data[c/8] & (1 << (c&7))) == 0) RRETURN(MATCH_NOMATCH); - } - } - /* Control never gets here */ - } - - /* If maximizing, find the longest possible run, then work backwards. */ - - else - { - pp = eptr; - -#ifdef SUPPORT_UTF8 - /* UTF-8 mode */ - if (md->utf8) - { - for (i = min; i < max; i++) - { - int len = 1; - if (eptr >= md->end_subject) break; - GETCHARLEN(c, eptr, len); - if (c > 255) - { - if (op == OP_CLASS) break; - } - else - { - if ((data[c/8] & (1 << (c&7))) == 0) break; - } - eptr += len; - } - for (;;) - { - RMATCH(rrc, eptr, ecode, offset_top, md, ims, eptrb, 0); - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - if (eptr-- == pp) break; /* Stop if tried at original pos */ - BACKCHAR(eptr); - } - } - else -#endif - /* Not UTF-8 mode */ - { - for (i = min; i < max; i++) - { - if (eptr >= md->end_subject) break; - c = *eptr; - if ((data[c/8] & (1 << (c&7))) == 0) break; - eptr++; - } - while (eptr >= pp) - { - RMATCH(rrc, eptr, ecode, offset_top, md, ims, eptrb, 0); - eptr--; - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - } - } - - RRETURN(MATCH_NOMATCH); - } - } - /* Control never gets here */ - - - /* Match an extended character class. This opcode is encountered only - in UTF-8 mode, because that's the only time it is compiled. */ - -#ifdef SUPPORT_UTF8 - case OP_XCLASS: - { - data = ecode + 1 + LINK_SIZE; /* Save for matching */ - ecode += GET(ecode, 1); /* Advance past the item */ - - switch (*ecode) - { - case OP_CRSTAR: - case OP_CRMINSTAR: - case OP_CRPLUS: - case OP_CRMINPLUS: - case OP_CRQUERY: - case OP_CRMINQUERY: - c = *ecode++ - OP_CRSTAR; - minimize = (c & 1) != 0; - min = rep_min[c]; /* Pick up values from tables; */ - max = rep_max[c]; /* zero for max => infinity */ - if (max == 0) max = INT_MAX; - break; - - case OP_CRRANGE: - case OP_CRMINRANGE: - minimize = (*ecode == OP_CRMINRANGE); - min = GET2(ecode, 1); - max = GET2(ecode, 3); - if (max == 0) max = INT_MAX; - ecode += 5; - break; - - default: /* No repeat follows */ - min = max = 1; - break; - } - - /* First, ensure the minimum number of matches are present. */ - - for (i = 1; i <= min; i++) - { - if (eptr >= md->end_subject) RRETURN(MATCH_NOMATCH); - GETCHARINC(c, eptr); - if (!match_xclass(c, data)) RRETURN(MATCH_NOMATCH); - } - - /* If max == min we can continue with the main loop without the - need to recurse. */ - - if (min == max) continue; - - /* If minimizing, keep testing the rest of the expression and advancing - the pointer while it matches the class. */ - - if (minimize) - { - for (fi = min;; fi++) - { - RMATCH(rrc, eptr, ecode, offset_top, md, ims, eptrb, 0); - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - if (fi >= max || eptr >= md->end_subject) RRETURN(MATCH_NOMATCH); - GETCHARINC(c, eptr); - if (!match_xclass(c, data)) RRETURN(MATCH_NOMATCH); - } - /* Control never gets here */ - } - - /* If maximizing, find the longest possible run, then work backwards. */ - - else - { - pp = eptr; - for (i = min; i < max; i++) - { - int len = 1; - if (eptr >= md->end_subject) break; - GETCHARLEN(c, eptr, len); - if (!match_xclass(c, data)) break; - eptr += len; - } - for(;;) - { - RMATCH(rrc, eptr, ecode, offset_top, md, ims, eptrb, 0); - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - if (eptr-- == pp) break; /* Stop if tried at original pos */ - BACKCHAR(eptr) - } - RRETURN(MATCH_NOMATCH); - } - - /* Control never gets here */ - } -#endif /* End of XCLASS */ - - /* Match a single character, casefully */ - - case OP_CHAR: -#ifdef SUPPORT_UTF8 - if (md->utf8) - { - length = 1; - ecode++; - GETCHARLEN(fc, ecode, length); - if (length > md->end_subject - eptr) RRETURN(MATCH_NOMATCH); - while (length-- > 0) if (*ecode++ != *eptr++) RRETURN(MATCH_NOMATCH); - } - else -#endif - - /* Non-UTF-8 mode */ - { - if (md->end_subject - eptr < 1) RRETURN(MATCH_NOMATCH); - if (ecode[1] != *eptr++) RRETURN(MATCH_NOMATCH); - ecode += 2; - } - break; - - /* Match a single character, caselessly */ - - case OP_CHARNC: -#ifdef SUPPORT_UTF8 - if (md->utf8) - { - length = 1; - ecode++; - GETCHARLEN(fc, ecode, length); - - if (length > md->end_subject - eptr) RRETURN(MATCH_NOMATCH); - - /* If the pattern character's value is < 128, we have only one byte, and - can use the fast lookup table. */ - - if (fc < 128) - { - if (md->lcc[*ecode++] != md->lcc[*eptr++]) RRETURN(MATCH_NOMATCH); - } - - /* Otherwise we must pick up the subject character */ - - else - { - int dc; - GETCHARINC(dc, eptr); - ecode += length; - - /* If we have Unicode property support, we can use it to test the other - case of the character, if there is one. The result of ucp_findchar() is - < 0 if the char isn't found, and othercase is returned as zero if there - isn't one. */ - - if (fc != dc) - { -#ifdef SUPPORT_UCP - int chartype; - int othercase; - if (ucp_findchar(fc, &chartype, &othercase) < 0 || dc != othercase) -#endif - RRETURN(MATCH_NOMATCH); - } - } - } - else -#endif /* SUPPORT_UTF8 */ - - /* Non-UTF-8 mode */ - { - if (md->end_subject - eptr < 1) RRETURN(MATCH_NOMATCH); - if (md->lcc[ecode[1]] != md->lcc[*eptr++]) RRETURN(MATCH_NOMATCH); - ecode += 2; - } - break; - - /* Match a single character repeatedly; different opcodes share code. */ - - case OP_EXACT: - min = max = GET2(ecode, 1); - ecode += 3; - goto REPEATCHAR; - - case OP_UPTO: - case OP_MINUPTO: - min = 0; - max = GET2(ecode, 1); - minimize = *ecode == OP_MINUPTO; - ecode += 3; - goto REPEATCHAR; - - case OP_STAR: - case OP_MINSTAR: - case OP_PLUS: - case OP_MINPLUS: - case OP_QUERY: - case OP_MINQUERY: - c = *ecode++ - OP_STAR; - minimize = (c & 1) != 0; - min = rep_min[c]; /* Pick up values from tables; */ - max = rep_max[c]; /* zero for max => infinity */ - if (max == 0) max = INT_MAX; - - /* Common code for all repeated single-character matches. We can give - up quickly if there are fewer than the minimum number of characters left in - the subject. */ - - REPEATCHAR: -#ifdef SUPPORT_UTF8 - if (md->utf8) - { - length = 1; - charptr = ecode; - GETCHARLEN(fc, ecode, length); - if (min * length > md->end_subject - eptr) RRETURN(MATCH_NOMATCH); - ecode += length; - - /* Handle multibyte character matching specially here. There is - support for caseless matching if UCP support is present. */ - - if (length > 1) - { - int oclength = 0; - uschar occhars[8]; - -#ifdef SUPPORT_UCP - int othercase; - int chartype; - if ((ims & PCRE_CASELESS) != 0 && - ucp_findchar(fc, &chartype, &othercase) >= 0 && - othercase > 0) - oclength = ord2utf8(othercase, occhars); -#endif /* SUPPORT_UCP */ - - for (i = 1; i <= min; i++) - { - if (memcmp(eptr, charptr, length) == 0) eptr += length; - /* Need braces because of following else */ - else if (oclength == 0) { RRETURN(MATCH_NOMATCH); } - else - { - if (memcmp(eptr, occhars, oclength) != 0) RRETURN(MATCH_NOMATCH); - eptr += oclength; - } - } - - if (min == max) continue; - - if (minimize) - { - for (fi = min;; fi++) - { - RMATCH(rrc, eptr, ecode, offset_top, md, ims, eptrb, 0); - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - if (fi >= max || eptr >= md->end_subject) RRETURN(MATCH_NOMATCH); - if (memcmp(eptr, charptr, length) == 0) eptr += length; - /* Need braces because of following else */ - else if (oclength == 0) { RRETURN(MATCH_NOMATCH); } - else - { - if (memcmp(eptr, occhars, oclength) != 0) RRETURN(MATCH_NOMATCH); - eptr += oclength; - } - } - /* Control never gets here */ - } - else - { - pp = eptr; - for (i = min; i < max; i++) - { - if (eptr > md->end_subject - length) break; - if (memcmp(eptr, charptr, length) == 0) eptr += length; - else if (oclength == 0) break; - else - { - if (memcmp(eptr, occhars, oclength) != 0) break; - eptr += oclength; - } - } - while (eptr >= pp) - { - RMATCH(rrc, eptr, ecode, offset_top, md, ims, eptrb, 0); - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - eptr -= length; - } - RRETURN(MATCH_NOMATCH); - } - /* Control never gets here */ - } - - /* If the length of a UTF-8 character is 1, we fall through here, and - obey the code as for non-UTF-8 characters below, though in this case the - value of fc will always be < 128. */ - } - else -#endif /* SUPPORT_UTF8 */ - - /* When not in UTF-8 mode, load a single-byte character. */ - { - if (min > md->end_subject - eptr) RRETURN(MATCH_NOMATCH); - fc = *ecode++; - } - - /* The value of fc at this point is always less than 256, though we may or - may not be in UTF-8 mode. The code is duplicated for the caseless and - caseful cases, for speed, since matching characters is likely to be quite - common. First, ensure the minimum number of matches are present. If min = - max, continue at the same level without recursing. Otherwise, if - minimizing, keep trying the rest of the expression and advancing one - matching character if failing, up to the maximum. Alternatively, if - maximizing, find the maximum number of characters and work backwards. */ - - DPRINTF(("matching %c{%d,%d} against subject %.*s\n", fc, min, max, - max, eptr)); - - if ((ims & PCRE_CASELESS) != 0) - { - fc = md->lcc[fc]; - for (i = 1; i <= min; i++) - if (fc != md->lcc[*eptr++]) RRETURN(MATCH_NOMATCH); - if (min == max) continue; - if (minimize) - { - for (fi = min;; fi++) - { - RMATCH(rrc, eptr, ecode, offset_top, md, ims, eptrb, 0); - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - if (fi >= max || eptr >= md->end_subject || - fc != md->lcc[*eptr++]) - RRETURN(MATCH_NOMATCH); - } - /* Control never gets here */ - } - else - { - pp = eptr; - for (i = min; i < max; i++) - { - if (eptr >= md->end_subject || fc != md->lcc[*eptr]) break; - eptr++; - } - while (eptr >= pp) - { - RMATCH(rrc, eptr, ecode, offset_top, md, ims, eptrb, 0); - eptr--; - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - } - RRETURN(MATCH_NOMATCH); - } - /* Control never gets here */ - } - - /* Caseful comparisons (includes all multi-byte characters) */ - - else - { - for (i = 1; i <= min; i++) if (fc != *eptr++) RRETURN(MATCH_NOMATCH); - if (min == max) continue; - if (minimize) - { - for (fi = min;; fi++) - { - RMATCH(rrc, eptr, ecode, offset_top, md, ims, eptrb, 0); - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - if (fi >= max || eptr >= md->end_subject || fc != *eptr++) - RRETURN(MATCH_NOMATCH); - } - /* Control never gets here */ - } - else - { - pp = eptr; - for (i = min; i < max; i++) - { - if (eptr >= md->end_subject || fc != *eptr) break; - eptr++; - } - while (eptr >= pp) - { - RMATCH(rrc, eptr, ecode, offset_top, md, ims, eptrb, 0); - eptr--; - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - } - RRETURN(MATCH_NOMATCH); - } - } - /* Control never gets here */ - - /* Match a negated single one-byte character. The character we are - checking can be multibyte. */ - - case OP_NOT: - if (eptr >= md->end_subject) RRETURN(MATCH_NOMATCH); - ecode++; - GETCHARINCTEST(c, eptr); - if ((ims & PCRE_CASELESS) != 0) - { -#ifdef SUPPORT_UTF8 - if (c < 256) -#endif - c = md->lcc[c]; - if (md->lcc[*ecode++] == c) RRETURN(MATCH_NOMATCH); - } - else - { - if (*ecode++ == c) RRETURN(MATCH_NOMATCH); - } - break; - - /* Match a negated single one-byte character repeatedly. This is almost a - repeat of the code for a repeated single character, but I haven't found a - nice way of commoning these up that doesn't require a test of the - positive/negative option for each character match. Maybe that wouldn't add - very much to the time taken, but character matching *is* what this is all - about... */ - - case OP_NOTEXACT: - min = max = GET2(ecode, 1); - ecode += 3; - goto REPEATNOTCHAR; - - case OP_NOTUPTO: - case OP_NOTMINUPTO: - min = 0; - max = GET2(ecode, 1); - minimize = *ecode == OP_NOTMINUPTO; - ecode += 3; - goto REPEATNOTCHAR; - - case OP_NOTSTAR: - case OP_NOTMINSTAR: - case OP_NOTPLUS: - case OP_NOTMINPLUS: - case OP_NOTQUERY: - case OP_NOTMINQUERY: - c = *ecode++ - OP_NOTSTAR; - minimize = (c & 1) != 0; - min = rep_min[c]; /* Pick up values from tables; */ - max = rep_max[c]; /* zero for max => infinity */ - if (max == 0) max = INT_MAX; - - /* Common code for all repeated single-byte matches. We can give up quickly - if there are fewer than the minimum number of bytes left in the - subject. */ - - REPEATNOTCHAR: - if (min > md->end_subject - eptr) RRETURN(MATCH_NOMATCH); - fc = *ecode++; - - /* The code is duplicated for the caseless and caseful cases, for speed, - since matching characters is likely to be quite common. First, ensure the - minimum number of matches are present. If min = max, continue at the same - level without recursing. Otherwise, if minimizing, keep trying the rest of - the expression and advancing one matching character if failing, up to the - maximum. Alternatively, if maximizing, find the maximum number of - characters and work backwards. */ - - DPRINTF(("negative matching %c{%d,%d} against subject %.*s\n", fc, min, max, - max, eptr)); - - if ((ims & PCRE_CASELESS) != 0) - { - fc = md->lcc[fc]; - -#ifdef SUPPORT_UTF8 - /* UTF-8 mode */ - if (md->utf8) - { - register int d; - for (i = 1; i <= min; i++) - { - GETCHARINC(d, eptr); - if (d < 256) d = md->lcc[d]; - if (fc == d) RRETURN(MATCH_NOMATCH); - } - } - else -#endif - - /* Not UTF-8 mode */ - { - for (i = 1; i <= min; i++) - if (fc == md->lcc[*eptr++]) RRETURN(MATCH_NOMATCH); - } - - if (min == max) continue; - - if (minimize) - { -#ifdef SUPPORT_UTF8 - /* UTF-8 mode */ - if (md->utf8) - { - register int d; - for (fi = min;; fi++) - { - RMATCH(rrc, eptr, ecode, offset_top, md, ims, eptrb, 0); - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - GETCHARINC(d, eptr); - if (d < 256) d = md->lcc[d]; - if (fi >= max || eptr >= md->end_subject || fc == d) - RRETURN(MATCH_NOMATCH); - } - } - else -#endif - /* Not UTF-8 mode */ - { - for (fi = min;; fi++) - { - RMATCH(rrc, eptr, ecode, offset_top, md, ims, eptrb, 0); - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - if (fi >= max || eptr >= md->end_subject || fc == md->lcc[*eptr++]) - RRETURN(MATCH_NOMATCH); - } - } - /* Control never gets here */ - } - - /* Maximize case */ - - else - { - pp = eptr; - -#ifdef SUPPORT_UTF8 - /* UTF-8 mode */ - if (md->utf8) - { - register int d; - for (i = min; i < max; i++) - { - int len = 1; - if (eptr >= md->end_subject) break; - GETCHARLEN(d, eptr, len); - if (d < 256) d = md->lcc[d]; - if (fc == d) break; - eptr += len; - } - for(;;) - { - RMATCH(rrc, eptr, ecode, offset_top, md, ims, eptrb, 0); - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - if (eptr-- == pp) break; /* Stop if tried at original pos */ - BACKCHAR(eptr); - } - } - else -#endif - /* Not UTF-8 mode */ - { - for (i = min; i < max; i++) - { - if (eptr >= md->end_subject || fc == md->lcc[*eptr]) break; - eptr++; - } - while (eptr >= pp) - { - RMATCH(rrc, eptr, ecode, offset_top, md, ims, eptrb, 0); - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - eptr--; - } - } - - RRETURN(MATCH_NOMATCH); - } - /* Control never gets here */ - } - - /* Caseful comparisons */ - - else - { -#ifdef SUPPORT_UTF8 - /* UTF-8 mode */ - if (md->utf8) - { - register int d; - for (i = 1; i <= min; i++) - { - GETCHARINC(d, eptr); - if (fc == d) RRETURN(MATCH_NOMATCH); - } - } - else -#endif - /* Not UTF-8 mode */ - { - for (i = 1; i <= min; i++) - if (fc == *eptr++) RRETURN(MATCH_NOMATCH); - } - - if (min == max) continue; - - if (minimize) - { -#ifdef SUPPORT_UTF8 - /* UTF-8 mode */ - if (md->utf8) - { - register int d; - for (fi = min;; fi++) - { - RMATCH(rrc, eptr, ecode, offset_top, md, ims, eptrb, 0); - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - GETCHARINC(d, eptr); - if (fi >= max || eptr >= md->end_subject || fc == d) - RRETURN(MATCH_NOMATCH); - } - } - else -#endif - /* Not UTF-8 mode */ - { - for (fi = min;; fi++) - { - RMATCH(rrc, eptr, ecode, offset_top, md, ims, eptrb, 0); - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - if (fi >= max || eptr >= md->end_subject || fc == *eptr++) - RRETURN(MATCH_NOMATCH); - } - } - /* Control never gets here */ - } - - /* Maximize case */ - - else - { - pp = eptr; - -#ifdef SUPPORT_UTF8 - /* UTF-8 mode */ - if (md->utf8) - { - register int d; - for (i = min; i < max; i++) - { - int len = 1; - if (eptr >= md->end_subject) break; - GETCHARLEN(d, eptr, len); - if (fc == d) break; - eptr += len; - } - for(;;) - { - RMATCH(rrc, eptr, ecode, offset_top, md, ims, eptrb, 0); - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - if (eptr-- == pp) break; /* Stop if tried at original pos */ - BACKCHAR(eptr); - } - } - else -#endif - /* Not UTF-8 mode */ - { - for (i = min; i < max; i++) - { - if (eptr >= md->end_subject || fc == *eptr) break; - eptr++; - } - while (eptr >= pp) - { - RMATCH(rrc, eptr, ecode, offset_top, md, ims, eptrb, 0); - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - eptr--; - } - } - - RRETURN(MATCH_NOMATCH); - } - } - /* Control never gets here */ - - /* Match a single character type repeatedly; several different opcodes - share code. This is very similar to the code for single characters, but we - repeat it in the interests of efficiency. */ - - case OP_TYPEEXACT: - min = max = GET2(ecode, 1); - minimize = TRUE; - ecode += 3; - goto REPEATTYPE; - - case OP_TYPEUPTO: - case OP_TYPEMINUPTO: - min = 0; - max = GET2(ecode, 1); - minimize = *ecode == OP_TYPEMINUPTO; - ecode += 3; - goto REPEATTYPE; - - case OP_TYPESTAR: - case OP_TYPEMINSTAR: - case OP_TYPEPLUS: - case OP_TYPEMINPLUS: - case OP_TYPEQUERY: - case OP_TYPEMINQUERY: - c = *ecode++ - OP_TYPESTAR; - minimize = (c & 1) != 0; - min = rep_min[c]; /* Pick up values from tables; */ - max = rep_max[c]; /* zero for max => infinity */ - if (max == 0) max = INT_MAX; - - /* Common code for all repeated single character type matches. Note that - in UTF-8 mode, '.' matches a character of any length, but for the other - character types, the valid characters are all one-byte long. */ - - REPEATTYPE: - ctype = *ecode++; /* Code for the character type */ - -#ifdef SUPPORT_UCP - if (ctype == OP_PROP || ctype == OP_NOTPROP) - { - prop_fail_result = ctype == OP_NOTPROP; - prop_type = *ecode++; - if (prop_type >= 128) - { - prop_test_against = prop_type - 128; - prop_test_variable = &prop_category; - } - else - { - prop_test_against = prop_type; - prop_test_variable = &prop_chartype; - } - } - else prop_type = -1; -#endif - - /* First, ensure the minimum number of matches are present. Use inline - code for maximizing the speed, and do the type test once at the start - (i.e. keep it out of the loop). Also we can test that there are at least - the minimum number of bytes before we start. This isn't as effective in - UTF-8 mode, but it does no harm. Separate the UTF-8 code completely as that - is tidier. Also separate the UCP code, which can be the same for both UTF-8 - and single-bytes. */ - - if (min > md->end_subject - eptr) RRETURN(MATCH_NOMATCH); - if (min > 0) - { -#ifdef SUPPORT_UCP - if (prop_type > 0) - { - for (i = 1; i <= min; i++) - { - GETCHARINC(c, eptr); - prop_category = ucp_findchar(c, &prop_chartype, &prop_othercase); - if ((*prop_test_variable == prop_test_against) == prop_fail_result) - RRETURN(MATCH_NOMATCH); - } - } - - /* Match extended Unicode sequences. We will get here only if the - support is in the binary; otherwise a compile-time error occurs. */ - - else if (ctype == OP_EXTUNI) - { - for (i = 1; i <= min; i++) - { - GETCHARINCTEST(c, eptr); - prop_category = ucp_findchar(c, &prop_chartype, &prop_othercase); - if (prop_category == ucp_M) RRETURN(MATCH_NOMATCH); - while (eptr < md->end_subject) - { - int len = 1; - if (!md->utf8) c = *eptr; else - { - GETCHARLEN(c, eptr, len); - } - prop_category = ucp_findchar(c, &prop_chartype, &prop_othercase); - if (prop_category != ucp_M) break; - eptr += len; - } - } - } - - else -#endif /* SUPPORT_UCP */ - -/* Handle all other cases when the coding is UTF-8 */ - -#ifdef SUPPORT_UTF8 - if (md->utf8) switch(ctype) - { - case OP_ANY: - for (i = 1; i <= min; i++) - { - if (eptr >= md->end_subject || - (*eptr++ == NEWLINE && (ims & PCRE_DOTALL) == 0)) - RRETURN(MATCH_NOMATCH); - while (eptr < md->end_subject && (*eptr & 0xc0) == 0x80) eptr++; - } - break; - - case OP_ANYBYTE: - eptr += min; - break; - - case OP_NOT_DIGIT: - for (i = 1; i <= min; i++) - { - if (eptr >= md->end_subject) RRETURN(MATCH_NOMATCH); - GETCHARINC(c, eptr); - if (c < 128 && (md->ctypes[c] & ctype_digit) != 0) - RRETURN(MATCH_NOMATCH); - } - break; - - case OP_DIGIT: - for (i = 1; i <= min; i++) - { - if (eptr >= md->end_subject || - *eptr >= 128 || (md->ctypes[*eptr++] & ctype_digit) == 0) - RRETURN(MATCH_NOMATCH); - /* No need to skip more bytes - we know it's a 1-byte character */ - } - break; - - case OP_NOT_WHITESPACE: - for (i = 1; i <= min; i++) - { - if (eptr >= md->end_subject || - (*eptr < 128 && (md->ctypes[*eptr++] & ctype_space) != 0)) - RRETURN(MATCH_NOMATCH); - while (eptr < md->end_subject && (*eptr & 0xc0) == 0x80) eptr++; - } - break; - - case OP_WHITESPACE: - for (i = 1; i <= min; i++) - { - if (eptr >= md->end_subject || - *eptr >= 128 || (md->ctypes[*eptr++] & ctype_space) == 0) - RRETURN(MATCH_NOMATCH); - /* No need to skip more bytes - we know it's a 1-byte character */ - } - break; - - case OP_NOT_WORDCHAR: - for (i = 1; i <= min; i++) - { - if (eptr >= md->end_subject || - (*eptr < 128 && (md->ctypes[*eptr++] & ctype_word) != 0)) - RRETURN(MATCH_NOMATCH); - while (eptr < md->end_subject && (*eptr & 0xc0) == 0x80) eptr++; - } - break; - - case OP_WORDCHAR: - for (i = 1; i <= min; i++) - { - if (eptr >= md->end_subject || - *eptr >= 128 || (md->ctypes[*eptr++] & ctype_word) == 0) - RRETURN(MATCH_NOMATCH); - /* No need to skip more bytes - we know it's a 1-byte character */ - } - break; - - default: - RRETURN(PCRE_ERROR_INTERNAL); - } /* End switch(ctype) */ - - else -#endif /* SUPPORT_UTF8 */ - - /* Code for the non-UTF-8 case for minimum matching of operators other - than OP_PROP and OP_NOTPROP. */ - - switch(ctype) - { - case OP_ANY: - if ((ims & PCRE_DOTALL) == 0) - { - for (i = 1; i <= min; i++) - if (*eptr++ == NEWLINE) RRETURN(MATCH_NOMATCH); - } - else eptr += min; - break; - - case OP_ANYBYTE: - eptr += min; - break; - - case OP_NOT_DIGIT: - for (i = 1; i <= min; i++) - if ((md->ctypes[*eptr++] & ctype_digit) != 0) RRETURN(MATCH_NOMATCH); - break; - - case OP_DIGIT: - for (i = 1; i <= min; i++) - if ((md->ctypes[*eptr++] & ctype_digit) == 0) RRETURN(MATCH_NOMATCH); - break; - - case OP_NOT_WHITESPACE: - for (i = 1; i <= min; i++) - if ((md->ctypes[*eptr++] & ctype_space) != 0) RRETURN(MATCH_NOMATCH); - break; - - case OP_WHITESPACE: - for (i = 1; i <= min; i++) - if ((md->ctypes[*eptr++] & ctype_space) == 0) RRETURN(MATCH_NOMATCH); - break; - - case OP_NOT_WORDCHAR: - for (i = 1; i <= min; i++) - if ((md->ctypes[*eptr++] & ctype_word) != 0) - RRETURN(MATCH_NOMATCH); - break; - - case OP_WORDCHAR: - for (i = 1; i <= min; i++) - if ((md->ctypes[*eptr++] & ctype_word) == 0) - RRETURN(MATCH_NOMATCH); - break; - - default: - RRETURN(PCRE_ERROR_INTERNAL); - } - } - - /* If min = max, continue at the same level without recursing */ - - if (min == max) continue; - - /* If minimizing, we have to test the rest of the pattern before each - subsequent match. Again, separate the UTF-8 case for speed, and also - separate the UCP cases. */ - - if (minimize) - { -#ifdef SUPPORT_UCP - if (prop_type > 0) - { - for (fi = min;; fi++) - { - RMATCH(rrc, eptr, ecode, offset_top, md, ims, eptrb, 0); - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - if (fi >= max || eptr >= md->end_subject) RRETURN(MATCH_NOMATCH); - GETCHARINC(c, eptr); - prop_category = ucp_findchar(c, &prop_chartype, &prop_othercase); - if ((*prop_test_variable == prop_test_against) == prop_fail_result) - RRETURN(MATCH_NOMATCH); - } - } - - /* Match extended Unicode sequences. We will get here only if the - support is in the binary; otherwise a compile-time error occurs. */ - - else if (ctype == OP_EXTUNI) - { - for (fi = min;; fi++) - { - RMATCH(rrc, eptr, ecode, offset_top, md, ims, eptrb, 0); - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - if (fi >= max || eptr >= md->end_subject) RRETURN(MATCH_NOMATCH); - GETCHARINCTEST(c, eptr); - prop_category = ucp_findchar(c, &prop_chartype, &prop_othercase); - if (prop_category == ucp_M) RRETURN(MATCH_NOMATCH); - while (eptr < md->end_subject) - { - int len = 1; - if (!md->utf8) c = *eptr; else - { - GETCHARLEN(c, eptr, len); - } - prop_category = ucp_findchar(c, &prop_chartype, &prop_othercase); - if (prop_category != ucp_M) break; - eptr += len; - } - } - } - - else -#endif /* SUPPORT_UCP */ - -#ifdef SUPPORT_UTF8 - /* UTF-8 mode */ - if (md->utf8) - { - for (fi = min;; fi++) - { - RMATCH(rrc, eptr, ecode, offset_top, md, ims, eptrb, 0); - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - if (fi >= max || eptr >= md->end_subject) RRETURN(MATCH_NOMATCH); - - GETCHARINC(c, eptr); - switch(ctype) - { - case OP_ANY: - if ((ims & PCRE_DOTALL) == 0 && c == NEWLINE) RRETURN(MATCH_NOMATCH); - break; - - case OP_ANYBYTE: - break; - - case OP_NOT_DIGIT: - if (c < 256 && (md->ctypes[c] & ctype_digit) != 0) - RRETURN(MATCH_NOMATCH); - break; - - case OP_DIGIT: - if (c >= 256 || (md->ctypes[c] & ctype_digit) == 0) - RRETURN(MATCH_NOMATCH); - break; - - case OP_NOT_WHITESPACE: - if (c < 256 && (md->ctypes[c] & ctype_space) != 0) - RRETURN(MATCH_NOMATCH); - break; - - case OP_WHITESPACE: - if (c >= 256 || (md->ctypes[c] & ctype_space) == 0) - RRETURN(MATCH_NOMATCH); - break; - - case OP_NOT_WORDCHAR: - if (c < 256 && (md->ctypes[c] & ctype_word) != 0) - RRETURN(MATCH_NOMATCH); - break; - - case OP_WORDCHAR: - if (c >= 256 && (md->ctypes[c] & ctype_word) == 0) - RRETURN(MATCH_NOMATCH); - break; - - default: - RRETURN(PCRE_ERROR_INTERNAL); - } - } - } - else -#endif - /* Not UTF-8 mode */ - { - for (fi = min;; fi++) - { - RMATCH(rrc, eptr, ecode, offset_top, md, ims, eptrb, 0); - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - if (fi >= max || eptr >= md->end_subject) RRETURN(MATCH_NOMATCH); - c = *eptr++; - switch(ctype) - { - case OP_ANY: - if ((ims & PCRE_DOTALL) == 0 && c == NEWLINE) RRETURN(MATCH_NOMATCH); - break; - - case OP_ANYBYTE: - break; - - case OP_NOT_DIGIT: - if ((md->ctypes[c] & ctype_digit) != 0) RRETURN(MATCH_NOMATCH); - break; - - case OP_DIGIT: - if ((md->ctypes[c] & ctype_digit) == 0) RRETURN(MATCH_NOMATCH); - break; - - case OP_NOT_WHITESPACE: - if ((md->ctypes[c] & ctype_space) != 0) RRETURN(MATCH_NOMATCH); - break; - - case OP_WHITESPACE: - if ((md->ctypes[c] & ctype_space) == 0) RRETURN(MATCH_NOMATCH); - break; - - case OP_NOT_WORDCHAR: - if ((md->ctypes[c] & ctype_word) != 0) RRETURN(MATCH_NOMATCH); - break; - - case OP_WORDCHAR: - if ((md->ctypes[c] & ctype_word) == 0) RRETURN(MATCH_NOMATCH); - break; - - default: - RRETURN(PCRE_ERROR_INTERNAL); - } - } - } - /* Control never gets here */ - } - - /* If maximizing it is worth using inline code for speed, doing the type - test once at the start (i.e. keep it out of the loop). Again, keep the - UTF-8 and UCP stuff separate. */ - - else - { - pp = eptr; /* Remember where we started */ - -#ifdef SUPPORT_UCP - if (prop_type > 0) - { - for (i = min; i < max; i++) - { - int len = 1; - if (eptr >= md->end_subject) break; - GETCHARLEN(c, eptr, len); - prop_category = ucp_findchar(c, &prop_chartype, &prop_othercase); - if ((*prop_test_variable == prop_test_against) == prop_fail_result) - break; - eptr+= len; - } - - /* eptr is now past the end of the maximum run */ - - for(;;) - { - RMATCH(rrc, eptr, ecode, offset_top, md, ims, eptrb, 0); - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - if (eptr-- == pp) break; /* Stop if tried at original pos */ - BACKCHAR(eptr); - } - } - - /* Match extended Unicode sequences. We will get here only if the - support is in the binary; otherwise a compile-time error occurs. */ - - else if (ctype == OP_EXTUNI) - { - for (i = min; i < max; i++) - { - if (eptr >= md->end_subject) break; - GETCHARINCTEST(c, eptr); - prop_category = ucp_findchar(c, &prop_chartype, &prop_othercase); - if (prop_category == ucp_M) break; - while (eptr < md->end_subject) - { - int len = 1; - if (!md->utf8) c = *eptr; else - { - GETCHARLEN(c, eptr, len); - } - prop_category = ucp_findchar(c, &prop_chartype, &prop_othercase); - if (prop_category != ucp_M) break; - eptr += len; - } - } - - /* eptr is now past the end of the maximum run */ - - for(;;) - { - RMATCH(rrc, eptr, ecode, offset_top, md, ims, eptrb, 0); - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - if (eptr-- == pp) break; /* Stop if tried at original pos */ - for (;;) /* Move back over one extended */ - { - int len = 1; - BACKCHAR(eptr); - if (!md->utf8) c = *eptr; else - { - GETCHARLEN(c, eptr, len); - } - prop_category = ucp_findchar(c, &prop_chartype, &prop_othercase); - if (prop_category != ucp_M) break; - eptr--; - } - } - } - - else -#endif /* SUPPORT_UCP */ - -#ifdef SUPPORT_UTF8 - /* UTF-8 mode */ - - if (md->utf8) - { - switch(ctype) - { - case OP_ANY: - - /* Special code is required for UTF8, but when the maximum is unlimited - we don't need it, so we repeat the non-UTF8 code. This is probably - worth it, because .* is quite a common idiom. */ - - if (max < INT_MAX) - { - if ((ims & PCRE_DOTALL) == 0) - { - for (i = min; i < max; i++) - { - if (eptr >= md->end_subject || *eptr == NEWLINE) break; - eptr++; - while (eptr < md->end_subject && (*eptr & 0xc0) == 0x80) eptr++; - } - } - else - { - for (i = min; i < max; i++) - { - eptr++; - while (eptr < md->end_subject && (*eptr & 0xc0) == 0x80) eptr++; - } - } - } - - /* Handle unlimited UTF-8 repeat */ - - else - { - if ((ims & PCRE_DOTALL) == 0) - { - for (i = min; i < max; i++) - { - if (eptr >= md->end_subject || *eptr == NEWLINE) break; - eptr++; - } - break; - } - else - { - c = max - min; - if (c > md->end_subject - eptr) c = md->end_subject - eptr; - eptr += c; - } - } - break; - - /* The byte case is the same as non-UTF8 */ - - case OP_ANYBYTE: - c = max - min; - if (c > md->end_subject - eptr) c = md->end_subject - eptr; - eptr += c; - break; - - case OP_NOT_DIGIT: - for (i = min; i < max; i++) - { - int len = 1; - if (eptr >= md->end_subject) break; - GETCHARLEN(c, eptr, len); - if (c < 256 && (md->ctypes[c] & ctype_digit) != 0) break; - eptr+= len; - } - break; - - case OP_DIGIT: - for (i = min; i < max; i++) - { - int len = 1; - if (eptr >= md->end_subject) break; - GETCHARLEN(c, eptr, len); - if (c >= 256 ||(md->ctypes[c] & ctype_digit) == 0) break; - eptr+= len; - } - break; - - case OP_NOT_WHITESPACE: - for (i = min; i < max; i++) - { - int len = 1; - if (eptr >= md->end_subject) break; - GETCHARLEN(c, eptr, len); - if (c < 256 && (md->ctypes[c] & ctype_space) != 0) break; - eptr+= len; - } - break; - - case OP_WHITESPACE: - for (i = min; i < max; i++) - { - int len = 1; - if (eptr >= md->end_subject) break; - GETCHARLEN(c, eptr, len); - if (c >= 256 ||(md->ctypes[c] & ctype_space) == 0) break; - eptr+= len; - } - break; - - case OP_NOT_WORDCHAR: - for (i = min; i < max; i++) - { - int len = 1; - if (eptr >= md->end_subject) break; - GETCHARLEN(c, eptr, len); - if (c < 256 && (md->ctypes[c] & ctype_word) != 0) break; - eptr+= len; - } - break; - - case OP_WORDCHAR: - for (i = min; i < max; i++) - { - int len = 1; - if (eptr >= md->end_subject) break; - GETCHARLEN(c, eptr, len); - if (c >= 256 || (md->ctypes[c] & ctype_word) == 0) break; - eptr+= len; - } - break; - - default: - RRETURN(PCRE_ERROR_INTERNAL); - } - - /* eptr is now past the end of the maximum run */ - - for(;;) - { - RMATCH(rrc, eptr, ecode, offset_top, md, ims, eptrb, 0); - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - if (eptr-- == pp) break; /* Stop if tried at original pos */ - BACKCHAR(eptr); - } - } - else -#endif - - /* Not UTF-8 mode */ - { - switch(ctype) - { - case OP_ANY: - if ((ims & PCRE_DOTALL) == 0) - { - for (i = min; i < max; i++) - { - if (eptr >= md->end_subject || *eptr == NEWLINE) break; - eptr++; - } - break; - } - /* For DOTALL case, fall through and treat as \C */ - - case OP_ANYBYTE: - c = max - min; - if (c > md->end_subject - eptr) c = md->end_subject - eptr; - eptr += c; - break; - - case OP_NOT_DIGIT: - for (i = min; i < max; i++) - { - if (eptr >= md->end_subject || (md->ctypes[*eptr] & ctype_digit) != 0) - break; - eptr++; - } - break; - - case OP_DIGIT: - for (i = min; i < max; i++) - { - if (eptr >= md->end_subject || (md->ctypes[*eptr] & ctype_digit) == 0) - break; - eptr++; - } - break; - - case OP_NOT_WHITESPACE: - for (i = min; i < max; i++) - { - if (eptr >= md->end_subject || (md->ctypes[*eptr] & ctype_space) != 0) - break; - eptr++; - } - break; - - case OP_WHITESPACE: - for (i = min; i < max; i++) - { - if (eptr >= md->end_subject || (md->ctypes[*eptr] & ctype_space) == 0) - break; - eptr++; - } - break; - - case OP_NOT_WORDCHAR: - for (i = min; i < max; i++) - { - if (eptr >= md->end_subject || (md->ctypes[*eptr] & ctype_word) != 0) - break; - eptr++; - } - break; - - case OP_WORDCHAR: - for (i = min; i < max; i++) - { - if (eptr >= md->end_subject || (md->ctypes[*eptr] & ctype_word) == 0) - break; - eptr++; - } - break; - - default: - RRETURN(PCRE_ERROR_INTERNAL); - } - - /* eptr is now past the end of the maximum run */ - - while (eptr >= pp) - { - RMATCH(rrc, eptr, ecode, offset_top, md, ims, eptrb, 0); - eptr--; - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - } - } - - /* Get here if we can't make it match with any permitted repetitions */ - - RRETURN(MATCH_NOMATCH); - } - /* Control never gets here */ - - /* There's been some horrible disaster. Since all codes > OP_BRA are - for capturing brackets, and there shouldn't be any gaps between 0 and - OP_BRA, arrival here can only mean there is something seriously wrong - in the code above or the OP_xxx definitions. */ - - default: - DPRINTF(("Unknown opcode %d\n", *ecode)); - RRETURN(PCRE_ERROR_UNKNOWN_NODE); - } - - /* Do not stick any code in here without much thought; it is assumed - that "continue" in the code above comes out to here to repeat the main - loop. */ - - } /* End of main loop */ -/* Control never reaches here */ -} - - -/*************************************************************************** -**************************************************************************** - RECURSION IN THE match() FUNCTION - -Undefine all the macros that were defined above to handle this. */ - -#ifdef NO_RECURSE -#undef eptr -#undef ecode -#undef offset_top -#undef ims -#undef eptrb -#undef flags - -#undef callpat -#undef charptr -#undef data -#undef next -#undef pp -#undef prev -#undef saved_eptr - -#undef new_recursive - -#undef cur_is_word -#undef condition -#undef minimize -#undef prev_is_word - -#undef original_ims - -#undef ctype -#undef length -#undef max -#undef min -#undef number -#undef offset -#undef op -#undef save_capture_last -#undef save_offset1 -#undef save_offset2 -#undef save_offset3 -#undef stacksave - -#undef newptrb - -#endif - -/* These two are defined as macros in both cases */ - -#undef fc -#undef fi - -/*************************************************************************** -***************************************************************************/ - - - -/************************************************* -* Execute a Regular Expression * -*************************************************/ - -/* This function applies a compiled re to a subject string and picks out -portions of the string if it matches. Two elements in the vector are set for -each substring: the offsets to the start and end of the substring. - -Arguments: - argument_re points to the compiled expression - extra_data points to extra data or is NULL - subject points to the subject string - length length of subject string (may contain binary zeros) - start_offset where to start in the subject string - options option bits - offsets points to a vector of ints to be filled in with offsets - offsetcount the number of elements in the vector - -Returns: > 0 => success; value is the number of elements filled in - = 0 => success, but offsets is not big enough - -1 => failed to match - < -1 => some kind of unexpected problem -*/ - -EXPORT int -pcre_exec(const pcre *argument_re, const pcre_extra *extra_data, - const char *subject, int length, int start_offset, int options, int *offsets, - int offsetcount) -{ -int rc, resetcount, ocount; -int first_byte = -1; -int req_byte = -1; -int req_byte2 = -1; -unsigned long int ims = 0; -BOOL using_temporary_offsets = FALSE; -BOOL anchored; -BOOL startline; -BOOL first_byte_caseless = FALSE; -BOOL req_byte_caseless = FALSE; -match_data match_block; -const uschar *tables; -const uschar *start_bits = NULL; -const uschar *start_match = (const uschar *)subject + start_offset; -const uschar *end_subject; -const uschar *req_byte_ptr = start_match - 1; - -pcre_study_data internal_study; -const pcre_study_data *study; - -real_pcre internal_re; -const real_pcre *external_re = (const real_pcre *)argument_re; -const real_pcre *re = external_re; - -/* Plausibility checks */ - -if ((options & ~PUBLIC_EXEC_OPTIONS) != 0) return PCRE_ERROR_BADOPTION; -if (re == NULL || subject == NULL || - (offsets == NULL && offsetcount > 0)) return PCRE_ERROR_NULL; -if (offsetcount < 0) return PCRE_ERROR_BADCOUNT; - -/* Fish out the optional data from the extra_data structure, first setting -the default values. */ - -study = NULL; -match_block.match_limit = MATCH_LIMIT; -match_block.callout_data = NULL; - -/* The table pointer is always in native byte order. */ - -tables = external_re->tables; - -if (extra_data != NULL) - { - register unsigned int flags = extra_data->flags; - if ((flags & PCRE_EXTRA_STUDY_DATA) != 0) - study = (const pcre_study_data *)extra_data->study_data; - if ((flags & PCRE_EXTRA_MATCH_LIMIT) != 0) - match_block.match_limit = extra_data->match_limit; - if ((flags & PCRE_EXTRA_CALLOUT_DATA) != 0) - match_block.callout_data = extra_data->callout_data; - if ((flags & PCRE_EXTRA_TABLES) != 0) tables = extra_data->tables; - } - -/* If the exec call supplied NULL for tables, use the inbuilt ones. This -is a feature that makes it possible to save compiled regex and re-use them -in other programs later. */ - -if (tables == NULL) tables = pcre_default_tables; - -/* Check that the first field in the block is the magic number. If it is not, -test for a regex that was compiled on a host of opposite endianness. If this is -the case, flipped values are put in internal_re and internal_study if there was -study data too. */ - -if (re->magic_number != MAGIC_NUMBER) - { - re = try_flipped(re, &internal_re, study, &internal_study); - if (re == NULL) return PCRE_ERROR_BADMAGIC; - if (study != NULL) study = &internal_study; - } - -/* Set up other data */ - -anchored = ((re->options | options) & PCRE_ANCHORED) != 0; -startline = (re->options & PCRE_STARTLINE) != 0; - -/* The code starts after the real_pcre block and the capture name table. */ - -match_block.start_code = (const uschar *)external_re + re->name_table_offset + - re->name_count * re->name_entry_size; - -match_block.start_subject = (const uschar *)subject; -match_block.start_offset = start_offset; -match_block.end_subject = match_block.start_subject + length; -end_subject = match_block.end_subject; - -match_block.endonly = (re->options & PCRE_DOLLAR_ENDONLY) != 0; -match_block.utf8 = (re->options & PCRE_UTF8) != 0; - -match_block.notbol = (options & PCRE_NOTBOL) != 0; -match_block.noteol = (options & PCRE_NOTEOL) != 0; -match_block.notempty = (options & PCRE_NOTEMPTY) != 0; -match_block.partial = (options & PCRE_PARTIAL) != 0; -match_block.hitend = FALSE; - -match_block.recursive = NULL; /* No recursion at top level */ - -match_block.lcc = tables + lcc_offset; -match_block.ctypes = tables + ctypes_offset; - -/* Partial matching is supported only for a restricted set of regexes at the -moment. */ - -if (match_block.partial && (re->options & PCRE_NOPARTIAL) != 0) - return PCRE_ERROR_BADPARTIAL; - -/* Check a UTF-8 string if required. Unfortunately there's no way of passing -back the character offset. */ - -#ifdef SUPPORT_UTF8 -if (match_block.utf8 && (options & PCRE_NO_UTF8_CHECK) == 0) - { - if (valid_utf8((uschar *)subject, length) >= 0) - return PCRE_ERROR_BADUTF8; - if (start_offset > 0 && start_offset < length) - { - int tb = ((uschar *)subject)[start_offset]; - if (tb > 127) - { - tb &= 0xc0; - if (tb != 0 && tb != 0xc0) return PCRE_ERROR_BADUTF8_OFFSET; - } - } - } -#endif - -/* The ims options can vary during the matching as a result of the presence -of (?ims) items in the pattern. They are kept in a local variable so that -restoring at the exit of a group is easy. */ - -ims = re->options & (PCRE_CASELESS|PCRE_MULTILINE|PCRE_DOTALL); - -/* If the expression has got more back references than the offsets supplied can -hold, we get a temporary chunk of working store to use during the matching. -Otherwise, we can use the vector supplied, rounding down its size to a multiple -of 3. */ - -ocount = offsetcount - (offsetcount % 3); - -if (re->top_backref > 0 && re->top_backref >= ocount/3) - { - ocount = re->top_backref * 3 + 3; - match_block.offset_vector = (int *)(pcre_malloc)(ocount * sizeof(int)); - if (match_block.offset_vector == NULL) return PCRE_ERROR_NOMEMORY; - using_temporary_offsets = TRUE; - DPRINTF(("Got memory to hold back references\n")); - } -else match_block.offset_vector = offsets; - -match_block.offset_end = ocount; -match_block.offset_max = (2*ocount)/3; -match_block.offset_overflow = FALSE; -match_block.capture_last = -1; - -/* Compute the minimum number of offsets that we need to reset each time. Doing -this makes a huge difference to execution time when there aren't many brackets -in the pattern. */ - -resetcount = 2 + re->top_bracket * 2; -if (resetcount > offsetcount) resetcount = ocount; - -/* Reset the working variable associated with each extraction. These should -never be used unless previously set, but they get saved and restored, and so we -initialize them to avoid reading uninitialized locations. */ - -if (match_block.offset_vector != NULL) - { - register int *iptr = match_block.offset_vector + ocount; - register int *iend = iptr - resetcount/2 + 1; - while (--iptr >= iend) *iptr = -1; - } - -/* Set up the first character to match, if available. The first_byte value is -never set for an anchored regular expression, but the anchoring may be forced -at run time, so we have to test for anchoring. The first char may be unset for -an unanchored pattern, of course. If there's no first char and the pattern was -studied, there may be a bitmap of possible first characters. */ - -if (!anchored) - { - if ((re->options & PCRE_FIRSTSET) != 0) - { - first_byte = re->first_byte & 255; - if ((first_byte_caseless = ((re->first_byte & REQ_CASELESS) != 0)) == TRUE) - first_byte = match_block.lcc[first_byte]; - } - else - if (!startline && study != NULL && - (study->options & PCRE_STUDY_MAPPED) != 0) - start_bits = study->start_bits; - } - -/* For anchored or unanchored matches, there may be a "last known required -character" set. */ - -if ((re->options & PCRE_REQCHSET) != 0) - { - req_byte = re->req_byte & 255; - req_byte_caseless = (re->req_byte & REQ_CASELESS) != 0; - req_byte2 = (tables + fcc_offset)[req_byte]; /* case flipped */ - } - -/* Loop for handling unanchored repeated matching attempts; for anchored regexs -the loop runs just once. */ - -do - { - /* Reset the maximum number of extractions we might see. */ - - if (match_block.offset_vector != NULL) - { - register int *iptr = match_block.offset_vector; - register int *iend = iptr + resetcount; - while (iptr < iend) *iptr++ = -1; - } - - /* Advance to a unique first char if possible */ - - if (first_byte >= 0) - { - if (first_byte_caseless) - while (start_match < end_subject && - match_block.lcc[*start_match] != first_byte) - start_match++; - else - while (start_match < end_subject && *start_match != first_byte) - start_match++; - } - - /* Or to just after \n for a multiline match if possible */ - - else if (startline) - { - if (start_match > match_block.start_subject + start_offset) - { - while (start_match < end_subject && start_match[-1] != NEWLINE) - start_match++; - } - } - - /* Or to a non-unique first char after study */ - - else if (start_bits != NULL) - { - while (start_match < end_subject) - { - register unsigned int c = *start_match; - if ((start_bits[c/8] & (1 << (c&7))) == 0) start_match++; else break; - } - } - -#ifdef DEBUG /* Sigh. Some compilers never learn. */ - printf(">>>> Match against: "); - pchars(start_match, end_subject - start_match, TRUE, &match_block); - printf("\n"); -#endif - - /* If req_byte is set, we know that that character must appear in the subject - for the match to succeed. If the first character is set, req_byte must be - later in the subject; otherwise the test starts at the match point. This - optimization can save a huge amount of backtracking in patterns with nested - unlimited repeats that aren't going to match. Writing separate code for - cased/caseless versions makes it go faster, as does using an autoincrement - and backing off on a match. - - HOWEVER: when the subject string is very, very long, searching to its end can - take a long time, and give bad performance on quite ordinary patterns. This - showed up when somebody was matching /^C/ on a 32-megabyte string... so we - don't do this when the string is sufficiently long. - - ALSO: this processing is disabled when partial matching is requested. - */ - - if (req_byte >= 0 && - end_subject - start_match < REQ_BYTE_MAX && - !match_block.partial) - { - register const uschar *p = start_match + ((first_byte >= 0)? 1 : 0); - - /* We don't need to repeat the search if we haven't yet reached the - place we found it at last time. */ - - if (p > req_byte_ptr) - { - if (req_byte_caseless) - { - while (p < end_subject) - { - register int pp = *p++; - if (pp == req_byte || pp == req_byte2) { p--; break; } - } - } - else - { - while (p < end_subject) - { - if (*p++ == req_byte) { p--; break; } - } - } - - /* If we can't find the required character, break the matching loop */ - - if (p >= end_subject) break; - - /* If we have found the required character, save the point where we - found it, so that we don't search again next time round the loop if - the start hasn't passed this character yet. */ - - req_byte_ptr = p; - } - } - - /* When a match occurs, substrings will be set for all internal extractions; - we just need to set up the whole thing as substring 0 before returning. If - there were too many extractions, set the return code to zero. In the case - where we had to get some local store to hold offsets for backreferences, copy - those back references that we can. In this case there need not be overflow - if certain parts of the pattern were not used. */ - - match_block.start_match = start_match; - match_block.match_call_count = 0; - - rc = match(start_match, match_block.start_code, 2, &match_block, ims, NULL, - match_isgroup); - - if (rc == MATCH_NOMATCH) - { - start_match++; -#ifdef SUPPORT_UTF8 - if (match_block.utf8) - while(start_match < end_subject && (*start_match & 0xc0) == 0x80) - start_match++; -#endif - continue; - } - - if (rc != MATCH_MATCH) - { - DPRINTF((">>>> error: returning %d\n", rc)); - return rc; - } - - /* We have a match! Copy the offset information from temporary store if - necessary */ - - if (using_temporary_offsets) - { - if (offsetcount >= 4) - { - memcpy(offsets + 2, match_block.offset_vector + 2, - (offsetcount - 2) * sizeof(int)); - DPRINTF(("Copied offsets from temporary memory\n")); - } - if (match_block.end_offset_top > offsetcount) - match_block.offset_overflow = TRUE; - - DPRINTF(("Freeing temporary memory\n")); - (pcre_free)(match_block.offset_vector); - } - - rc = match_block.offset_overflow? 0 : match_block.end_offset_top/2; - - if (offsetcount < 2) rc = 0; else - { - offsets[0] = start_match - match_block.start_subject; - offsets[1] = match_block.end_match_ptr - match_block.start_subject; - } - - DPRINTF((">>>> returning %d\n", rc)); - return rc; - } - -/* This "while" is the end of the "do" above */ - -while (!anchored && start_match <= end_subject); - -if (using_temporary_offsets) - { - DPRINTF(("Freeing temporary memory\n")); - (pcre_free)(match_block.offset_vector); - } - -if (match_block.partial && match_block.hitend) - { - DPRINTF((">>>> returning PCRE_ERROR_PARTIAL\n")); - return PCRE_ERROR_PARTIAL; - } -else - { - DPRINTF((">>>> returning PCRE_ERROR_NOMATCH\n")); - return PCRE_ERROR_NOMATCH; - } -} - -/* End of pcre.c */ +/************************************************* +* Perl-Compatible Regular Expressions * +*************************************************/ + +/* +This is a library of functions to support regular expressions whose syntax +and semantics are as close as possible to those of the Perl 5 language. See +the file Tech.Notes for some information on the internals. + +Written by: Philip Hazel + + Copyright (c) 1997-2004 University of Cambridge + +----------------------------------------------------------------------------- +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + * 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. + + * Neither the name of the University of Cambridge nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +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. +----------------------------------------------------------------------------- +*/ + + +/* Define DEBUG to get debugging output on stdout. */ +/* #define DEBUG */ + +/* Use a macro for debugging printing, 'cause that eliminates the use of #ifdef +inline, and there are *still* stupid compilers about that don't like indented +pre-processor statements. I suppose it's only been 10 years... */ + +#ifdef DEBUG +#define DPRINTF(p) printf p +#else +#define DPRINTF(p) /*nothing*/ +#endif + +/* Include the internals header, which itself includes "config.h", the Standard +C headers, and the external pcre header. */ + +#include "pcreinternal.h" + +/* If Unicode Property support is wanted, include a private copy of the +function that does it, and the table that translates names to numbers. */ + +#ifdef SUPPORT_UCP +#include "ucp.c" +#include "ucptypetable.c" +#endif + +/* Maximum number of items on the nested bracket stacks at compile time. This +applies to the nesting of all kinds of parentheses. It does not limit +un-nested, non-capturing parentheses. This number can be made bigger if +necessary - it is used to dimension one int and one unsigned char vector at +compile time. */ + +#define BRASTACK_SIZE 200 + + +/* Maximum number of ints of offset to save on the stack for recursive calls. +If the offset vector is bigger, malloc is used. This should be a multiple of 3, +because the offset vector is always a multiple of 3 long. */ + +#define REC_STACK_SAVE_MAX 30 + + +/* The maximum remaining length of subject we are prepared to search for a +req_byte match. */ + +#define REQ_BYTE_MAX 1000 + + +/* Table of sizes for the fixed-length opcodes. It's defined in a macro so that +the definition is next to the definition of the opcodes in internal.h. */ + +static const uschar OP_lengths[] = { OP_LENGTHS }; + +/* Min and max values for the common repeats; for the maxima, 0 => infinity */ + +static const char rep_min[] = { 0, 0, 1, 1, 0, 0 }; +static const char rep_max[] = { 0, 0, 0, 0, 1, 1 }; + +/* Table for handling escaped characters in the range '0'-'z'. Positive returns +are simple data values; negative values are for special things like \d and so +on. Zero means further processing is needed (for things like \x), or the escape +is invalid. */ + +#if !EBCDIC /* This is the "normal" table for ASCII systems */ +static const short int escapes[] = { + 0, 0, 0, 0, 0, 0, 0, 0, /* 0 - 7 */ + 0, 0, ':', ';', '<', '=', '>', '?', /* 8 - ? */ + '@', -ESC_A, -ESC_B, -ESC_C, -ESC_D, -ESC_E, 0, -ESC_G, /* @ - G */ + 0, 0, 0, 0, 0, 0, 0, 0, /* H - O */ +-ESC_P, -ESC_Q, 0, -ESC_S, 0, 0, 0, -ESC_W, /* P - W */ +-ESC_X, 0, -ESC_Z, '[', '\\', ']', '^', '_', /* X - _ */ + '`', 7, -ESC_b, 0, -ESC_d, ESC_e, ESC_f, 0, /* ` - g */ + 0, 0, 0, 0, 0, 0, ESC_n, 0, /* h - o */ +-ESC_p, 0, ESC_r, -ESC_s, ESC_tee, 0, 0, -ESC_w, /* p - w */ + 0, 0, -ESC_z /* x - z */ +}; + +#else /* This is the "abnormal" table for EBCDIC systems */ +static const short int escapes[] = { +/* 48 */ 0, 0, 0, '.', '<', '(', '+', '|', +/* 50 */ '&', 0, 0, 0, 0, 0, 0, 0, +/* 58 */ 0, 0, '!', '$', '*', ')', ';', '~', +/* 60 */ '-', '/', 0, 0, 0, 0, 0, 0, +/* 68 */ 0, 0, '|', ',', '%', '_', '>', '?', +/* 70 */ 0, 0, 0, 0, 0, 0, 0, 0, +/* 78 */ 0, '`', ':', '#', '@', '\'', '=', '"', +/* 80 */ 0, 7, -ESC_b, 0, -ESC_d, ESC_e, ESC_f, 0, +/* 88 */ 0, 0, 0, '{', 0, 0, 0, 0, +/* 90 */ 0, 0, 0, 'l', 0, ESC_n, 0, -ESC_p, +/* 98 */ 0, ESC_r, 0, '}', 0, 0, 0, 0, +/* A0 */ 0, '~', -ESC_s, ESC_tee, 0, 0, -ESC_w, 0, +/* A8 */ 0,-ESC_z, 0, 0, 0, '[', 0, 0, +/* B0 */ 0, 0, 0, 0, 0, 0, 0, 0, +/* B8 */ 0, 0, 0, 0, 0, ']', '=', '-', +/* C0 */ '{',-ESC_A, -ESC_B, -ESC_C, -ESC_D,-ESC_E, 0, -ESC_G, +/* C8 */ 0, 0, 0, 0, 0, 0, 0, 0, +/* D0 */ '}', 0, 0, 0, 0, 0, 0, -ESC_P, +/* D8 */-ESC_Q, 0, 0, 0, 0, 0, 0, 0, +/* E0 */ '\\', 0, -ESC_S, 0, 0, 0, -ESC_W, -ESC_X, +/* E8 */ 0,-ESC_Z, 0, 0, 0, 0, 0, 0, +/* F0 */ 0, 0, 0, 0, 0, 0, 0, 0, +/* F8 */ 0, 0, 0, 0, 0, 0, 0, 0 +}; +#endif + + +/* Tables of names of POSIX character classes and their lengths. The list is +terminated by a zero length entry. The first three must be alpha, upper, lower, +as this is assumed for handling case independence. */ + +static const char *const posix_names[] = { + "alpha", "lower", "upper", + "alnum", "ascii", "blank", "cntrl", "digit", "graph", + "print", "punct", "space", "word", "xdigit" }; + +static const uschar posix_name_lengths[] = { + 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 4, 6, 0 }; + +/* Table of class bit maps for each POSIX class; up to three may be combined +to form the class. The table for [:blank:] is dynamically modified to remove +the vertical space characters. */ + +static const int posix_class_maps[] = { + cbit_lower, cbit_upper, -1, /* alpha */ + cbit_lower, -1, -1, /* lower */ + cbit_upper, -1, -1, /* upper */ + cbit_digit, cbit_lower, cbit_upper, /* alnum */ + cbit_print, cbit_cntrl, -1, /* ascii */ + cbit_space, -1, -1, /* blank - a GNU extension */ + cbit_cntrl, -1, -1, /* cntrl */ + cbit_digit, -1, -1, /* digit */ + cbit_graph, -1, -1, /* graph */ + cbit_print, -1, -1, /* print */ + cbit_punct, -1, -1, /* punct */ + cbit_space, -1, -1, /* space */ + cbit_word, -1, -1, /* word - a Perl extension */ + cbit_xdigit,-1, -1 /* xdigit */ +}; + +/* Table to identify digits and hex digits. This is used when compiling +patterns. Note that the tables in chartables are dependent on the locale, and +may mark arbitrary characters as digits - but the PCRE compiling code expects +to handle only 0-9, a-z, and A-Z as digits when compiling. That is why we have +a private table here. It costs 256 bytes, but it is a lot faster than doing +character value tests (at least in some simple cases I timed), and in some +applications one wants PCRE to compile efficiently as well as match +efficiently. + +For convenience, we use the same bit definitions as in chartables: + + 0x04 decimal digit + 0x08 hexadecimal digit + +Then we can use ctype_digit and ctype_xdigit in the code. */ + +#if !EBCDIC /* This is the "normal" case, for ASCII systems */ +static const unsigned char digitab[] = + { + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 0- 7 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 8- 15 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 16- 23 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 24- 31 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* - ' */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* ( - / */ + 0x0c,0x0c,0x0c,0x0c,0x0c,0x0c,0x0c,0x0c, /* 0 - 7 */ + 0x0c,0x0c,0x00,0x00,0x00,0x00,0x00,0x00, /* 8 - ? */ + 0x00,0x08,0x08,0x08,0x08,0x08,0x08,0x00, /* @ - G */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* H - O */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* P - W */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* X - _ */ + 0x00,0x08,0x08,0x08,0x08,0x08,0x08,0x00, /* ` - g */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* h - o */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* p - w */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* x -127 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 128-135 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 136-143 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 144-151 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 152-159 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 160-167 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 168-175 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 176-183 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 184-191 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 192-199 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 200-207 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 208-215 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 216-223 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 224-231 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 232-239 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 240-247 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};/* 248-255 */ + +#else /* This is the "abnormal" case, for EBCDIC systems */ +static const unsigned char digitab[] = + { + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 0- 7 0 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 8- 15 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 16- 23 10 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 24- 31 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 32- 39 20 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 40- 47 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 48- 55 30 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 56- 63 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* - 71 40 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 72- | */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* & - 87 50 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 88- ¬ */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* - -103 60 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 104- ? */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 112-119 70 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 120- " */ + 0x00,0x08,0x08,0x08,0x08,0x08,0x08,0x00, /* 128- g 80 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* h -143 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 144- p 90 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* q -159 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 160- x A0 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* y -175 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* ^ -183 B0 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 184-191 */ + 0x00,0x08,0x08,0x08,0x08,0x08,0x08,0x00, /* { - G C0 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* H -207 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* } - P D0 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* Q -223 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* \ - X E0 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* Y -239 */ + 0x0c,0x0c,0x0c,0x0c,0x0c,0x0c,0x0c,0x0c, /* 0 - 7 F0 */ + 0x0c,0x0c,0x00,0x00,0x00,0x00,0x00,0x00};/* 8 -255 */ + +static const unsigned char ebcdic_chartab[] = { /* chartable partial dup */ + 0x80,0x00,0x00,0x00,0x00,0x01,0x00,0x00, /* 0- 7 */ + 0x00,0x00,0x00,0x00,0x01,0x01,0x00,0x00, /* 8- 15 */ + 0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00, /* 16- 23 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 24- 31 */ + 0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00, /* 32- 39 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 40- 47 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 48- 55 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 56- 63 */ + 0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* - 71 */ + 0x00,0x00,0x00,0x80,0x00,0x80,0x80,0x80, /* 72- | */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* & - 87 */ + 0x00,0x00,0x00,0x80,0x80,0x80,0x00,0x00, /* 88- ¬ */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* - -103 */ + 0x00,0x00,0x00,0x00,0x00,0x10,0x00,0x80, /* 104- ? */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 112-119 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 120- " */ + 0x00,0x1a,0x1a,0x1a,0x1a,0x1a,0x1a,0x12, /* 128- g */ + 0x12,0x12,0x00,0x00,0x00,0x00,0x00,0x00, /* h -143 */ + 0x00,0x12,0x12,0x12,0x12,0x12,0x12,0x12, /* 144- p */ + 0x12,0x12,0x00,0x00,0x00,0x00,0x00,0x00, /* q -159 */ + 0x00,0x00,0x12,0x12,0x12,0x12,0x12,0x12, /* 160- x */ + 0x12,0x12,0x00,0x00,0x00,0x00,0x00,0x00, /* y -175 */ + 0x80,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* ^ -183 */ + 0x00,0x00,0x80,0x00,0x00,0x00,0x00,0x00, /* 184-191 */ + 0x80,0x1a,0x1a,0x1a,0x1a,0x1a,0x1a,0x12, /* { - G */ + 0x12,0x12,0x00,0x00,0x00,0x00,0x00,0x00, /* H -207 */ + 0x00,0x12,0x12,0x12,0x12,0x12,0x12,0x12, /* } - P */ + 0x12,0x12,0x00,0x00,0x00,0x00,0x00,0x00, /* Q -223 */ + 0x00,0x00,0x12,0x12,0x12,0x12,0x12,0x12, /* \ - X */ + 0x12,0x12,0x00,0x00,0x00,0x00,0x00,0x00, /* Y -239 */ + 0x1c,0x1c,0x1c,0x1c,0x1c,0x1c,0x1c,0x1c, /* 0 - 7 */ + 0x1c,0x1c,0x00,0x00,0x00,0x00,0x00,0x00};/* 8 -255 */ +#endif + + +/* Definition to allow mutual recursion */ + +static BOOL + compile_regex(int, int, int *, uschar **, const uschar **, const char **, + BOOL, int, int *, int *, branch_chain *, compile_data *); + +/* Structure for building a chain of data that actually lives on the +stack, for holding the values of the subject pointer at the start of each +subpattern, so as to detect when an empty string has been matched by a +subpattern - to break infinite loops. When NO_RECURSE is set, these blocks +are on the heap, not on the stack. */ + +typedef struct eptrblock { + struct eptrblock *epb_prev; + const uschar *epb_saved_eptr; +} eptrblock; + +/* Flag bits for the match() function */ + +#define match_condassert 0x01 /* Called to check a condition assertion */ +#define match_isgroup 0x02 /* Set if start of bracketed group */ + +/* Non-error returns from the match() function. Error returns are externally +defined PCRE_ERROR_xxx codes, which are all negative. */ + +#define MATCH_MATCH 1 +#define MATCH_NOMATCH 0 + + + +/************************************************* +* Global variables * +*************************************************/ + +/* PCRE is thread-clean and doesn't use any global variables in the normal +sense. However, it calls memory allocation and free functions via the four +indirections below, and it can optionally do callouts. These values can be +changed by the caller, but are shared between all threads. However, when +compiling for Virtual Pascal, things are done differently (see pcre.in). */ + +#ifndef VPCOMPAT +#ifdef __cplusplus +extern "C" void *(*pcre_malloc)(size_t) = malloc; +extern "C" void (*pcre_free)(void *) = free; +extern "C" void *(*pcre_stack_malloc)(size_t) = malloc; +extern "C" void (*pcre_stack_free)(void *) = free; +extern "C" int (*pcre_callout)(pcre_callout_block *) = NULL; +#else +void *(*pcre_malloc)(size_t) = malloc; +void (*pcre_free)(void *) = free; +void *(*pcre_stack_malloc)(size_t) = malloc; +void (*pcre_stack_free)(void *) = free; +int (*pcre_callout)(pcre_callout_block *) = NULL; +#endif +#endif + + +/************************************************* +* Macros and tables for character handling * +*************************************************/ + +/* When UTF-8 encoding is being used, a character is no longer just a single +byte. The macros for character handling generate simple sequences when used in +byte-mode, and more complicated ones for UTF-8 characters. */ + +#ifndef SUPPORT_UTF8 +#define GETCHAR(c, eptr) c = *eptr; +#define GETCHARINC(c, eptr) c = *eptr++; +#define GETCHARINCTEST(c, eptr) c = *eptr++; +#define GETCHARLEN(c, eptr, len) c = *eptr; +#define BACKCHAR(eptr) + +#else /* SUPPORT_UTF8 */ + +/* Get the next UTF-8 character, not advancing the pointer. This is called when +we know we are in UTF-8 mode. */ + +#define GETCHAR(c, eptr) \ + c = *eptr; \ + if ((c & 0xc0) == 0xc0) \ + { \ + int gcii; \ + int gcaa = utf8_table4[c & 0x3f]; /* Number of additional bytes */ \ + int gcss = 6*gcaa; \ + c = (c & utf8_table3[gcaa]) << gcss; \ + for (gcii = 1; gcii <= gcaa; gcii++) \ + { \ + gcss -= 6; \ + c |= (eptr[gcii] & 0x3f) << gcss; \ + } \ + } + +/* Get the next UTF-8 character, advancing the pointer. This is called when we +know we are in UTF-8 mode. */ + +#define GETCHARINC(c, eptr) \ + c = *eptr++; \ + if ((c & 0xc0) == 0xc0) \ + { \ + int gcaa = utf8_table4[c & 0x3f]; /* Number of additional bytes */ \ + int gcss = 6*gcaa; \ + c = (c & utf8_table3[gcaa]) << gcss; \ + while (gcaa-- > 0) \ + { \ + gcss -= 6; \ + c |= (*eptr++ & 0x3f) << gcss; \ + } \ + } + +/* Get the next character, testing for UTF-8 mode, and advancing the pointer */ + +#define GETCHARINCTEST(c, eptr) \ + c = *eptr++; \ + if (md->utf8 && (c & 0xc0) == 0xc0) \ + { \ + int gcaa = utf8_table4[c & 0x3f]; /* Number of additional bytes */ \ + int gcss = 6*gcaa; \ + c = (c & utf8_table3[gcaa]) << gcss; \ + while (gcaa-- > 0) \ + { \ + gcss -= 6; \ + c |= (*eptr++ & 0x3f) << gcss; \ + } \ + } + +/* Get the next UTF-8 character, not advancing the pointer, incrementing length +if there are extra bytes. This is called when we know we are in UTF-8 mode. */ + +#define GETCHARLEN(c, eptr, len) \ + c = *eptr; \ + if ((c & 0xc0) == 0xc0) \ + { \ + int gcii; \ + int gcaa = utf8_table4[c & 0x3f]; /* Number of additional bytes */ \ + int gcss = 6*gcaa; \ + c = (c & utf8_table3[gcaa]) << gcss; \ + for (gcii = 1; gcii <= gcaa; gcii++) \ + { \ + gcss -= 6; \ + c |= (eptr[gcii] & 0x3f) << gcss; \ + } \ + len += gcaa; \ + } + +/* If the pointer is not at the start of a character, move it back until +it is. Called only in UTF-8 mode. */ + +#define BACKCHAR(eptr) while((*eptr & 0xc0) == 0x80) eptr--; + +#endif + + + +/************************************************* +* Default character tables * +*************************************************/ + +/* A default set of character tables is included in the PCRE binary. Its source +is built by the maketables auxiliary program, which uses the default C ctypes +functions, and put in the file chartables.c. These tables are used by PCRE +whenever the caller of pcre_compile() does not provide an alternate set of +tables. */ + +#include "chartables.c" + + + +#ifdef SUPPORT_UTF8 +/************************************************* +* Tables for UTF-8 support * +*************************************************/ + +/* These are the breakpoints for different numbers of bytes in a UTF-8 +character. */ + +static const int utf8_table1[] = + { 0x7f, 0x7ff, 0xffff, 0x1fffff, 0x3ffffff, 0x7fffffff}; + +/* These are the indicator bits and the mask for the data bits to set in the +first byte of a character, indexed by the number of additional bytes. */ + +static const int utf8_table2[] = { 0, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc}; +static const int utf8_table3[] = { 0xff, 0x1f, 0x0f, 0x07, 0x03, 0x01}; + +/* Table of the number of extra characters, indexed by the first character +masked with 0x3f. The highest number for a valid UTF-8 character is in fact +0x3d. */ + +static const uschar utf8_table4[] = { + 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, + 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, + 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, + 3,3,3,3,3,3,3,3,4,4,4,4,5,5,5,5 }; + + +/************************************************* +* Convert character value to UTF-8 * +*************************************************/ + +/* This function takes an integer value in the range 0 - 0x7fffffff +and encodes it as a UTF-8 character in 0 to 6 bytes. + +Arguments: + cvalue the character value + buffer pointer to buffer for result - at least 6 bytes long + +Returns: number of characters placed in the buffer +*/ + +static int +ord2utf8(int cvalue, uschar *buffer) +{ +register int i, j; +for (i = 0; i < sizeof(utf8_table1)/sizeof(int); i++) + if (cvalue <= utf8_table1[i]) break; +buffer += i; +for (j = i; j > 0; j--) + { + *buffer-- = 0x80 | (cvalue & 0x3f); + cvalue >>= 6; + } +*buffer = utf8_table2[i] | cvalue; +return i + 1; +} +#endif + + + +/************************************************* +* Print compiled regex * +*************************************************/ + +/* The code for doing this is held in a separate file that is also included in +pcretest.c. It defines a function called print_internals(). */ + +#ifdef DEBUG +#include "printint.c" +#endif + + + +/************************************************* +* Return version string * +*************************************************/ + +#define STRING(a) # a +#define XSTRING(s) STRING(s) + +EXPORT const char * +pcre_version(void) +{ +return XSTRING(PCRE_MAJOR) "." XSTRING(PCRE_MINOR) " " XSTRING(PCRE_DATE); +} + + + + +/************************************************* +* Flip bytes in an integer * +*************************************************/ + +/* This function is called when the magic number in a regex doesn't match in +order to flip its bytes to see if we are dealing with a pattern that was +compiled on a host of different endianness. If so, this function is used to +flip other byte values. + +Arguments: + value the number to flip + n the number of bytes to flip (assumed to be 2 or 4) + +Returns: the flipped value +*/ + +static long int +byteflip(long int value, int n) +{ +if (n == 2) return ((value & 0x00ff) << 8) | ((value & 0xff00) >> 8); +return ((value & 0x000000ff) << 24) | + ((value & 0x0000ff00) << 8) | + ((value & 0x00ff0000) >> 8) | + ((value & 0xff000000) >> 24); +} + + + +/************************************************* +* Test for a byte-flipped compiled regex * +*************************************************/ + +/* This function is called from pce_exec() and also from pcre_fullinfo(). Its +job is to test whether the regex is byte-flipped - that is, it was compiled on +a system of opposite endianness. The function is called only when the native +MAGIC_NUMBER test fails. If the regex is indeed flipped, we flip all the +relevant values into a different data block, and return it. + +Arguments: + re points to the regex + study points to study data, or NULL + internal_re points to a new regex block + internal_study points to a new study block + +Returns: the new block if is is indeed a byte-flipped regex + NULL if it is not +*/ + +static real_pcre * +try_flipped(const real_pcre *re, real_pcre *internal_re, + const pcre_study_data *study, pcre_study_data *internal_study) +{ +if (byteflip(re->magic_number, sizeof(re->magic_number)) != MAGIC_NUMBER) + return NULL; + +*internal_re = *re; /* To copy other fields */ +internal_re->size = byteflip(re->size, sizeof(re->size)); +internal_re->options = byteflip(re->options, sizeof(re->options)); +internal_re->top_bracket = byteflip(re->top_bracket, sizeof(re->top_bracket)); +internal_re->top_backref = byteflip(re->top_backref, sizeof(re->top_backref)); +internal_re->first_byte = byteflip(re->first_byte, sizeof(re->first_byte)); +internal_re->req_byte = byteflip(re->req_byte, sizeof(re->req_byte)); +internal_re->name_table_offset = byteflip(re->name_table_offset, + sizeof(re->name_table_offset)); +internal_re->name_entry_size = byteflip(re->name_entry_size, + sizeof(re->name_entry_size)); +internal_re->name_count = byteflip(re->name_count, sizeof(re->name_count)); + +if (study != NULL) + { + *internal_study = *study; /* To copy other fields */ + internal_study->size = byteflip(study->size, sizeof(study->size)); + internal_study->options = byteflip(study->options, sizeof(study->options)); + } + +return internal_re; +} + + + +/************************************************* +* (Obsolete) Return info about compiled pattern * +*************************************************/ + +/* This is the original "info" function. It picks potentially useful data out +of the private structure, but its interface was too rigid. It remains for +backwards compatibility. The public options are passed back in an int - though +the re->options field has been expanded to a long int, all the public options +at the low end of it, and so even on 16-bit systems this will still be OK. +Therefore, I haven't changed the API for pcre_info(). + +Arguments: + argument_re points to compiled code + optptr where to pass back the options + first_byte where to pass back the first character, + or -1 if multiline and all branches start ^, + or -2 otherwise + +Returns: number of capturing subpatterns + or negative values on error +*/ + +EXPORT int +pcre_info(const pcre *argument_re, int *optptr, int *first_byte) +{ +real_pcre internal_re; +const real_pcre *re = (const real_pcre *)argument_re; +if (re == NULL) return PCRE_ERROR_NULL; +if (re->magic_number != MAGIC_NUMBER) + { + re = try_flipped(re, &internal_re, NULL, NULL); + if (re == NULL) return PCRE_ERROR_BADMAGIC; + } +if (optptr != NULL) *optptr = (int)(re->options & PUBLIC_OPTIONS); +if (first_byte != NULL) + *first_byte = ((re->options & PCRE_FIRSTSET) != 0)? re->first_byte : + ((re->options & PCRE_STARTLINE) != 0)? -1 : -2; +return re->top_bracket; +} + + + +/************************************************* +* Return info about compiled pattern * +*************************************************/ + +/* This is a newer "info" function which has an extensible interface so +that additional items can be added compatibly. + +Arguments: + argument_re points to compiled code + extra_data points extra data, or NULL + what what information is required + where where to put the information + +Returns: 0 if data returned, negative on error +*/ + +EXPORT int +pcre_fullinfo(const pcre *argument_re, const pcre_extra *extra_data, int what, + void *where) +{ +real_pcre internal_re; +pcre_study_data internal_study; +const real_pcre *re = (const real_pcre *)argument_re; +const pcre_study_data *study = NULL; + +if (re == NULL || where == NULL) return PCRE_ERROR_NULL; + +if (extra_data != NULL && (extra_data->flags & PCRE_EXTRA_STUDY_DATA) != 0) + study = (const pcre_study_data *)extra_data->study_data; + +if (re->magic_number != MAGIC_NUMBER) + { + re = try_flipped(re, &internal_re, study, &internal_study); + if (re == NULL) return PCRE_ERROR_BADMAGIC; + if (study != NULL) study = &internal_study; + } + +switch (what) + { + case PCRE_INFO_OPTIONS: + *((unsigned long int *)where) = re->options & PUBLIC_OPTIONS; + break; + + case PCRE_INFO_SIZE: + *((size_t *)where) = re->size; + break; + + case PCRE_INFO_STUDYSIZE: + *((size_t *)where) = (study == NULL)? 0 : study->size; + break; + + case PCRE_INFO_CAPTURECOUNT: + *((int *)where) = re->top_bracket; + break; + + case PCRE_INFO_BACKREFMAX: + *((int *)where) = re->top_backref; + break; + + case PCRE_INFO_FIRSTBYTE: + *((int *)where) = + ((re->options & PCRE_FIRSTSET) != 0)? re->first_byte : + ((re->options & PCRE_STARTLINE) != 0)? -1 : -2; + break; + + /* Make sure we pass back the pointer to the bit vector in the external + block, not the internal copy (with flipped integer fields). */ + + case PCRE_INFO_FIRSTTABLE: + *((const uschar **)where) = + (study != NULL && (study->options & PCRE_STUDY_MAPPED) != 0)? + ((const pcre_study_data *)extra_data->study_data)->start_bits : NULL; + break; + + case PCRE_INFO_LASTLITERAL: + *((int *)where) = + ((re->options & PCRE_REQCHSET) != 0)? re->req_byte : -1; + break; + + case PCRE_INFO_NAMEENTRYSIZE: + *((int *)where) = re->name_entry_size; + break; + + case PCRE_INFO_NAMECOUNT: + *((int *)where) = re->name_count; + break; + + case PCRE_INFO_NAMETABLE: + *((const uschar **)where) = (const uschar *)re + re->name_table_offset; + break; + + case PCRE_INFO_DEFAULT_TABLES: + *((const uschar **)where) = (const uschar *)pcre_default_tables; + break; + + default: return PCRE_ERROR_BADOPTION; + } + +return 0; +} + + + +/************************************************* +* Return info about what features are configured * +*************************************************/ + +/* This is function which has an extensible interface so that additional items +can be added compatibly. + +Arguments: + what what information is required + where where to put the information + +Returns: 0 if data returned, negative on error +*/ + +EXPORT int +pcre_config(int what, void *where) +{ +switch (what) + { + case PCRE_CONFIG_UTF8: +#ifdef SUPPORT_UTF8 + *((int *)where) = 1; +#else + *((int *)where) = 0; +#endif + break; + + case PCRE_CONFIG_UNICODE_PROPERTIES: +#ifdef SUPPORT_UCP + *((int *)where) = 1; +#else + *((int *)where) = 0; +#endif + break; + + case PCRE_CONFIG_NEWLINE: + *((int *)where) = NEWLINE; + break; + + case PCRE_CONFIG_LINK_SIZE: + *((int *)where) = LINK_SIZE; + break; + + case PCRE_CONFIG_POSIX_MALLOC_THRESHOLD: + *((int *)where) = POSIX_MALLOC_THRESHOLD; + break; + + case PCRE_CONFIG_MATCH_LIMIT: + *((unsigned int *)where) = MATCH_LIMIT; + break; + + case PCRE_CONFIG_STACKRECURSE: +#ifdef NO_RECURSE + *((int *)where) = 0; +#else + *((int *)where) = 1; +#endif + break; + + default: return PCRE_ERROR_BADOPTION; + } + +return 0; +} + + + +#ifdef DEBUG +/************************************************* +* Debugging function to print chars * +*************************************************/ + +/* Print a sequence of chars in printable format, stopping at the end of the +subject if the requested. + +Arguments: + p points to characters + length number to print + is_subject TRUE if printing from within md->start_subject + md pointer to matching data block, if is_subject is TRUE + +Returns: nothing +*/ + +static void +pchars(const uschar *p, int length, BOOL is_subject, match_data *md) +{ +int c; +if (is_subject && length > md->end_subject - p) length = md->end_subject - p; +while (length-- > 0) + if (isprint(c = *(p++))) printf("%c", c); else printf("\\x%02x", c); +} +#endif + + + + +/************************************************* +* Handle escapes * +*************************************************/ + +/* This function is called when a \ has been encountered. It either returns a +positive value for a simple escape such as \n, or a negative value which +encodes one of the more complicated things such as \d. When UTF-8 is enabled, +a positive value greater than 255 may be returned. On entry, ptr is pointing at +the \. On exit, it is on the final character of the escape sequence. + +Arguments: + ptrptr points to the pattern position pointer + errorptr points to the pointer to the error message + bracount number of previous extracting brackets + options the options bits + isclass TRUE if inside a character class + +Returns: zero or positive => a data character + negative => a special escape sequence + on error, errorptr is set +*/ + +static int +check_escape(const uschar **ptrptr, const char **errorptr, int bracount, + int options, BOOL isclass) +{ +const uschar *ptr = *ptrptr; +int c, i; + +/* If backslash is at the end of the pattern, it's an error. */ + +c = *(++ptr); +if (c == 0) *errorptr = ERR1; + +/* Non-alphamerics are literals. For digits or letters, do an initial lookup in +a table. A non-zero result is something that can be returned immediately. +Otherwise further processing may be required. */ + +#if !EBCDIC /* ASCII coding */ +else if (c < '0' || c > 'z') {} /* Not alphameric */ +else if ((i = escapes[c - '0']) != 0) c = i; + +#else /* EBCDIC coding */ +else if (c < 'a' || (ebcdic_chartab[c] & 0x0E) == 0) {} /* Not alphameric */ +else if ((i = escapes[c - 0x48]) != 0) c = i; +#endif + +/* Escapes that need further processing, or are illegal. */ + +else + { + const uschar *oldptr; + switch (c) + { + /* A number of Perl escapes are not handled by PCRE. We give an explicit + error. */ + + case 'l': + case 'L': + case 'N': + case 'u': + case 'U': + *errorptr = ERR37; + break; + + /* The handling of escape sequences consisting of a string of digits + starting with one that is not zero is not straightforward. By experiment, + the way Perl works seems to be as follows: + + Outside a character class, the digits are read as a decimal number. If the + number is less than 10, or if there are that many previous extracting + left brackets, then it is a back reference. Otherwise, up to three octal + digits are read to form an escaped byte. Thus \123 is likely to be octal + 123 (cf \0123, which is octal 012 followed by the literal 3). If the octal + value is greater than 377, the least significant 8 bits are taken. Inside a + character class, \ followed by a digit is always an octal number. */ + + case '1': case '2': case '3': case '4': case '5': + case '6': case '7': case '8': case '9': + + if (!isclass) + { + oldptr = ptr; + c -= '0'; + while ((digitab[ptr[1]] & ctype_digit) != 0) + c = c * 10 + *(++ptr) - '0'; + if (c < 10 || c <= bracount) + { + c = -(ESC_REF + c); + break; + } + ptr = oldptr; /* Put the pointer back and fall through */ + } + + /* Handle an octal number following \. If the first digit is 8 or 9, Perl + generates a binary zero byte and treats the digit as a following literal. + Thus we have to pull back the pointer by one. */ + + if ((c = *ptr) >= '8') + { + ptr--; + c = 0; + break; + } + + /* \0 always starts an octal number, but we may drop through to here with a + larger first octal digit. */ + + case '0': + c -= '0'; + while(i++ < 2 && ptr[1] >= '0' && ptr[1] <= '7') + c = c * 8 + *(++ptr) - '0'; + c &= 255; /* Take least significant 8 bits */ + break; + + /* \x is complicated when UTF-8 is enabled. \x{ddd} is a character number + which can be greater than 0xff, but only if the ddd are hex digits. */ + + case 'x': +#ifdef SUPPORT_UTF8 + if (ptr[1] == '{' && (options & PCRE_UTF8) != 0) + { + const uschar *pt = ptr + 2; + register int count = 0; + c = 0; + while ((digitab[*pt] & ctype_xdigit) != 0) + { + int cc = *pt++; + count++; +#if !EBCDIC /* ASCII coding */ + if (cc >= 'a') cc -= 32; /* Convert to upper case */ + c = c * 16 + cc - ((cc < 'A')? '0' : ('A' - 10)); +#else /* EBCDIC coding */ + if (cc >= 'a' && cc <= 'z') cc += 64; /* Convert to upper case */ + c = c * 16 + cc - ((cc >= '0')? '0' : ('A' - 10)); +#endif + } + if (*pt == '}') + { + if (c < 0 || count > 8) *errorptr = ERR34; + ptr = pt; + break; + } + /* If the sequence of hex digits does not end with '}', then we don't + recognize this construct; fall through to the normal \x handling. */ + } +#endif + + /* Read just a single hex char */ + + c = 0; + while (i++ < 2 && (digitab[ptr[1]] & ctype_xdigit) != 0) + { + int cc; /* Some compilers don't like ++ */ + cc = *(++ptr); /* in initializers */ +#if !EBCDIC /* ASCII coding */ + if (cc >= 'a') cc -= 32; /* Convert to upper case */ + c = c * 16 + cc - ((cc < 'A')? '0' : ('A' - 10)); +#else /* EBCDIC coding */ + if (cc <= 'z') cc += 64; /* Convert to upper case */ + c = c * 16 + cc - ((cc >= '0')? '0' : ('A' - 10)); +#endif + } + break; + + /* Other special escapes not starting with a digit are straightforward */ + + case 'c': + c = *(++ptr); + if (c == 0) + { + *errorptr = ERR2; + return 0; + } + + /* A letter is upper-cased; then the 0x40 bit is flipped. This coding + is ASCII-specific, but then the whole concept of \cx is ASCII-specific. + (However, an EBCDIC equivalent has now been added.) */ + +#if !EBCDIC /* ASCII coding */ + if (c >= 'a' && c <= 'z') c -= 32; + c ^= 0x40; +#else /* EBCDIC coding */ + if (c >= 'a' && c <= 'z') c += 64; + c ^= 0xC0; +#endif + break; + + /* PCRE_EXTRA enables extensions to Perl in the matter of escapes. Any + other alphameric following \ is an error if PCRE_EXTRA was set; otherwise, + for Perl compatibility, it is a literal. This code looks a bit odd, but + there used to be some cases other than the default, and there may be again + in future, so I haven't "optimized" it. */ + + default: + if ((options & PCRE_EXTRA) != 0) switch(c) + { + default: + *errorptr = ERR3; + break; + } + break; + } + } + +*ptrptr = ptr; +return c; +} + + + +#ifdef SUPPORT_UCP +/************************************************* +* Handle \P and \p * +*************************************************/ + +/* This function is called after \P or \p has been encountered, provided that +PCRE is compiled with support for Unicode properties. On entry, ptrptr is +pointing at the P or p. On exit, it is pointing at the final character of the +escape sequence. + +Argument: + ptrptr points to the pattern position pointer + negptr points to a boolean that is set TRUE for negation else FALSE + errorptr points to the pointer to the error message + +Returns: value from ucp_type_table, or -1 for an invalid type +*/ + +static int +get_ucp(const uschar **ptrptr, BOOL *negptr, const char **errorptr) +{ +int c, i, bot, top; +const uschar *ptr = *ptrptr; +char name[4]; + +c = *(++ptr); +if (c == 0) goto ERROR_RETURN; + +*negptr = FALSE; + +/* \P or \p can be followed by a one- or two-character name in {}, optionally +preceded by ^ for negation. */ + +if (c == '{') + { + if (ptr[1] == '^') + { + *negptr = TRUE; + ptr++; + } + for (i = 0; i <= 2; i++) + { + c = *(++ptr); + if (c == 0) goto ERROR_RETURN; + if (c == '}') break; + name[i] = c; + } + if (c !='}') /* Try to distinguish error cases */ + { + while (*(++ptr) != 0 && *ptr != '}'); + if (*ptr == '}') goto UNKNOWN_RETURN; else goto ERROR_RETURN; + } + name[i] = 0; + } + +/* Otherwise there is just one following character */ + +else + { + name[0] = c; + name[1] = 0; + } + +*ptrptr = ptr; + +/* Search for a recognized property name using binary chop */ + +bot = 0; +top = sizeof(utt)/sizeof(ucp_type_table); + +while (bot < top) + { + i = (bot + top)/2; + c = strcmp(name, utt[i].name); + if (c == 0) return utt[i].value; + if (c > 0) bot = i + 1; else top = i; + } + +UNKNOWN_RETURN: +*errorptr = ERR47; +*ptrptr = ptr; +return -1; + +ERROR_RETURN: +*errorptr = ERR46; +*ptrptr = ptr; +return -1; +} +#endif + + + + +/************************************************* +* Check for counted repeat * +*************************************************/ + +/* This function is called when a '{' is encountered in a place where it might +start a quantifier. It looks ahead to see if it really is a quantifier or not. +It is only a quantifier if it is one of the forms {ddd} {ddd,} or {ddd,ddd} +where the ddds are digits. + +Arguments: + p pointer to the first char after '{' + +Returns: TRUE or FALSE +*/ + +static BOOL +is_counted_repeat(const uschar *p) +{ +if ((digitab[*p++] & ctype_digit) == 0) return FALSE; +while ((digitab[*p] & ctype_digit) != 0) p++; +if (*p == '}') return TRUE; + +if (*p++ != ',') return FALSE; +if (*p == '}') return TRUE; + +if ((digitab[*p++] & ctype_digit) == 0) return FALSE; +while ((digitab[*p] & ctype_digit) != 0) p++; + +return (*p == '}'); +} + + + +/************************************************* +* Read repeat counts * +*************************************************/ + +/* Read an item of the form {n,m} and return the values. This is called only +after is_counted_repeat() has confirmed that a repeat-count quantifier exists, +so the syntax is guaranteed to be correct, but we need to check the values. + +Arguments: + p pointer to first char after '{' + minp pointer to int for min + maxp pointer to int for max + returned as -1 if no max + errorptr points to pointer to error message + +Returns: pointer to '}' on success; + current ptr on error, with errorptr set +*/ + +static const uschar * +read_repeat_counts(const uschar *p, int *minp, int *maxp, const char **errorptr) +{ +int min = 0; +int max = -1; + +while ((digitab[*p] & ctype_digit) != 0) min = min * 10 + *p++ - '0'; + +if (*p == '}') max = min; else + { + if (*(++p) != '}') + { + max = 0; + while((digitab[*p] & ctype_digit) != 0) max = max * 10 + *p++ - '0'; + if (max < min) + { + *errorptr = ERR4; + return p; + } + } + } + +/* Do paranoid checks, then fill in the required variables, and pass back the +pointer to the terminating '}'. */ + +if (min > 65535 || max > 65535) + *errorptr = ERR5; +else + { + *minp = min; + *maxp = max; + } +return p; +} + + + +/************************************************* +* Find first significant op code * +*************************************************/ + +/* This is called by several functions that scan a compiled expression looking +for a fixed first character, or an anchoring op code etc. It skips over things +that do not influence this. For some calls, a change of option is important. +For some calls, it makes sense to skip negative forward and all backward +assertions, and also the \b assertion; for others it does not. + +Arguments: + code pointer to the start of the group + options pointer to external options + optbit the option bit whose changing is significant, or + zero if none are + skipassert TRUE if certain assertions are to be skipped + +Returns: pointer to the first significant opcode +*/ + +static const uschar* +first_significant_code(const uschar *code, int *options, int optbit, + BOOL skipassert) +{ +for (;;) + { + switch ((int)*code) + { + case OP_OPT: + if (optbit > 0 && ((int)code[1] & optbit) != (*options & optbit)) + *options = (int)code[1]; + code += 2; + break; + + case OP_ASSERT_NOT: + case OP_ASSERTBACK: + case OP_ASSERTBACK_NOT: + if (!skipassert) return code; + do code += GET(code, 1); while (*code == OP_ALT); + code += OP_lengths[*code]; + break; + + case OP_WORD_BOUNDARY: + case OP_NOT_WORD_BOUNDARY: + if (!skipassert) return code; + /* Fall through */ + + case OP_CALLOUT: + case OP_CREF: + case OP_BRANUMBER: + code += OP_lengths[*code]; + break; + + default: + return code; + } + } +/* Control never reaches here */ +} + + + + +/************************************************* +* Find the fixed length of a pattern * +*************************************************/ + +/* Scan a pattern and compute the fixed length of subject that will match it, +if the length is fixed. This is needed for dealing with backward assertions. +In UTF8 mode, the result is in characters rather than bytes. + +Arguments: + code points to the start of the pattern (the bracket) + options the compiling options + +Returns: the fixed length, or -1 if there is no fixed length, + or -2 if \C was encountered +*/ + +static int +find_fixedlength(uschar *code, int options) +{ +int length = -1; + +register int branchlength = 0; +register uschar *cc = code + 1 + LINK_SIZE; + +/* Scan along the opcodes for this branch. If we get to the end of the +branch, check the length against that of the other branches. */ + +for (;;) + { + int d; + register int op = *cc; + if (op >= OP_BRA) op = OP_BRA; + + switch (op) + { + case OP_BRA: + case OP_ONCE: + case OP_COND: + d = find_fixedlength(cc, options); + if (d < 0) return d; + branchlength += d; + do cc += GET(cc, 1); while (*cc == OP_ALT); + cc += 1 + LINK_SIZE; + break; + + /* Reached end of a branch; if it's a ket it is the end of a nested + call. If it's ALT it is an alternation in a nested call. If it is + END it's the end of the outer call. All can be handled by the same code. */ + + case OP_ALT: + case OP_KET: + case OP_KETRMAX: + case OP_KETRMIN: + case OP_END: + if (length < 0) length = branchlength; + else if (length != branchlength) return -1; + if (*cc != OP_ALT) return length; + cc += 1 + LINK_SIZE; + branchlength = 0; + break; + + /* Skip over assertive subpatterns */ + + case OP_ASSERT: + case OP_ASSERT_NOT: + case OP_ASSERTBACK: + case OP_ASSERTBACK_NOT: + do cc += GET(cc, 1); while (*cc == OP_ALT); + /* Fall through */ + + /* Skip over things that don't match chars */ + + case OP_REVERSE: + case OP_BRANUMBER: + case OP_CREF: + case OP_OPT: + case OP_CALLOUT: + case OP_SOD: + case OP_SOM: + case OP_EOD: + case OP_EODN: + case OP_CIRC: + case OP_DOLL: + case OP_NOT_WORD_BOUNDARY: + case OP_WORD_BOUNDARY: + cc += OP_lengths[*cc]; + break; + + /* Handle literal characters */ + + case OP_CHAR: + case OP_CHARNC: + branchlength++; + cc += 2; +#ifdef SUPPORT_UTF8 + if ((options & PCRE_UTF8) != 0) + { + while ((*cc & 0xc0) == 0x80) cc++; + } +#endif + break; + + /* Handle exact repetitions. The count is already in characters, but we + need to skip over a multibyte character in UTF8 mode. */ + + case OP_EXACT: + branchlength += GET2(cc,1); + cc += 4; +#ifdef SUPPORT_UTF8 + if ((options & PCRE_UTF8) != 0) + { + while((*cc & 0x80) == 0x80) cc++; + } +#endif + break; + + case OP_TYPEEXACT: + branchlength += GET2(cc,1); + cc += 4; + break; + + /* Handle single-char matchers */ + + case OP_PROP: + case OP_NOTPROP: + cc++; + /* Fall through */ + + case OP_NOT_DIGIT: + case OP_DIGIT: + case OP_NOT_WHITESPACE: + case OP_WHITESPACE: + case OP_NOT_WORDCHAR: + case OP_WORDCHAR: + case OP_ANY: + branchlength++; + cc++; + break; + + /* The single-byte matcher isn't allowed */ + + case OP_ANYBYTE: + return -2; + + /* Check a class for variable quantification */ + +#ifdef SUPPORT_UTF8 + case OP_XCLASS: + cc += GET(cc, 1) - 33; + /* Fall through */ +#endif + + case OP_CLASS: + case OP_NCLASS: + cc += 33; + + switch (*cc) + { + case OP_CRSTAR: + case OP_CRMINSTAR: + case OP_CRQUERY: + case OP_CRMINQUERY: + return -1; + + case OP_CRRANGE: + case OP_CRMINRANGE: + if (GET2(cc,1) != GET2(cc,3)) return -1; + branchlength += GET2(cc,1); + cc += 5; + break; + + default: + branchlength++; + } + break; + + /* Anything else is variable length */ + + default: + return -1; + } + } +/* Control never gets here */ +} + + + + +/************************************************* +* Scan compiled regex for numbered bracket * +*************************************************/ + +/* This little function scans through a compiled pattern until it finds a +capturing bracket with the given number. + +Arguments: + code points to start of expression + utf8 TRUE in UTF-8 mode + number the required bracket number + +Returns: pointer to the opcode for the bracket, or NULL if not found +*/ + +static const uschar * +find_bracket(const uschar *code, BOOL utf8, int number) +{ +#ifndef SUPPORT_UTF8 +utf8 = utf8; /* Stop pedantic compilers complaining */ +#endif + +for (;;) + { + register int c = *code; + if (c == OP_END) return NULL; + else if (c > OP_BRA) + { + int n = c - OP_BRA; + if (n > EXTRACT_BASIC_MAX) n = GET2(code, 2+LINK_SIZE); + if (n == number) return (uschar *)code; + code += OP_lengths[OP_BRA]; + } + else + { + code += OP_lengths[c]; + +#ifdef SUPPORT_UTF8 + + /* In UTF-8 mode, opcodes that are followed by a character may be followed + by a multi-byte character. The length in the table is a minimum, so we have + to scan along to skip the extra bytes. All opcodes are less than 128, so we + can use relatively efficient code. */ + + if (utf8) switch(c) + { + case OP_CHAR: + case OP_CHARNC: + case OP_EXACT: + case OP_UPTO: + case OP_MINUPTO: + case OP_STAR: + case OP_MINSTAR: + case OP_PLUS: + case OP_MINPLUS: + case OP_QUERY: + case OP_MINQUERY: + while ((*code & 0xc0) == 0x80) code++; + break; + + /* XCLASS is used for classes that cannot be represented just by a bit + map. This includes negated single high-valued characters. The length in + the table is zero; the actual length is stored in the compiled code. */ + + case OP_XCLASS: + code += GET(code, 1) + 1; + break; + } +#endif + } + } +} + + + +/************************************************* +* Scan compiled regex for recursion reference * +*************************************************/ + +/* This little function scans through a compiled pattern until it finds an +instance of OP_RECURSE. + +Arguments: + code points to start of expression + utf8 TRUE in UTF-8 mode + +Returns: pointer to the opcode for OP_RECURSE, or NULL if not found +*/ + +static const uschar * +find_recurse(const uschar *code, BOOL utf8) +{ +#ifndef SUPPORT_UTF8 +utf8 = utf8; /* Stop pedantic compilers complaining */ +#endif + +for (;;) + { + register int c = *code; + if (c == OP_END) return NULL; + else if (c == OP_RECURSE) return code; + else if (c > OP_BRA) + { + code += OP_lengths[OP_BRA]; + } + else + { + code += OP_lengths[c]; + +#ifdef SUPPORT_UTF8 + + /* In UTF-8 mode, opcodes that are followed by a character may be followed + by a multi-byte character. The length in the table is a minimum, so we have + to scan along to skip the extra bytes. All opcodes are less than 128, so we + can use relatively efficient code. */ + + if (utf8) switch(c) + { + case OP_CHAR: + case OP_CHARNC: + case OP_EXACT: + case OP_UPTO: + case OP_MINUPTO: + case OP_STAR: + case OP_MINSTAR: + case OP_PLUS: + case OP_MINPLUS: + case OP_QUERY: + case OP_MINQUERY: + while ((*code & 0xc0) == 0x80) code++; + break; + + /* XCLASS is used for classes that cannot be represented just by a bit + map. This includes negated single high-valued characters. The length in + the table is zero; the actual length is stored in the compiled code. */ + + case OP_XCLASS: + code += GET(code, 1) + 1; + break; + } +#endif + } + } +} + + + +/************************************************* +* Scan compiled branch for non-emptiness * +*************************************************/ + +/* This function scans through a branch of a compiled pattern to see whether it +can match the empty string or not. It is called only from could_be_empty() +below. Note that first_significant_code() skips over assertions. If we hit an +unclosed bracket, we return "empty" - this means we've struck an inner bracket +whose current branch will already have been scanned. + +Arguments: + code points to start of search + endcode points to where to stop + utf8 TRUE if in UTF8 mode + +Returns: TRUE if what is matched could be empty +*/ + +static BOOL +could_be_empty_branch(const uschar *code, const uschar *endcode, BOOL utf8) +{ +register int c; +for (code = first_significant_code(code + 1 + LINK_SIZE, NULL, 0, TRUE); + code < endcode; + code = first_significant_code(code + OP_lengths[c], NULL, 0, TRUE)) + { + const uschar *ccode; + + c = *code; + + if (c >= OP_BRA) + { + BOOL empty_branch; + if (GET(code, 1) == 0) return TRUE; /* Hit unclosed bracket */ + + /* Scan a closed bracket */ + + empty_branch = FALSE; + do + { + if (!empty_branch && could_be_empty_branch(code, endcode, utf8)) + empty_branch = TRUE; + code += GET(code, 1); + } + while (*code == OP_ALT); + if (!empty_branch) return FALSE; /* All branches are non-empty */ + code += 1 + LINK_SIZE; + c = *code; + } + + else switch (c) + { + /* Check for quantifiers after a class */ + +#ifdef SUPPORT_UTF8 + case OP_XCLASS: + ccode = code + GET(code, 1); + goto CHECK_CLASS_REPEAT; +#endif + + case OP_CLASS: + case OP_NCLASS: + ccode = code + 33; + +#ifdef SUPPORT_UTF8 + CHECK_CLASS_REPEAT: +#endif + + switch (*ccode) + { + case OP_CRSTAR: /* These could be empty; continue */ + case OP_CRMINSTAR: + case OP_CRQUERY: + case OP_CRMINQUERY: + break; + + default: /* Non-repeat => class must match */ + case OP_CRPLUS: /* These repeats aren't empty */ + case OP_CRMINPLUS: + return FALSE; + + case OP_CRRANGE: + case OP_CRMINRANGE: + if (GET2(ccode, 1) > 0) return FALSE; /* Minimum > 0 */ + break; + } + break; + + /* Opcodes that must match a character */ + + case OP_PROP: + case OP_NOTPROP: + case OP_EXTUNI: + case OP_NOT_DIGIT: + case OP_DIGIT: + case OP_NOT_WHITESPACE: + case OP_WHITESPACE: + case OP_NOT_WORDCHAR: + case OP_WORDCHAR: + case OP_ANY: + case OP_ANYBYTE: + case OP_CHAR: + case OP_CHARNC: + case OP_NOT: + case OP_PLUS: + case OP_MINPLUS: + case OP_EXACT: + case OP_NOTPLUS: + case OP_NOTMINPLUS: + case OP_NOTEXACT: + case OP_TYPEPLUS: + case OP_TYPEMINPLUS: + case OP_TYPEEXACT: + return FALSE; + + /* End of branch */ + + case OP_KET: + case OP_KETRMAX: + case OP_KETRMIN: + case OP_ALT: + return TRUE; + + /* In UTF-8 mode, STAR, MINSTAR, QUERY, MINQUERY, UPTO, and MINUPTO may be + followed by a multibyte character */ + +#ifdef SUPPORT_UTF8 + case OP_STAR: + case OP_MINSTAR: + case OP_QUERY: + case OP_MINQUERY: + case OP_UPTO: + case OP_MINUPTO: + if (utf8) while ((code[2] & 0xc0) == 0x80) code++; + break; +#endif + } + } + +return TRUE; +} + + + +/************************************************* +* Scan compiled regex for non-emptiness * +*************************************************/ + +/* This function is called to check for left recursive calls. We want to check +the current branch of the current pattern to see if it could match the empty +string. If it could, we must look outwards for branches at other levels, +stopping when we pass beyond the bracket which is the subject of the recursion. + +Arguments: + code points to start of the recursion + endcode points to where to stop (current RECURSE item) + bcptr points to the chain of current (unclosed) branch starts + utf8 TRUE if in UTF-8 mode + +Returns: TRUE if what is matched could be empty +*/ + +static BOOL +could_be_empty(const uschar *code, const uschar *endcode, branch_chain *bcptr, + BOOL utf8) +{ +while (bcptr != NULL && bcptr->current >= code) + { + if (!could_be_empty_branch(bcptr->current, endcode, utf8)) return FALSE; + bcptr = bcptr->outer; + } +return TRUE; +} + + + +/************************************************* +* Check for POSIX class syntax * +*************************************************/ + +/* This function is called when the sequence "[:" or "[." or "[=" is +encountered in a character class. It checks whether this is followed by an +optional ^ and then a sequence of letters, terminated by a matching ":]" or +".]" or "=]". + +Argument: + ptr pointer to the initial [ + endptr where to return the end pointer + cd pointer to compile data + +Returns: TRUE or FALSE +*/ + +static BOOL +check_posix_syntax(const uschar *ptr, const uschar **endptr, compile_data *cd) +{ +int terminator; /* Don't combine these lines; the Solaris cc */ +terminator = *(++ptr); /* compiler warns about "non-constant" initializer. */ +if (*(++ptr) == '^') ptr++; +while ((cd->ctypes[*ptr] & ctype_letter) != 0) ptr++; +if (*ptr == terminator && ptr[1] == ']') + { + *endptr = ptr; + return TRUE; + } +return FALSE; +} + + + + +/************************************************* +* Check POSIX class name * +*************************************************/ + +/* This function is called to check the name given in a POSIX-style class entry +such as [:alnum:]. + +Arguments: + ptr points to the first letter + len the length of the name + +Returns: a value representing the name, or -1 if unknown +*/ + +static int +check_posix_name(const uschar *ptr, int len) +{ +register int yield = 0; +while (posix_name_lengths[yield] != 0) + { + if (len == posix_name_lengths[yield] && + strncmp((const char *)ptr, posix_names[yield], len) == 0) return yield; + yield++; + } +return -1; +} + + +/************************************************* +* Adjust OP_RECURSE items in repeated group * +*************************************************/ + +/* OP_RECURSE items contain an offset from the start of the regex to the group +that is referenced. This means that groups can be replicated for fixed +repetition simply by copying (because the recursion is allowed to refer to +earlier groups that are outside the current group). However, when a group is +optional (i.e. the minimum quantifier is zero), OP_BRAZERO is inserted before +it, after it has been compiled. This means that any OP_RECURSE items within it +that refer to the group itself or any contained groups have to have their +offsets adjusted. That is the job of this function. Before it is called, the +partially compiled regex must be temporarily terminated with OP_END. + +Arguments: + group points to the start of the group + adjust the amount by which the group is to be moved + utf8 TRUE in UTF-8 mode + cd contains pointers to tables etc. + +Returns: nothing +*/ + +static void +adjust_recurse(uschar *group, int adjust, BOOL utf8, compile_data *cd) +{ +uschar *ptr = group; +while ((ptr = (uschar *)find_recurse(ptr, utf8)) != NULL) + { + int offset = GET(ptr, 1); + if (cd->start_code + offset >= group) PUT(ptr, 1, offset + adjust); + ptr += 1 + LINK_SIZE; + } +} + + + +/************************************************* +* Insert an automatic callout point * +*************************************************/ + +/* This function is called when the PCRE_AUTO_CALLOUT option is set, to insert +callout points before each pattern item. + +Arguments: + code current code pointer + ptr current pattern pointer + cd pointers to tables etc + +Returns: new code pointer +*/ + +static uschar * +auto_callout(uschar *code, const uschar *ptr, compile_data *cd) +{ +*code++ = OP_CALLOUT; +*code++ = 255; +PUT(code, 0, ptr - cd->start_pattern); /* Pattern offset */ +PUT(code, LINK_SIZE, 0); /* Default length */ +return code + 2*LINK_SIZE; +} + + + +/************************************************* +* Complete a callout item * +*************************************************/ + +/* A callout item contains the length of the next item in the pattern, which +we can't fill in till after we have reached the relevant point. This is used +for both automatic and manual callouts. + +Arguments: + previous_callout points to previous callout item + ptr current pattern pointer + cd pointers to tables etc + +Returns: nothing +*/ + +static void +complete_callout(uschar *previous_callout, const uschar *ptr, compile_data *cd) +{ +int length = ptr - cd->start_pattern - GET(previous_callout, 2); +PUT(previous_callout, 2 + LINK_SIZE, length); +} + + + +#ifdef SUPPORT_UCP +/************************************************* +* Get othercase range * +*************************************************/ + +/* This function is passed the start and end of a class range, in UTF-8 mode +with UCP support. It searches up the characters, looking for internal ranges of +characters in the "other" case. Each call returns the next one, updating the +start address. + +Arguments: + cptr points to starting character value; updated + d end value + ocptr where to put start of othercase range + odptr where to put end of othercase range + +Yield: TRUE when range returned; FALSE when no more +*/ + +static BOOL +get_othercase_range(int *cptr, int d, int *ocptr, int *odptr) +{ +int c, chartype, othercase, next; + +for (c = *cptr; c <= d; c++) + { + if (ucp_findchar(c, &chartype, &othercase) == ucp_L && othercase != 0) break; + } + +if (c > d) return FALSE; + +*ocptr = othercase; +next = othercase + 1; + +for (++c; c <= d; c++) + { + if (ucp_findchar(c, &chartype, &othercase) != ucp_L || othercase != next) + break; + next++; + } + +*odptr = next - 1; +*cptr = c; + +return TRUE; +} +#endif /* SUPPORT_UCP */ + + +/************************************************* +* Compile one branch * +*************************************************/ + +/* Scan the pattern, compiling it into the code vector. If the options are +changed during the branch, the pointer is used to change the external options +bits. + +Arguments: + optionsptr pointer to the option bits + brackets points to number of extracting brackets used + codeptr points to the pointer to the current code point + ptrptr points to the current pattern pointer + errorptr points to pointer to error message + firstbyteptr set to initial literal character, or < 0 (REQ_UNSET, REQ_NONE) + reqbyteptr set to the last literal character required, else < 0 + bcptr points to current branch chain + cd contains pointers to tables etc. + +Returns: TRUE on success + FALSE, with *errorptr set on error +*/ + +static BOOL +compile_branch(int *optionsptr, int *brackets, uschar **codeptr, + const uschar **ptrptr, const char **errorptr, int *firstbyteptr, + int *reqbyteptr, branch_chain *bcptr, compile_data *cd) +{ +int repeat_type, op_type; +int repeat_min = 0, repeat_max = 0; /* To please picky compilers */ +int bravalue = 0; +int greedy_default, greedy_non_default; +int firstbyte, reqbyte; +int zeroreqbyte, zerofirstbyte; +int req_caseopt, reqvary, tempreqvary; +int condcount = 0; +int options = *optionsptr; +int after_manual_callout = 0; +register int c; +register uschar *code = *codeptr; +uschar *tempcode; +BOOL inescq = FALSE; +BOOL groupsetfirstbyte = FALSE; +const uschar *ptr = *ptrptr; +const uschar *tempptr; +uschar *previous = NULL; +uschar *previous_callout = NULL; +uschar classbits[32]; + +#ifdef SUPPORT_UTF8 +BOOL class_utf8; +BOOL utf8 = (options & PCRE_UTF8) != 0; +uschar *class_utf8data; +uschar utf8_char[6]; +#else +BOOL utf8 = FALSE; +#endif + +/* Set up the default and non-default settings for greediness */ + +greedy_default = ((options & PCRE_UNGREEDY) != 0); +greedy_non_default = greedy_default ^ 1; + +/* Initialize no first byte, no required byte. REQ_UNSET means "no char +matching encountered yet". It gets changed to REQ_NONE if we hit something that +matches a non-fixed char first char; reqbyte just remains unset if we never +find one. + +When we hit a repeat whose minimum is zero, we may have to adjust these values +to take the zero repeat into account. This is implemented by setting them to +zerofirstbyte and zeroreqbyte when such a repeat is encountered. The individual +item types that can be repeated set these backoff variables appropriately. */ + +firstbyte = reqbyte = zerofirstbyte = zeroreqbyte = REQ_UNSET; + +/* The variable req_caseopt contains either the REQ_CASELESS value or zero, +according to the current setting of the caseless flag. REQ_CASELESS is a bit +value > 255. It is added into the firstbyte or reqbyte variables to record the +case status of the value. This is used only for ASCII characters. */ + +req_caseopt = ((options & PCRE_CASELESS) != 0)? REQ_CASELESS : 0; + +/* Switch on next character until the end of the branch */ + +for (;; ptr++) + { + BOOL negate_class; + BOOL possessive_quantifier; + BOOL is_quantifier; + int class_charcount; + int class_lastchar; + int newoptions; + int recno; + int skipbytes; + int subreqbyte; + int subfirstbyte; + int mclength; + uschar mcbuffer[8]; + + /* Next byte in the pattern */ + + c = *ptr; + + /* If in \Q...\E, check for the end; if not, we have a literal */ + + if (inescq && c != 0) + { + if (c == '\\' && ptr[1] == 'E') + { + inescq = FALSE; + ptr++; + continue; + } + else + { + if (previous_callout != NULL) + { + complete_callout(previous_callout, ptr, cd); + previous_callout = NULL; + } + if ((options & PCRE_AUTO_CALLOUT) != 0) + { + previous_callout = code; + code = auto_callout(code, ptr, cd); + } + goto NORMAL_CHAR; + } + } + + /* Fill in length of a previous callout, except when the next thing is + a quantifier. */ + + is_quantifier = c == '*' || c == '+' || c == '?' || + (c == '{' && is_counted_repeat(ptr+1)); + + if (!is_quantifier && previous_callout != NULL && + after_manual_callout-- <= 0) + { + complete_callout(previous_callout, ptr, cd); + previous_callout = NULL; + } + + /* In extended mode, skip white space and comments */ + + if ((options & PCRE_EXTENDED) != 0) + { + if ((cd->ctypes[c] & ctype_space) != 0) continue; + if (c == '#') + { + /* The space before the ; is to avoid a warning on a silly compiler + on the Macintosh. */ + while ((c = *(++ptr)) != 0 && c != NEWLINE) ; + if (c != 0) continue; /* Else fall through to handle end of string */ + } + } + + /* No auto callout for quantifiers. */ + + if ((options & PCRE_AUTO_CALLOUT) != 0 && !is_quantifier) + { + previous_callout = code; + code = auto_callout(code, ptr, cd); + } + + switch(c) + { + /* The branch terminates at end of string, |, or ). */ + + case 0: + case '|': + case ')': + *firstbyteptr = firstbyte; + *reqbyteptr = reqbyte; + *codeptr = code; + *ptrptr = ptr; + return TRUE; + + /* Handle single-character metacharacters. In multiline mode, ^ disables + the setting of any following char as a first character. */ + + case '^': + if ((options & PCRE_MULTILINE) != 0) + { + if (firstbyte == REQ_UNSET) firstbyte = REQ_NONE; + } + previous = NULL; + *code++ = OP_CIRC; + break; + + case '$': + previous = NULL; + *code++ = OP_DOLL; + break; + + /* There can never be a first char if '.' is first, whatever happens about + repeats. The value of reqbyte doesn't change either. */ + + case '.': + if (firstbyte == REQ_UNSET) firstbyte = REQ_NONE; + zerofirstbyte = firstbyte; + zeroreqbyte = reqbyte; + previous = code; + *code++ = OP_ANY; + break; + + /* Character classes. If the included characters are all < 255 in value, we + build a 32-byte bitmap of the permitted characters, except in the special + case where there is only one such character. For negated classes, we build + the map as usual, then invert it at the end. However, we use a different + opcode so that data characters > 255 can be handled correctly. + + If the class contains characters outside the 0-255 range, a different + opcode is compiled. It may optionally have a bit map for characters < 256, + but those above are are explicitly listed afterwards. A flag byte tells + whether the bitmap is present, and whether this is a negated class or not. + */ + + case '[': + previous = code; + + /* PCRE supports POSIX class stuff inside a class. Perl gives an error if + they are encountered at the top level, so we'll do that too. */ + + if ((ptr[1] == ':' || ptr[1] == '.' || ptr[1] == '=') && + check_posix_syntax(ptr, &tempptr, cd)) + { + *errorptr = (ptr[1] == ':')? ERR13 : ERR31; + goto FAILED; + } + + /* If the first character is '^', set the negation flag and skip it. */ + + if ((c = *(++ptr)) == '^') + { + negate_class = TRUE; + c = *(++ptr); + } + else + { + negate_class = FALSE; + } + + /* Keep a count of chars with values < 256 so that we can optimize the case + of just a single character (as long as it's < 256). For higher valued UTF-8 + characters, we don't yet do any optimization. */ + + class_charcount = 0; + class_lastchar = -1; + +#ifdef SUPPORT_UTF8 + class_utf8 = FALSE; /* No chars >= 256 */ + class_utf8data = code + LINK_SIZE + 34; /* For UTF-8 items */ +#endif + + /* Initialize the 32-char bit map to all zeros. We have to build the + map in a temporary bit of store, in case the class contains only 1 + character (< 256), because in that case the compiled code doesn't use the + bit map. */ + + memset(classbits, 0, 32 * sizeof(uschar)); + + /* Process characters until ] is reached. By writing this as a "do" it + means that an initial ] is taken as a data character. The first pass + through the regex checked the overall syntax, so we don't need to be very + strict here. At the start of the loop, c contains the first byte of the + character. */ + + do + { +#ifdef SUPPORT_UTF8 + if (utf8 && c > 127) + { /* Braces are required because the */ + GETCHARLEN(c, ptr, ptr); /* macro generates multiple statements */ + } +#endif + + /* Inside \Q...\E everything is literal except \E */ + + if (inescq) + { + if (c == '\\' && ptr[1] == 'E') + { + inescq = FALSE; + ptr++; + continue; + } + else goto LONE_SINGLE_CHARACTER; + } + + /* Handle POSIX class names. Perl allows a negation extension of the + form [:^name:]. A square bracket that doesn't match the syntax is + treated as a literal. We also recognize the POSIX constructions + [.ch.] and [=ch=] ("collating elements") and fault them, as Perl + 5.6 and 5.8 do. */ + + if (c == '[' && + (ptr[1] == ':' || ptr[1] == '.' || ptr[1] == '=') && + check_posix_syntax(ptr, &tempptr, cd)) + { + BOOL local_negate = FALSE; + int posix_class, i; + register const uschar *cbits = cd->cbits; + + if (ptr[1] != ':') + { + *errorptr = ERR31; + goto FAILED; + } + + ptr += 2; + if (*ptr == '^') + { + local_negate = TRUE; + ptr++; + } + + posix_class = check_posix_name(ptr, tempptr - ptr); + if (posix_class < 0) + { + *errorptr = ERR30; + goto FAILED; + } + + /* If matching is caseless, upper and lower are converted to + alpha. This relies on the fact that the class table starts with + alpha, lower, upper as the first 3 entries. */ + + if ((options & PCRE_CASELESS) != 0 && posix_class <= 2) + posix_class = 0; + + /* Or into the map we are building up to 3 of the static class + tables, or their negations. The [:blank:] class sets up the same + chars as the [:space:] class (all white space). We remove the vertical + white space chars afterwards. */ + + posix_class *= 3; + for (i = 0; i < 3; i++) + { + BOOL blankclass = strncmp((char *)ptr, "blank", 5) == 0; + int taboffset = posix_class_maps[posix_class + i]; + if (taboffset < 0) break; + if (local_negate) + { + if (i == 0) + for (c = 0; c < 32; c++) classbits[c] |= ~cbits[c+taboffset]; + else + for (c = 0; c < 32; c++) classbits[c] &= ~cbits[c+taboffset]; + if (blankclass) classbits[1] |= 0x3c; + } + else + { + for (c = 0; c < 32; c++) classbits[c] |= cbits[c+taboffset]; + if (blankclass) classbits[1] &= ~0x3c; + } + } + + ptr = tempptr + 1; + class_charcount = 10; /* Set > 1; assumes more than 1 per class */ + continue; /* End of POSIX syntax handling */ + } + + /* Backslash may introduce a single character, or it may introduce one + of the specials, which just set a flag. Escaped items are checked for + validity in the pre-compiling pass. The sequence \b is a special case. + Inside a class (and only there) it is treated as backspace. Elsewhere + it marks a word boundary. Other escapes have preset maps ready to + or into the one we are building. We assume they have more than one + character in them, so set class_charcount bigger than one. */ + + if (c == '\\') + { + c = check_escape(&ptr, errorptr, *brackets, options, TRUE); + + if (-c == ESC_b) c = '\b'; /* \b is backslash in a class */ + else if (-c == ESC_X) c = 'X'; /* \X is literal X in a class */ + else if (-c == ESC_Q) /* Handle start of quoted string */ + { + if (ptr[1] == '\\' && ptr[2] == 'E') + { + ptr += 2; /* avoid empty string */ + } + else inescq = TRUE; + continue; + } + + if (c < 0) + { + register const uschar *cbits = cd->cbits; + class_charcount += 2; /* Greater than 1 is what matters */ + switch (-c) + { + case ESC_d: + for (c = 0; c < 32; c++) classbits[c] |= cbits[c+cbit_digit]; + continue; + + case ESC_D: + for (c = 0; c < 32; c++) classbits[c] |= ~cbits[c+cbit_digit]; + continue; + + case ESC_w: + for (c = 0; c < 32; c++) classbits[c] |= cbits[c+cbit_word]; + continue; + + case ESC_W: + for (c = 0; c < 32; c++) classbits[c] |= ~cbits[c+cbit_word]; + continue; + + case ESC_s: + for (c = 0; c < 32; c++) classbits[c] |= cbits[c+cbit_space]; + classbits[1] &= ~0x08; /* Perl 5.004 onwards omits VT from \s */ + continue; + + case ESC_S: + for (c = 0; c < 32; c++) classbits[c] |= ~cbits[c+cbit_space]; + classbits[1] |= 0x08; /* Perl 5.004 onwards omits VT from \s */ + continue; + +#ifdef SUPPORT_UCP + case ESC_p: + case ESC_P: + { + BOOL negated; + int property = get_ucp(&ptr, &negated, errorptr); + if (property < 0) goto FAILED; + class_utf8 = TRUE; + *class_utf8data++ = ((-c == ESC_p) != negated)? + XCL_PROP : XCL_NOTPROP; + *class_utf8data++ = property; + class_charcount -= 2; /* Not a < 256 character */ + } + continue; +#endif + + /* Unrecognized escapes are faulted if PCRE is running in its + strict mode. By default, for compatibility with Perl, they are + treated as literals. */ + + default: + if ((options & PCRE_EXTRA) != 0) + { + *errorptr = ERR7; + goto FAILED; + } + c = *ptr; /* The final character */ + class_charcount -= 2; /* Undo the default count from above */ + } + } + + /* Fall through if we have a single character (c >= 0). This may be + > 256 in UTF-8 mode. */ + + } /* End of backslash handling */ + + /* A single character may be followed by '-' to form a range. However, + Perl does not permit ']' to be the end of the range. A '-' character + here is treated as a literal. */ + + if (ptr[1] == '-' && ptr[2] != ']') + { + int d; + ptr += 2; + +#ifdef SUPPORT_UTF8 + if (utf8) + { /* Braces are required because the */ + GETCHARLEN(d, ptr, ptr); /* macro generates multiple statements */ + } + else +#endif + d = *ptr; /* Not UTF-8 mode */ + + /* The second part of a range can be a single-character escape, but + not any of the other escapes. Perl 5.6 treats a hyphen as a literal + in such circumstances. */ + + if (d == '\\') + { + const uschar *oldptr = ptr; + d = check_escape(&ptr, errorptr, *brackets, options, TRUE); + + /* \b is backslash; \X is literal X; any other special means the '-' + was literal */ + + if (d < 0) + { + if (d == -ESC_b) d = '\b'; + else if (d == -ESC_X) d = 'X'; else + { + ptr = oldptr - 2; + goto LONE_SINGLE_CHARACTER; /* A few lines below */ + } + } + } + + /* The check that the two values are in the correct order happens in + the pre-pass. Optimize one-character ranges */ + + if (d == c) goto LONE_SINGLE_CHARACTER; /* A few lines below */ + + /* In UTF-8 mode, if the upper limit is > 255, or > 127 for caseless + matching, we have to use an XCLASS with extra data items. Caseless + matching for characters > 127 is available only if UCP support is + available. */ + +#ifdef SUPPORT_UTF8 + if (utf8 && (d > 255 || ((options & PCRE_CASELESS) != 0 && d > 127))) + { + class_utf8 = TRUE; + + /* With UCP support, we can find the other case equivalents of + the relevant characters. There may be several ranges. Optimize how + they fit with the basic range. */ + +#ifdef SUPPORT_UCP + if ((options & PCRE_CASELESS) != 0) + { + int occ, ocd; + int cc = c; + int origd = d; + while (get_othercase_range(&cc, origd, &occ, &ocd)) + { + if (occ >= c && ocd <= d) continue; /* Skip embedded ranges */ + + if (occ < c && ocd >= c - 1) /* Extend the basic range */ + { /* if there is overlap, */ + c = occ; /* noting that if occ < c */ + continue; /* we can't have ocd > d */ + } /* because a subrange is */ + if (ocd > d && occ <= d + 1) /* always shorter than */ + { /* the basic range. */ + d = ocd; + continue; + } + + if (occ == ocd) + { + *class_utf8data++ = XCL_SINGLE; + } + else + { + *class_utf8data++ = XCL_RANGE; + class_utf8data += ord2utf8(occ, class_utf8data); + } + class_utf8data += ord2utf8(ocd, class_utf8data); + } + } +#endif /* SUPPORT_UCP */ + + /* Now record the original range, possibly modified for UCP caseless + overlapping ranges. */ + + *class_utf8data++ = XCL_RANGE; + class_utf8data += ord2utf8(c, class_utf8data); + class_utf8data += ord2utf8(d, class_utf8data); + + /* With UCP support, we are done. Without UCP support, there is no + caseless matching for UTF-8 characters > 127; we can use the bit map + for the smaller ones. */ + +#ifdef SUPPORT_UCP + continue; /* With next character in the class */ +#else + if ((options & PCRE_CASELESS) == 0 || c > 127) continue; + + /* Adjust upper limit and fall through to set up the map */ + + d = 127; + +#endif /* SUPPORT_UCP */ + } +#endif /* SUPPORT_UTF8 */ + + /* We use the bit map for all cases when not in UTF-8 mode; else + ranges that lie entirely within 0-127 when there is UCP support; else + for partial ranges without UCP support. */ + + for (; c <= d; c++) + { + classbits[c/8] |= (1 << (c&7)); + if ((options & PCRE_CASELESS) != 0) + { + int uc = cd->fcc[c]; /* flip case */ + classbits[uc/8] |= (1 << (uc&7)); + } + class_charcount++; /* in case a one-char range */ + class_lastchar = c; + } + + continue; /* Go get the next char in the class */ + } + + /* Handle a lone single character - we can get here for a normal + non-escape char, or after \ that introduces a single character or for an + apparent range that isn't. */ + + LONE_SINGLE_CHARACTER: + + /* Handle a character that cannot go in the bit map */ + +#ifdef SUPPORT_UTF8 + if (utf8 && (c > 255 || ((options & PCRE_CASELESS) != 0 && c > 127))) + { + class_utf8 = TRUE; + *class_utf8data++ = XCL_SINGLE; + class_utf8data += ord2utf8(c, class_utf8data); + +#ifdef SUPPORT_UCP + if ((options & PCRE_CASELESS) != 0) + { + int chartype; + int othercase; + if (ucp_findchar(c, &chartype, &othercase) >= 0 && othercase > 0) + { + *class_utf8data++ = XCL_SINGLE; + class_utf8data += ord2utf8(othercase, class_utf8data); + } + } +#endif /* SUPPORT_UCP */ + + } + else +#endif /* SUPPORT_UTF8 */ + + /* Handle a single-byte character */ + { + classbits[c/8] |= (1 << (c&7)); + if ((options & PCRE_CASELESS) != 0) + { + c = cd->fcc[c]; /* flip case */ + classbits[c/8] |= (1 << (c&7)); + } + class_charcount++; + class_lastchar = c; + } + } + + /* Loop until ']' reached; the check for end of string happens inside the + loop. This "while" is the end of the "do" above. */ + + while ((c = *(++ptr)) != ']' || inescq); + + /* If class_charcount is 1, we saw precisely one character whose value is + less than 256. In non-UTF-8 mode we can always optimize. In UTF-8 mode, we + can optimize the negative case only if there were no characters >= 128 + because OP_NOT and the related opcodes like OP_NOTSTAR operate on + single-bytes only. This is an historical hangover. Maybe one day we can + tidy these opcodes to handle multi-byte characters. + + The optimization throws away the bit map. We turn the item into a + 1-character OP_CHAR[NC] if it's positive, or OP_NOT if it's negative. Note + that OP_NOT does not support multibyte characters. In the positive case, it + can cause firstbyte to be set. Otherwise, there can be no first char if + this item is first, whatever repeat count may follow. In the case of + reqbyte, save the previous value for reinstating. */ + +#ifdef SUPPORT_UTF8 + if (class_charcount == 1 && + (!utf8 || + (!class_utf8 && (!negate_class || class_lastchar < 128)))) + +#else + if (class_charcount == 1) +#endif + { + zeroreqbyte = reqbyte; + + /* The OP_NOT opcode works on one-byte characters only. */ + + if (negate_class) + { + if (firstbyte == REQ_UNSET) firstbyte = REQ_NONE; + zerofirstbyte = firstbyte; + *code++ = OP_NOT; + *code++ = class_lastchar; + break; + } + + /* For a single, positive character, get the value into mcbuffer, and + then we can handle this with the normal one-character code. */ + +#ifdef SUPPORT_UTF8 + if (utf8 && class_lastchar > 127) + mclength = ord2utf8(class_lastchar, mcbuffer); + else +#endif + { + mcbuffer[0] = class_lastchar; + mclength = 1; + } + goto ONE_CHAR; + } /* End of 1-char optimization */ + + /* The general case - not the one-char optimization. If this is the first + thing in the branch, there can be no first char setting, whatever the + repeat count. Any reqbyte setting must remain unchanged after any kind of + repeat. */ + + if (firstbyte == REQ_UNSET) firstbyte = REQ_NONE; + zerofirstbyte = firstbyte; + zeroreqbyte = reqbyte; + + /* If there are characters with values > 255, we have to compile an + extended class, with its own opcode. If there are no characters < 256, + we can omit the bitmap. */ + +#ifdef SUPPORT_UTF8 + if (class_utf8) + { + *class_utf8data++ = XCL_END; /* Marks the end of extra data */ + *code++ = OP_XCLASS; + code += LINK_SIZE; + *code = negate_class? XCL_NOT : 0; + + /* If the map is required, install it, and move on to the end of + the extra data */ + + if (class_charcount > 0) + { + *code++ |= XCL_MAP; + memcpy(code, classbits, 32); + code = class_utf8data; + } + + /* If the map is not required, slide down the extra data. */ + + else + { + int len = class_utf8data - (code + 33); + memmove(code + 1, code + 33, len); + code += len + 1; + } + + /* Now fill in the complete length of the item */ + + PUT(previous, 1, code - previous); + break; /* End of class handling */ + } +#endif + + /* If there are no characters > 255, negate the 32-byte map if necessary, + and copy it into the code vector. If this is the first thing in the branch, + there can be no first char setting, whatever the repeat count. Any reqbyte + setting must remain unchanged after any kind of repeat. */ + + if (negate_class) + { + *code++ = OP_NCLASS; + for (c = 0; c < 32; c++) code[c] = ~classbits[c]; + } + else + { + *code++ = OP_CLASS; + memcpy(code, classbits, 32); + } + code += 32; + break; + + /* Various kinds of repeat; '{' is not necessarily a quantifier, but this + has been tested above. */ + + case '{': + if (!is_quantifier) goto NORMAL_CHAR; + ptr = read_repeat_counts(ptr+1, &repeat_min, &repeat_max, errorptr); + if (*errorptr != NULL) goto FAILED; + goto REPEAT; + + case '*': + repeat_min = 0; + repeat_max = -1; + goto REPEAT; + + case '+': + repeat_min = 1; + repeat_max = -1; + goto REPEAT; + + case '?': + repeat_min = 0; + repeat_max = 1; + + REPEAT: + if (previous == NULL) + { + *errorptr = ERR9; + goto FAILED; + } + + if (repeat_min == 0) + { + firstbyte = zerofirstbyte; /* Adjust for zero repeat */ + reqbyte = zeroreqbyte; /* Ditto */ + } + + /* Remember whether this is a variable length repeat */ + + reqvary = (repeat_min == repeat_max)? 0 : REQ_VARY; + + op_type = 0; /* Default single-char op codes */ + possessive_quantifier = FALSE; /* Default not possessive quantifier */ + + /* Save start of previous item, in case we have to move it up to make space + for an inserted OP_ONCE for the additional '+' extension. */ + + tempcode = previous; + + /* If the next character is '+', we have a possessive quantifier. This + implies greediness, whatever the setting of the PCRE_UNGREEDY option. + If the next character is '?' this is a minimizing repeat, by default, + but if PCRE_UNGREEDY is set, it works the other way round. We change the + repeat type to the non-default. */ + + if (ptr[1] == '+') + { + repeat_type = 0; /* Force greedy */ + possessive_quantifier = TRUE; + ptr++; + } + else if (ptr[1] == '?') + { + repeat_type = greedy_non_default; + ptr++; + } + else repeat_type = greedy_default; + + /* If previous was a recursion, we need to wrap it inside brackets so that + it can be replicated if necessary. */ + + if (*previous == OP_RECURSE) + { + memmove(previous + 1 + LINK_SIZE, previous, 1 + LINK_SIZE); + code += 1 + LINK_SIZE; + *previous = OP_BRA; + PUT(previous, 1, code - previous); + *code = OP_KET; + PUT(code, 1, code - previous); + code += 1 + LINK_SIZE; + } + + /* If previous was a character match, abolish the item and generate a + repeat item instead. If a char item has a minumum of more than one, ensure + that it is set in reqbyte - it might not be if a sequence such as x{3} is + the first thing in a branch because the x will have gone into firstbyte + instead. */ + + if (*previous == OP_CHAR || *previous == OP_CHARNC) + { + /* Deal with UTF-8 characters that take up more than one byte. It's + easier to write this out separately than try to macrify it. Use c to + hold the length of the character in bytes, plus 0x80 to flag that it's a + length rather than a small character. */ + +#ifdef SUPPORT_UTF8 + if (utf8 && (code[-1] & 0x80) != 0) + { + uschar *lastchar = code - 1; + while((*lastchar & 0xc0) == 0x80) lastchar--; + c = code - lastchar; /* Length of UTF-8 character */ + memcpy(utf8_char, lastchar, c); /* Save the char */ + c |= 0x80; /* Flag c as a length */ + } + else +#endif + + /* Handle the case of a single byte - either with no UTF8 support, or + with UTF-8 disabled, or for a UTF-8 character < 128. */ + + { + c = code[-1]; + if (repeat_min > 1) reqbyte = c | req_caseopt | cd->req_varyopt; + } + + goto OUTPUT_SINGLE_REPEAT; /* Code shared with single character types */ + } + + /* If previous was a single negated character ([^a] or similar), we use + one of the special opcodes, replacing it. The code is shared with single- + character repeats by setting opt_type to add a suitable offset into + repeat_type. OP_NOT is currently used only for single-byte chars. */ + + else if (*previous == OP_NOT) + { + op_type = OP_NOTSTAR - OP_STAR; /* Use "not" opcodes */ + c = previous[1]; + goto OUTPUT_SINGLE_REPEAT; + } + + /* If previous was a character type match (\d or similar), abolish it and + create a suitable repeat item. The code is shared with single-character + repeats by setting op_type to add a suitable offset into repeat_type. Note + the the Unicode property types will be present only when SUPPORT_UCP is + defined, but we don't wrap the little bits of code here because it just + makes it horribly messy. */ + + else if (*previous < OP_EODN) + { + uschar *oldcode; + int prop_type; + op_type = OP_TYPESTAR - OP_STAR; /* Use type opcodes */ + c = *previous; + + OUTPUT_SINGLE_REPEAT: + prop_type = (*previous == OP_PROP || *previous == OP_NOTPROP)? + previous[1] : -1; + + oldcode = code; + code = previous; /* Usually overwrite previous item */ + + /* If the maximum is zero then the minimum must also be zero; Perl allows + this case, so we do too - by simply omitting the item altogether. */ + + if (repeat_max == 0) goto END_REPEAT; + + /* All real repeats make it impossible to handle partial matching (maybe + one day we will be able to remove this restriction). */ + + if (repeat_max != 1) cd->nopartial = TRUE; + + /* Combine the op_type with the repeat_type */ + + repeat_type += op_type; + + /* A minimum of zero is handled either as the special case * or ?, or as + an UPTO, with the maximum given. */ + + if (repeat_min == 0) + { + if (repeat_max == -1) *code++ = OP_STAR + repeat_type; + else if (repeat_max == 1) *code++ = OP_QUERY + repeat_type; + else + { + *code++ = OP_UPTO + repeat_type; + PUT2INC(code, 0, repeat_max); + } + } + + /* A repeat minimum of 1 is optimized into some special cases. If the + maximum is unlimited, we use OP_PLUS. Otherwise, the original item it + left in place and, if the maximum is greater than 1, we use OP_UPTO with + one less than the maximum. */ + + else if (repeat_min == 1) + { + if (repeat_max == -1) + *code++ = OP_PLUS + repeat_type; + else + { + code = oldcode; /* leave previous item in place */ + if (repeat_max == 1) goto END_REPEAT; + *code++ = OP_UPTO + repeat_type; + PUT2INC(code, 0, repeat_max - 1); + } + } + + /* The case {n,n} is just an EXACT, while the general case {n,m} is + handled as an EXACT followed by an UPTO. */ + + else + { + *code++ = OP_EXACT + op_type; /* NB EXACT doesn't have repeat_type */ + PUT2INC(code, 0, repeat_min); + + /* If the maximum is unlimited, insert an OP_STAR. Before doing so, + we have to insert the character for the previous code. For a repeated + Unicode property match, there is an extra byte that defines the + required property. In UTF-8 mode, long characters have their length in + c, with the 0x80 bit as a flag. */ + + if (repeat_max < 0) + { +#ifdef SUPPORT_UTF8 + if (utf8 && c >= 128) + { + memcpy(code, utf8_char, c & 7); + code += c & 7; + } + else +#endif + { + *code++ = c; + if (prop_type >= 0) *code++ = prop_type; + } + *code++ = OP_STAR + repeat_type; + } + + /* Else insert an UPTO if the max is greater than the min, again + preceded by the character, for the previously inserted code. */ + + else if (repeat_max != repeat_min) + { +#ifdef SUPPORT_UTF8 + if (utf8 && c >= 128) + { + memcpy(code, utf8_char, c & 7); + code += c & 7; + } + else +#endif + *code++ = c; + if (prop_type >= 0) *code++ = prop_type; + repeat_max -= repeat_min; + *code++ = OP_UPTO + repeat_type; + PUT2INC(code, 0, repeat_max); + } + } + + /* The character or character type itself comes last in all cases. */ + +#ifdef SUPPORT_UTF8 + if (utf8 && c >= 128) + { + memcpy(code, utf8_char, c & 7); + code += c & 7; + } + else +#endif + *code++ = c; + + /* For a repeated Unicode property match, there is an extra byte that + defines the required property. */ + +#ifdef SUPPORT_UCP + if (prop_type >= 0) *code++ = prop_type; +#endif + } + + /* If previous was a character class or a back reference, we put the repeat + stuff after it, but just skip the item if the repeat was {0,0}. */ + + else if (*previous == OP_CLASS || + *previous == OP_NCLASS || +#ifdef SUPPORT_UTF8 + *previous == OP_XCLASS || +#endif + *previous == OP_REF) + { + if (repeat_max == 0) + { + code = previous; + goto END_REPEAT; + } + + /* All real repeats make it impossible to handle partial matching (maybe + one day we will be able to remove this restriction). */ + + if (repeat_max != 1) cd->nopartial = TRUE; + + if (repeat_min == 0 && repeat_max == -1) + *code++ = OP_CRSTAR + repeat_type; + else if (repeat_min == 1 && repeat_max == -1) + *code++ = OP_CRPLUS + repeat_type; + else if (repeat_min == 0 && repeat_max == 1) + *code++ = OP_CRQUERY + repeat_type; + else + { + *code++ = OP_CRRANGE + repeat_type; + PUT2INC(code, 0, repeat_min); + if (repeat_max == -1) repeat_max = 0; /* 2-byte encoding for max */ + PUT2INC(code, 0, repeat_max); + } + } + + /* If previous was a bracket group, we may have to replicate it in certain + cases. */ + + else if (*previous >= OP_BRA || *previous == OP_ONCE || + *previous == OP_COND) + { + register int i; + int ketoffset = 0; + int len = code - previous; + uschar *bralink = NULL; + + /* If the maximum repeat count is unlimited, find the end of the bracket + by scanning through from the start, and compute the offset back to it + from the current code pointer. There may be an OP_OPT setting following + the final KET, so we can't find the end just by going back from the code + pointer. */ + + if (repeat_max == -1) + { + register uschar *ket = previous; + do ket += GET(ket, 1); while (*ket != OP_KET); + ketoffset = code - ket; + } + + /* The case of a zero minimum is special because of the need to stick + OP_BRAZERO in front of it, and because the group appears once in the + data, whereas in other cases it appears the minimum number of times. For + this reason, it is simplest to treat this case separately, as otherwise + the code gets far too messy. There are several special subcases when the + minimum is zero. */ + + if (repeat_min == 0) + { + /* If the maximum is also zero, we just omit the group from the output + altogether. */ + + if (repeat_max == 0) + { + code = previous; + goto END_REPEAT; + } + + /* If the maximum is 1 or unlimited, we just have to stick in the + BRAZERO and do no more at this point. However, we do need to adjust + any OP_RECURSE calls inside the group that refer to the group itself or + any internal group, because the offset is from the start of the whole + regex. Temporarily terminate the pattern while doing this. */ + + if (repeat_max <= 1) + { + *code = OP_END; + adjust_recurse(previous, 1, utf8, cd); + memmove(previous+1, previous, len); + code++; + *previous++ = OP_BRAZERO + repeat_type; + } + + /* If the maximum is greater than 1 and limited, we have to replicate + in a nested fashion, sticking OP_BRAZERO before each set of brackets. + The first one has to be handled carefully because it's the original + copy, which has to be moved up. The remainder can be handled by code + that is common with the non-zero minimum case below. We have to + adjust the value or repeat_max, since one less copy is required. Once + again, we may have to adjust any OP_RECURSE calls inside the group. */ + + else + { + int offset; + *code = OP_END; + adjust_recurse(previous, 2 + LINK_SIZE, utf8, cd); + memmove(previous + 2 + LINK_SIZE, previous, len); + code += 2 + LINK_SIZE; + *previous++ = OP_BRAZERO + repeat_type; + *previous++ = OP_BRA; + + /* We chain together the bracket offset fields that have to be + filled in later when the ends of the brackets are reached. */ + + offset = (bralink == NULL)? 0 : previous - bralink; + bralink = previous; + PUTINC(previous, 0, offset); + } + + repeat_max--; + } + + /* If the minimum is greater than zero, replicate the group as many + times as necessary, and adjust the maximum to the number of subsequent + copies that we need. If we set a first char from the group, and didn't + set a required char, copy the latter from the former. */ + + else + { + if (repeat_min > 1) + { + if (groupsetfirstbyte && reqbyte < 0) reqbyte = firstbyte; + for (i = 1; i < repeat_min; i++) + { + memcpy(code, previous, len); + code += len; + } + } + if (repeat_max > 0) repeat_max -= repeat_min; + } + + /* This code is common to both the zero and non-zero minimum cases. If + the maximum is limited, it replicates the group in a nested fashion, + remembering the bracket starts on a stack. In the case of a zero minimum, + the first one was set up above. In all cases the repeat_max now specifies + the number of additional copies needed. */ + + if (repeat_max >= 0) + { + for (i = repeat_max - 1; i >= 0; i--) + { + *code++ = OP_BRAZERO + repeat_type; + + /* All but the final copy start a new nesting, maintaining the + chain of brackets outstanding. */ + + if (i != 0) + { + int offset; + *code++ = OP_BRA; + offset = (bralink == NULL)? 0 : code - bralink; + bralink = code; + PUTINC(code, 0, offset); + } + + memcpy(code, previous, len); + code += len; + } + + /* Now chain through the pending brackets, and fill in their length + fields (which are holding the chain links pro tem). */ + + while (bralink != NULL) + { + int oldlinkoffset; + int offset = code - bralink + 1; + uschar *bra = code - offset; + oldlinkoffset = GET(bra, 1); + bralink = (oldlinkoffset == 0)? NULL : bralink - oldlinkoffset; + *code++ = OP_KET; + PUTINC(code, 0, offset); + PUT(bra, 1, offset); + } + } + + /* If the maximum is unlimited, set a repeater in the final copy. We + can't just offset backwards from the current code point, because we + don't know if there's been an options resetting after the ket. The + correct offset was computed above. */ + + else code[-ketoffset] = OP_KETRMAX + repeat_type; + } + + /* Else there's some kind of shambles */ + + else + { + *errorptr = ERR11; + goto FAILED; + } + + /* If the character following a repeat is '+', we wrap the entire repeated + item inside OP_ONCE brackets. This is just syntactic sugar, taken from + Sun's Java package. The repeated item starts at tempcode, not at previous, + which might be the first part of a string whose (former) last char we + repeated. However, we don't support '+' after a greediness '?'. */ + + if (possessive_quantifier) + { + int len = code - tempcode; + memmove(tempcode + 1+LINK_SIZE, tempcode, len); + code += 1 + LINK_SIZE; + len += 1 + LINK_SIZE; + tempcode[0] = OP_ONCE; + *code++ = OP_KET; + PUTINC(code, 0, len); + PUT(tempcode, 1, len); + } + + /* In all case we no longer have a previous item. We also set the + "follows varying string" flag for subsequently encountered reqbytes if + it isn't already set and we have just passed a varying length item. */ + + END_REPEAT: + previous = NULL; + cd->req_varyopt |= reqvary; + break; + + + /* Start of nested bracket sub-expression, or comment or lookahead or + lookbehind or option setting or condition. First deal with special things + that can come after a bracket; all are introduced by ?, and the appearance + of any of them means that this is not a referencing group. They were + checked for validity in the first pass over the string, so we don't have to + check for syntax errors here. */ + + case '(': + newoptions = options; + skipbytes = 0; + + if (*(++ptr) == '?') + { + int set, unset; + int *optset; + + switch (*(++ptr)) + { + case '#': /* Comment; skip to ket */ + ptr++; + while (*ptr != ')') ptr++; + continue; + + case ':': /* Non-extracting bracket */ + bravalue = OP_BRA; + ptr++; + break; + + case '(': + bravalue = OP_COND; /* Conditional group */ + + /* Condition to test for recursion */ + + if (ptr[1] == 'R') + { + code[1+LINK_SIZE] = OP_CREF; + PUT2(code, 2+LINK_SIZE, CREF_RECURSE); + skipbytes = 3; + ptr += 3; + } + + /* Condition to test for a numbered subpattern match. We know that + if a digit follows ( then there will just be digits until ) because + the syntax was checked in the first pass. */ + + else if ((digitab[ptr[1]] && ctype_digit) != 0) + { + int condref; /* Don't amalgamate; some compilers */ + condref = *(++ptr) - '0'; /* grumble at autoincrement in declaration */ + while (*(++ptr) != ')') condref = condref*10 + *ptr - '0'; + if (condref == 0) + { + *errorptr = ERR35; + goto FAILED; + } + ptr++; + code[1+LINK_SIZE] = OP_CREF; + PUT2(code, 2+LINK_SIZE, condref); + skipbytes = 3; + } + /* For conditions that are assertions, we just fall through, having + set bravalue above. */ + break; + + case '=': /* Positive lookahead */ + bravalue = OP_ASSERT; + ptr++; + break; + + case '!': /* Negative lookahead */ + bravalue = OP_ASSERT_NOT; + ptr++; + break; + + case '<': /* Lookbehinds */ + switch (*(++ptr)) + { + case '=': /* Positive lookbehind */ + bravalue = OP_ASSERTBACK; + ptr++; + break; + + case '!': /* Negative lookbehind */ + bravalue = OP_ASSERTBACK_NOT; + ptr++; + break; + } + break; + + case '>': /* One-time brackets */ + bravalue = OP_ONCE; + ptr++; + break; + + case 'C': /* Callout - may be followed by digits; */ + previous_callout = code; /* Save for later completion */ + after_manual_callout = 1; /* Skip one item before completing */ + *code++ = OP_CALLOUT; /* Already checked that the terminating */ + { /* closing parenthesis is present. */ + int n = 0; + while ((digitab[*(++ptr)] & ctype_digit) != 0) + n = n * 10 + *ptr - '0'; + if (n > 255) + { + *errorptr = ERR38; + goto FAILED; + } + *code++ = n; + PUT(code, 0, ptr - cd->start_pattern + 1); /* Pattern offset */ + PUT(code, LINK_SIZE, 0); /* Default length */ + code += 2 * LINK_SIZE; + } + previous = NULL; + continue; + + case 'P': /* Named subpattern handling */ + if (*(++ptr) == '<') /* Definition */ + { + int i, namelen; + uschar *slot = cd->name_table; + const uschar *name; /* Don't amalgamate; some compilers */ + name = ++ptr; /* grumble at autoincrement in declaration */ + + while (*ptr++ != '>'); + namelen = ptr - name - 1; + + for (i = 0; i < cd->names_found; i++) + { + int crc = memcmp(name, slot+2, namelen); + if (crc == 0) + { + if (slot[2+namelen] == 0) + { + *errorptr = ERR43; + goto FAILED; + } + crc = -1; /* Current name is substring */ + } + if (crc < 0) + { + memmove(slot + cd->name_entry_size, slot, + (cd->names_found - i) * cd->name_entry_size); + break; + } + slot += cd->name_entry_size; + } + + PUT2(slot, 0, *brackets + 1); + memcpy(slot + 2, name, namelen); + slot[2+namelen] = 0; + cd->names_found++; + goto NUMBERED_GROUP; + } + + if (*ptr == '=' || *ptr == '>') /* Reference or recursion */ + { + int i, namelen; + int type = *ptr++; + const uschar *name = ptr; + uschar *slot = cd->name_table; + + while (*ptr != ')') ptr++; + namelen = ptr - name; + + for (i = 0; i < cd->names_found; i++) + { + if (strncmp((char *)name, (char *)slot+2, namelen) == 0) break; + slot += cd->name_entry_size; + } + if (i >= cd->names_found) + { + *errorptr = ERR15; + goto FAILED; + } + + recno = GET2(slot, 0); + + if (type == '>') goto HANDLE_RECURSION; /* A few lines below */ + + /* Back reference */ + + previous = code; + *code++ = OP_REF; + PUT2INC(code, 0, recno); + cd->backref_map |= (recno < 32)? (1 << recno) : 1; + if (recno > cd->top_backref) cd->top_backref = recno; + continue; + } + + /* Should never happen */ + break; + + case 'R': /* Pattern recursion */ + ptr++; /* Same as (?0) */ + /* Fall through */ + + /* Recursion or "subroutine" call */ + + case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': + { + const uschar *called; + recno = 0; + while((digitab[*ptr] & ctype_digit) != 0) + recno = recno * 10 + *ptr++ - '0'; + + /* Come here from code above that handles a named recursion */ + + HANDLE_RECURSION: + + previous = code; + + /* Find the bracket that is being referenced. Temporarily end the + regex in case it doesn't exist. */ + + *code = OP_END; + called = (recno == 0)? + cd->start_code : find_bracket(cd->start_code, utf8, recno); + + if (called == NULL) + { + *errorptr = ERR15; + goto FAILED; + } + + /* If the subpattern is still open, this is a recursive call. We + check to see if this is a left recursion that could loop for ever, + and diagnose that case. */ + + if (GET(called, 1) == 0 && could_be_empty(called, code, bcptr, utf8)) + { + *errorptr = ERR40; + goto FAILED; + } + + /* Insert the recursion/subroutine item */ + + *code = OP_RECURSE; + PUT(code, 1, called - cd->start_code); + code += 1 + LINK_SIZE; + } + continue; + + /* Character after (? not specially recognized */ + + default: /* Option setting */ + set = unset = 0; + optset = &set; + + while (*ptr != ')' && *ptr != ':') + { + switch (*ptr++) + { + case '-': optset = &unset; break; + + case 'i': *optset |= PCRE_CASELESS; break; + case 'm': *optset |= PCRE_MULTILINE; break; + case 's': *optset |= PCRE_DOTALL; break; + case 'x': *optset |= PCRE_EXTENDED; break; + case 'U': *optset |= PCRE_UNGREEDY; break; + case 'X': *optset |= PCRE_EXTRA; break; + } + } + + /* Set up the changed option bits, but don't change anything yet. */ + + newoptions = (options | set) & (~unset); + + /* If the options ended with ')' this is not the start of a nested + group with option changes, so the options change at this level. Compile + code to change the ims options if this setting actually changes any of + them. We also pass the new setting back so that it can be put at the + start of any following branches, and when this group ends (if we are in + a group), a resetting item can be compiled. + + Note that if this item is right at the start of the pattern, the + options will have been abstracted and made global, so there will be no + change to compile. */ + + if (*ptr == ')') + { + if ((options & PCRE_IMS) != (newoptions & PCRE_IMS)) + { + *code++ = OP_OPT; + *code++ = newoptions & PCRE_IMS; + } + + /* Change options at this level, and pass them back for use + in subsequent branches. Reset the greedy defaults and the case + value for firstbyte and reqbyte. */ + + *optionsptr = options = newoptions; + greedy_default = ((newoptions & PCRE_UNGREEDY) != 0); + greedy_non_default = greedy_default ^ 1; + req_caseopt = ((options & PCRE_CASELESS) != 0)? REQ_CASELESS : 0; + + previous = NULL; /* This item can't be repeated */ + continue; /* It is complete */ + } + + /* If the options ended with ':' we are heading into a nested group + with possible change of options. Such groups are non-capturing and are + not assertions of any kind. All we need to do is skip over the ':'; + the newoptions value is handled below. */ + + bravalue = OP_BRA; + ptr++; + } + } + + /* If PCRE_NO_AUTO_CAPTURE is set, all unadorned brackets become + non-capturing and behave like (?:...) brackets */ + + else if ((options & PCRE_NO_AUTO_CAPTURE) != 0) + { + bravalue = OP_BRA; + } + + /* Else we have a referencing group; adjust the opcode. If the bracket + number is greater than EXTRACT_BASIC_MAX, we set the opcode one higher, and + arrange for the true number to follow later, in an OP_BRANUMBER item. */ + + else + { + NUMBERED_GROUP: + if (++(*brackets) > EXTRACT_BASIC_MAX) + { + bravalue = OP_BRA + EXTRACT_BASIC_MAX + 1; + code[1+LINK_SIZE] = OP_BRANUMBER; + PUT2(code, 2+LINK_SIZE, *brackets); + skipbytes = 3; + } + else bravalue = OP_BRA + *brackets; + } + + /* Process nested bracketed re. Assertions may not be repeated, but other + kinds can be. We copy code into a non-register variable in order to be able + to pass its address because some compilers complain otherwise. Pass in a + new setting for the ims options if they have changed. */ + + previous = (bravalue >= OP_ONCE)? code : NULL; + *code = bravalue; + tempcode = code; + tempreqvary = cd->req_varyopt; /* Save value before bracket */ + + if (!compile_regex( + newoptions, /* The complete new option state */ + options & PCRE_IMS, /* The previous ims option state */ + brackets, /* Extracting bracket count */ + &tempcode, /* Where to put code (updated) */ + &ptr, /* Input pointer (updated) */ + errorptr, /* Where to put an error message */ + (bravalue == OP_ASSERTBACK || + bravalue == OP_ASSERTBACK_NOT), /* TRUE if back assert */ + skipbytes, /* Skip over OP_COND/OP_BRANUMBER */ + &subfirstbyte, /* For possible first char */ + &subreqbyte, /* For possible last char */ + bcptr, /* Current branch chain */ + cd)) /* Tables block */ + goto FAILED; + + /* At the end of compiling, code is still pointing to the start of the + group, while tempcode has been updated to point past the end of the group + and any option resetting that may follow it. The pattern pointer (ptr) + is on the bracket. */ + + /* If this is a conditional bracket, check that there are no more than + two branches in the group. */ + + else if (bravalue == OP_COND) + { + uschar *tc = code; + condcount = 0; + + do { + condcount++; + tc += GET(tc,1); + } + while (*tc != OP_KET); + + if (condcount > 2) + { + *errorptr = ERR27; + goto FAILED; + } + + /* If there is just one branch, we must not make use of its firstbyte or + reqbyte, because this is equivalent to an empty second branch. */ + + if (condcount == 1) subfirstbyte = subreqbyte = REQ_NONE; + } + + /* Handle updating of the required and first characters. Update for normal + brackets of all kinds, and conditions with two branches (see code above). + If the bracket is followed by a quantifier with zero repeat, we have to + back off. Hence the definition of zeroreqbyte and zerofirstbyte outside the + main loop so that they can be accessed for the back off. */ + + zeroreqbyte = reqbyte; + zerofirstbyte = firstbyte; + groupsetfirstbyte = FALSE; + + if (bravalue >= OP_BRA || bravalue == OP_ONCE || bravalue == OP_COND) + { + /* If we have not yet set a firstbyte in this branch, take it from the + subpattern, remembering that it was set here so that a repeat of more + than one can replicate it as reqbyte if necessary. If the subpattern has + no firstbyte, set "none" for the whole branch. In both cases, a zero + repeat forces firstbyte to "none". */ + + if (firstbyte == REQ_UNSET) + { + if (subfirstbyte >= 0) + { + firstbyte = subfirstbyte; + groupsetfirstbyte = TRUE; + } + else firstbyte = REQ_NONE; + zerofirstbyte = REQ_NONE; + } + + /* If firstbyte was previously set, convert the subpattern's firstbyte + into reqbyte if there wasn't one, using the vary flag that was in + existence beforehand. */ + + else if (subfirstbyte >= 0 && subreqbyte < 0) + subreqbyte = subfirstbyte | tempreqvary; + + /* If the subpattern set a required byte (or set a first byte that isn't + really the first byte - see above), set it. */ + + if (subreqbyte >= 0) reqbyte = subreqbyte; + } + + /* For a forward assertion, we take the reqbyte, if set. This can be + helpful if the pattern that follows the assertion doesn't set a different + char. For example, it's useful for /(?=abcde).+/. We can't set firstbyte + for an assertion, however because it leads to incorrect effect for patterns + such as /(?=a)a.+/ when the "real" "a" would then become a reqbyte instead + of a firstbyte. This is overcome by a scan at the end if there's no + firstbyte, looking for an asserted first char. */ + + else if (bravalue == OP_ASSERT && subreqbyte >= 0) reqbyte = subreqbyte; + + /* Now update the main code pointer to the end of the group. */ + + code = tempcode; + + /* Error if hit end of pattern */ + + if (*ptr != ')') + { + *errorptr = ERR14; + goto FAILED; + } + break; + + /* Check \ for being a real metacharacter; if not, fall through and handle + it as a data character at the start of a string. Escape items are checked + for validity in the pre-compiling pass. */ + + case '\\': + tempptr = ptr; + c = check_escape(&ptr, errorptr, *brackets, options, FALSE); + + /* Handle metacharacters introduced by \. For ones like \d, the ESC_ values + are arranged to be the negation of the corresponding OP_values. For the + back references, the values are ESC_REF plus the reference number. Only + back references and those types that consume a character may be repeated. + We can test for values between ESC_b and ESC_Z for the latter; this may + have to change if any new ones are ever created. */ + + if (c < 0) + { + if (-c == ESC_Q) /* Handle start of quoted string */ + { + if (ptr[1] == '\\' && ptr[2] == 'E') ptr += 2; /* avoid empty string */ + else inescq = TRUE; + continue; + } + + /* For metasequences that actually match a character, we disable the + setting of a first character if it hasn't already been set. */ + + if (firstbyte == REQ_UNSET && -c > ESC_b && -c < ESC_Z) + firstbyte = REQ_NONE; + + /* Set values to reset to if this is followed by a zero repeat. */ + + zerofirstbyte = firstbyte; + zeroreqbyte = reqbyte; + + /* Back references are handled specially */ + + if (-c >= ESC_REF) + { + int number = -c - ESC_REF; + previous = code; + *code++ = OP_REF; + PUT2INC(code, 0, number); + } + + /* So are Unicode property matches, if supported. We know that get_ucp + won't fail because it was tested in the pre-pass. */ + +#ifdef SUPPORT_UCP + else if (-c == ESC_P || -c == ESC_p) + { + BOOL negated; + int value = get_ucp(&ptr, &negated, errorptr); + previous = code; + *code++ = ((-c == ESC_p) != negated)? OP_PROP : OP_NOTPROP; + *code++ = value; + } +#endif + + /* For the rest, we can obtain the OP value by negating the escape + value */ + + else + { + previous = (-c > ESC_b && -c < ESC_Z)? code : NULL; + *code++ = -c; + } + continue; + } + + /* We have a data character whose value is in c. In UTF-8 mode it may have + a value > 127. We set its representation in the length/buffer, and then + handle it as a data character. */ + +#ifdef SUPPORT_UTF8 + if (utf8 && c > 127) + mclength = ord2utf8(c, mcbuffer); + else +#endif + + { + mcbuffer[0] = c; + mclength = 1; + } + + goto ONE_CHAR; + + /* Handle a literal character. It is guaranteed not to be whitespace or # + when the extended flag is set. If we are in UTF-8 mode, it may be a + multi-byte literal character. */ + + default: + NORMAL_CHAR: + mclength = 1; + mcbuffer[0] = c; + +#ifdef SUPPORT_UTF8 + if (utf8 && (c & 0xc0) == 0xc0) + { + while ((ptr[1] & 0xc0) == 0x80) + mcbuffer[mclength++] = *(++ptr); + } +#endif + + /* At this point we have the character's bytes in mcbuffer, and the length + in mclength. When not in UTF-8 mode, the length is always 1. */ + + ONE_CHAR: + previous = code; + *code++ = ((options & PCRE_CASELESS) != 0)? OP_CHARNC : OP_CHAR; + for (c = 0; c < mclength; c++) *code++ = mcbuffer[c]; + + /* Set the first and required bytes appropriately. If no previous first + byte, set it from this character, but revert to none on a zero repeat. + Otherwise, leave the firstbyte value alone, and don't change it on a zero + repeat. */ + + if (firstbyte == REQ_UNSET) + { + zerofirstbyte = REQ_NONE; + zeroreqbyte = reqbyte; + + /* If the character is more than one byte long, we can set firstbyte + only if it is not to be matched caselessly. */ + + if (mclength == 1 || req_caseopt == 0) + { + firstbyte = mcbuffer[0] | req_caseopt; + if (mclength != 1) reqbyte = code[-1] | cd->req_varyopt; + } + else firstbyte = reqbyte = REQ_NONE; + } + + /* firstbyte was previously set; we can set reqbyte only the length is + 1 or the matching is caseful. */ + + else + { + zerofirstbyte = firstbyte; + zeroreqbyte = reqbyte; + if (mclength == 1 || req_caseopt == 0) + reqbyte = code[-1] | req_caseopt | cd->req_varyopt; + } + + break; /* End of literal character handling */ + } + } /* end of big loop */ + +/* Control never reaches here by falling through, only by a goto for all the +error states. Pass back the position in the pattern so that it can be displayed +to the user for diagnosing the error. */ + +FAILED: +*ptrptr = ptr; +return FALSE; +} + + + + +/************************************************* +* Compile sequence of alternatives * +*************************************************/ + +/* On entry, ptr is pointing past the bracket character, but on return +it points to the closing bracket, or vertical bar, or end of string. +The code variable is pointing at the byte into which the BRA operator has been +stored. If the ims options are changed at the start (for a (?ims: group) or +during any branch, we need to insert an OP_OPT item at the start of every +following branch to ensure they get set correctly at run time, and also pass +the new options into every subsequent branch compile. + +Argument: + options option bits, including any changes for this subpattern + oldims previous settings of ims option bits + brackets -> int containing the number of extracting brackets used + codeptr -> the address of the current code pointer + ptrptr -> the address of the current pattern pointer + errorptr -> pointer to error message + lookbehind TRUE if this is a lookbehind assertion + skipbytes skip this many bytes at start (for OP_COND, OP_BRANUMBER) + firstbyteptr place to put the first required character, or a negative number + reqbyteptr place to put the last required character, or a negative number + bcptr pointer to the chain of currently open branches + cd points to the data block with tables pointers etc. + +Returns: TRUE on success +*/ + +static BOOL +compile_regex(int options, int oldims, int *brackets, uschar **codeptr, + const uschar **ptrptr, const char **errorptr, BOOL lookbehind, int skipbytes, + int *firstbyteptr, int *reqbyteptr, branch_chain *bcptr, compile_data *cd) +{ +const uschar *ptr = *ptrptr; +uschar *code = *codeptr; +uschar *last_branch = code; +uschar *start_bracket = code; +uschar *reverse_count = NULL; +int firstbyte, reqbyte; +int branchfirstbyte, branchreqbyte; +branch_chain bc; + +bc.outer = bcptr; +bc.current = code; + +firstbyte = reqbyte = REQ_UNSET; + +/* Offset is set zero to mark that this bracket is still open */ + +PUT(code, 1, 0); +code += 1 + LINK_SIZE + skipbytes; + +/* Loop for each alternative branch */ + +for (;;) + { + /* Handle a change of ims options at the start of the branch */ + + if ((options & PCRE_IMS) != oldims) + { + *code++ = OP_OPT; + *code++ = options & PCRE_IMS; + } + + /* Set up dummy OP_REVERSE if lookbehind assertion */ + + if (lookbehind) + { + *code++ = OP_REVERSE; + reverse_count = code; + PUTINC(code, 0, 0); + } + + /* Now compile the branch */ + + if (!compile_branch(&options, brackets, &code, &ptr, errorptr, + &branchfirstbyte, &branchreqbyte, &bc, cd)) + { + *ptrptr = ptr; + return FALSE; + } + + /* If this is the first branch, the firstbyte and reqbyte values for the + branch become the values for the regex. */ + + if (*last_branch != OP_ALT) + { + firstbyte = branchfirstbyte; + reqbyte = branchreqbyte; + } + + /* If this is not the first branch, the first char and reqbyte have to + match the values from all the previous branches, except that if the previous + value for reqbyte didn't have REQ_VARY set, it can still match, and we set + REQ_VARY for the regex. */ + + else + { + /* If we previously had a firstbyte, but it doesn't match the new branch, + we have to abandon the firstbyte for the regex, but if there was previously + no reqbyte, it takes on the value of the old firstbyte. */ + + if (firstbyte >= 0 && firstbyte != branchfirstbyte) + { + if (reqbyte < 0) reqbyte = firstbyte; + firstbyte = REQ_NONE; + } + + /* If we (now or from before) have no firstbyte, a firstbyte from the + branch becomes a reqbyte if there isn't a branch reqbyte. */ + + if (firstbyte < 0 && branchfirstbyte >= 0 && branchreqbyte < 0) + branchreqbyte = branchfirstbyte; + + /* Now ensure that the reqbytes match */ + + if ((reqbyte & ~REQ_VARY) != (branchreqbyte & ~REQ_VARY)) + reqbyte = REQ_NONE; + else reqbyte |= branchreqbyte; /* To "or" REQ_VARY */ + } + + /* If lookbehind, check that this branch matches a fixed-length string, + and put the length into the OP_REVERSE item. Temporarily mark the end of + the branch with OP_END. */ + + if (lookbehind) + { + int length; + *code = OP_END; + length = find_fixedlength(last_branch, options); + DPRINTF(("fixed length = %d\n", length)); + if (length < 0) + { + *errorptr = (length == -2)? ERR36 : ERR25; + *ptrptr = ptr; + return FALSE; + } + PUT(reverse_count, 0, length); + } + + /* Reached end of expression, either ')' or end of pattern. Go back through + the alternative branches and reverse the chain of offsets, with the field in + the BRA item now becoming an offset to the first alternative. If there are + no alternatives, it points to the end of the group. The length in the + terminating ket is always the length of the whole bracketed item. If any of + the ims options were changed inside the group, compile a resetting op-code + following, except at the very end of the pattern. Return leaving the pointer + at the terminating char. */ + + if (*ptr != '|') + { + int length = code - last_branch; + do + { + int prev_length = GET(last_branch, 1); + PUT(last_branch, 1, length); + length = prev_length; + last_branch -= length; + } + while (length > 0); + + /* Fill in the ket */ + + *code = OP_KET; + PUT(code, 1, code - start_bracket); + code += 1 + LINK_SIZE; + + /* Resetting option if needed */ + + if ((options & PCRE_IMS) != oldims && *ptr == ')') + { + *code++ = OP_OPT; + *code++ = oldims; + } + + /* Set values to pass back */ + + *codeptr = code; + *ptrptr = ptr; + *firstbyteptr = firstbyte; + *reqbyteptr = reqbyte; + return TRUE; + } + + /* Another branch follows; insert an "or" node. Its length field points back + to the previous branch while the bracket remains open. At the end the chain + is reversed. It's done like this so that the start of the bracket has a + zero offset until it is closed, making it possible to detect recursion. */ + + *code = OP_ALT; + PUT(code, 1, code - last_branch); + bc.current = last_branch = code; + code += 1 + LINK_SIZE; + ptr++; + } +/* Control never reaches here */ +} + + + + +/************************************************* +* Check for anchored expression * +*************************************************/ + +/* Try to find out if this is an anchored regular expression. Consider each +alternative branch. If they all start with OP_SOD or OP_CIRC, or with a bracket +all of whose alternatives start with OP_SOD or OP_CIRC (recurse ad lib), then +it's anchored. However, if this is a multiline pattern, then only OP_SOD +counts, since OP_CIRC can match in the middle. + +We can also consider a regex to be anchored if OP_SOM starts all its branches. +This is the code for \G, which means "match at start of match position, taking +into account the match offset". + +A branch is also implicitly anchored if it starts with .* and DOTALL is set, +because that will try the rest of the pattern at all possible matching points, +so there is no point trying again.... er .... + +.... except when the .* appears inside capturing parentheses, and there is a +subsequent back reference to those parentheses. We haven't enough information +to catch that case precisely. + +At first, the best we could do was to detect when .* was in capturing brackets +and the highest back reference was greater than or equal to that level. +However, by keeping a bitmap of the first 31 back references, we can catch some +of the more common cases more precisely. + +Arguments: + code points to start of expression (the bracket) + options points to the options setting + bracket_map a bitmap of which brackets we are inside while testing; this + handles up to substring 31; after that we just have to take + the less precise approach + backref_map the back reference bitmap + +Returns: TRUE or FALSE +*/ + +static BOOL +is_anchored(register const uschar *code, int *options, unsigned int bracket_map, + unsigned int backref_map) +{ +do { + const uschar *scode = + first_significant_code(code + 1+LINK_SIZE, options, PCRE_MULTILINE, FALSE); + register int op = *scode; + + /* Capturing brackets */ + + if (op > OP_BRA) + { + int new_map; + op -= OP_BRA; + if (op > EXTRACT_BASIC_MAX) op = GET2(scode, 2+LINK_SIZE); + new_map = bracket_map | ((op < 32)? (1 << op) : 1); + if (!is_anchored(scode, options, new_map, backref_map)) return FALSE; + } + + /* Other brackets */ + + else if (op == OP_BRA || op == OP_ASSERT || op == OP_ONCE || op == OP_COND) + { + if (!is_anchored(scode, options, bracket_map, backref_map)) return FALSE; + } + + /* .* is not anchored unless DOTALL is set and it isn't in brackets that + are or may be referenced. */ + + else if ((op == OP_TYPESTAR || op == OP_TYPEMINSTAR) && + (*options & PCRE_DOTALL) != 0) + { + if (scode[1] != OP_ANY || (bracket_map & backref_map) != 0) return FALSE; + } + + /* Check for explicit anchoring */ + + else if (op != OP_SOD && op != OP_SOM && + ((*options & PCRE_MULTILINE) != 0 || op != OP_CIRC)) + return FALSE; + code += GET(code, 1); + } +while (*code == OP_ALT); /* Loop for each alternative */ +return TRUE; +} + + + +/************************************************* +* Check for starting with ^ or .* * +*************************************************/ + +/* This is called to find out if every branch starts with ^ or .* so that +"first char" processing can be done to speed things up in multiline +matching and for non-DOTALL patterns that start with .* (which must start at +the beginning or after \n). As in the case of is_anchored() (see above), we +have to take account of back references to capturing brackets that contain .* +because in that case we can't make the assumption. + +Arguments: + code points to start of expression (the bracket) + bracket_map a bitmap of which brackets we are inside while testing; this + handles up to substring 31; after that we just have to take + the less precise approach + backref_map the back reference bitmap + +Returns: TRUE or FALSE +*/ + +static BOOL +is_startline(const uschar *code, unsigned int bracket_map, + unsigned int backref_map) +{ +do { + const uschar *scode = first_significant_code(code + 1+LINK_SIZE, NULL, 0, + FALSE); + register int op = *scode; + + /* Capturing brackets */ + + if (op > OP_BRA) + { + int new_map; + op -= OP_BRA; + if (op > EXTRACT_BASIC_MAX) op = GET2(scode, 2+LINK_SIZE); + new_map = bracket_map | ((op < 32)? (1 << op) : 1); + if (!is_startline(scode, new_map, backref_map)) return FALSE; + } + + /* Other brackets */ + + else if (op == OP_BRA || op == OP_ASSERT || op == OP_ONCE || op == OP_COND) + { if (!is_startline(scode, bracket_map, backref_map)) return FALSE; } + + /* .* means "start at start or after \n" if it isn't in brackets that + may be referenced. */ + + else if (op == OP_TYPESTAR || op == OP_TYPEMINSTAR) + { + if (scode[1] != OP_ANY || (bracket_map & backref_map) != 0) return FALSE; + } + + /* Check for explicit circumflex */ + + else if (op != OP_CIRC) return FALSE; + + /* Move on to the next alternative */ + + code += GET(code, 1); + } +while (*code == OP_ALT); /* Loop for each alternative */ +return TRUE; +} + + + +/************************************************* +* Check for asserted fixed first char * +*************************************************/ + +/* During compilation, the "first char" settings from forward assertions are +discarded, because they can cause conflicts with actual literals that follow. +However, if we end up without a first char setting for an unanchored pattern, +it is worth scanning the regex to see if there is an initial asserted first +char. If all branches start with the same asserted char, or with a bracket all +of whose alternatives start with the same asserted char (recurse ad lib), then +we return that char, otherwise -1. + +Arguments: + code points to start of expression (the bracket) + options pointer to the options (used to check casing changes) + inassert TRUE if in an assertion + +Returns: -1 or the fixed first char +*/ + +static int +find_firstassertedchar(const uschar *code, int *options, BOOL inassert) +{ +register int c = -1; +do { + int d; + const uschar *scode = + first_significant_code(code + 1+LINK_SIZE, options, PCRE_CASELESS, TRUE); + register int op = *scode; + + if (op >= OP_BRA) op = OP_BRA; + + switch(op) + { + default: + return -1; + + case OP_BRA: + case OP_ASSERT: + case OP_ONCE: + case OP_COND: + if ((d = find_firstassertedchar(scode, options, op == OP_ASSERT)) < 0) + return -1; + if (c < 0) c = d; else if (c != d) return -1; + break; + + case OP_EXACT: /* Fall through */ + scode += 2; + + case OP_CHAR: + case OP_CHARNC: + case OP_PLUS: + case OP_MINPLUS: + if (!inassert) return -1; + if (c < 0) + { + c = scode[1]; + if ((*options & PCRE_CASELESS) != 0) c |= REQ_CASELESS; + } + else if (c != scode[1]) return -1; + break; + } + + code += GET(code, 1); + } +while (*code == OP_ALT); +return c; +} + + + + +#ifdef SUPPORT_UTF8 +/************************************************* +* Validate a UTF-8 string * +*************************************************/ + +/* This function is called (optionally) at the start of compile or match, to +validate that a supposed UTF-8 string is actually valid. The early check means +that subsequent code can assume it is dealing with a valid string. The check +can be turned off for maximum performance, but then consequences of supplying +an invalid string are then undefined. + +Arguments: + string points to the string + length length of string, or -1 if the string is zero-terminated + +Returns: < 0 if the string is a valid UTF-8 string + >= 0 otherwise; the value is the offset of the bad byte +*/ + +static int +valid_utf8(const uschar *string, int length) +{ +register const uschar *p; + +if (length < 0) + { + for (p = string; *p != 0; p++); + length = p - string; + } + +for (p = string; length-- > 0; p++) + { + register int ab; + register int c = *p; + if (c < 128) continue; + if ((c & 0xc0) != 0xc0) return p - string; + ab = utf8_table4[c & 0x3f]; /* Number of additional bytes */ + if (length < ab) return p - string; + length -= ab; + + /* Check top bits in the second byte */ + if ((*(++p) & 0xc0) != 0x80) return p - string; + + /* Check for overlong sequences for each different length */ + switch (ab) + { + /* Check for xx00 000x */ + case 1: + if ((c & 0x3e) == 0) return p - string; + continue; /* We know there aren't any more bytes to check */ + + /* Check for 1110 0000, xx0x xxxx */ + case 2: + if (c == 0xe0 && (*p & 0x20) == 0) return p - string; + break; + + /* Check for 1111 0000, xx00 xxxx */ + case 3: + if (c == 0xf0 && (*p & 0x30) == 0) return p - string; + break; + + /* Check for 1111 1000, xx00 0xxx */ + case 4: + if (c == 0xf8 && (*p & 0x38) == 0) return p - string; + break; + + /* Check for leading 0xfe or 0xff, and then for 1111 1100, xx00 00xx */ + case 5: + if (c == 0xfe || c == 0xff || + (c == 0xfc && (*p & 0x3c) == 0)) return p - string; + break; + } + + /* Check for valid bytes after the 2nd, if any; all must start 10 */ + while (--ab > 0) + { + if ((*(++p) & 0xc0) != 0x80) return p - string; + } + } + +return -1; +} +#endif + + + +/************************************************* +* Compile a Regular Expression * +*************************************************/ + +/* This function takes a string and returns a pointer to a block of store +holding a compiled version of the expression. + +Arguments: + pattern the regular expression + options various option bits + errorptr pointer to pointer to error text + erroroffset ptr offset in pattern where error was detected + tables pointer to character tables or NULL + +Returns: pointer to compiled data block, or NULL on error, + with errorptr and erroroffset set +*/ + +EXPORT pcre * +pcre_compile(const char *pattern, int options, const char **errorptr, + int *erroroffset, const unsigned char *tables) +{ +real_pcre *re; +int length = 1 + LINK_SIZE; /* For initial BRA plus length */ +//int runlength; +int c, firstbyte, reqbyte; +int bracount = 0; +int branch_extra = 0; +int branch_newextra; +int item_count = -1; +int name_count = 0; +int max_name_size = 0; +int lastitemlength = 0; +#ifdef SUPPORT_UTF8 +BOOL utf8; +BOOL class_utf8; +#endif +BOOL inescq = FALSE; +unsigned int brastackptr = 0; +size_t size; +uschar *code; +const uschar *codestart; +const uschar *ptr; +compile_data compile_block; +int brastack[BRASTACK_SIZE]; +uschar bralenstack[BRASTACK_SIZE]; + +/* We can't pass back an error message if errorptr is NULL; I guess the best we +can do is just return NULL. */ + +if (errorptr == NULL) return NULL; +*errorptr = NULL; + +/* However, we can give a message for this error */ + +if (erroroffset == NULL) + { + *errorptr = ERR16; + return NULL; + } +*erroroffset = 0; + +/* Can't support UTF8 unless PCRE has been compiled to include the code. */ + +#ifdef SUPPORT_UTF8 +utf8 = (options & PCRE_UTF8) != 0; +if (utf8 && (options & PCRE_NO_UTF8_CHECK) == 0 && + (*erroroffset = valid_utf8((uschar *)pattern, -1)) >= 0) + { + *errorptr = ERR44; + return NULL; + } +#else +if ((options & PCRE_UTF8) != 0) + { + *errorptr = ERR32; + return NULL; + } +#endif + +if ((options & ~PUBLIC_OPTIONS) != 0) + { + *errorptr = ERR17; + return NULL; + } + +/* Set up pointers to the individual character tables */ + +if (tables == NULL) tables = pcre_default_tables; +compile_block.lcc = tables + lcc_offset; +compile_block.fcc = tables + fcc_offset; +compile_block.cbits = tables + cbits_offset; +compile_block.ctypes = tables + ctypes_offset; + +/* Maximum back reference and backref bitmap. This is updated for numeric +references during the first pass, but for named references during the actual +compile pass. The bitmap records up to 31 back references to help in deciding +whether (.*) can be treated as anchored or not. */ + +compile_block.top_backref = 0; +compile_block.backref_map = 0; + +/* Reflect pattern for debugging output */ + +DPRINTF(("------------------------------------------------------------------\n")); +DPRINTF(("%s\n", pattern)); + +/* The first thing to do is to make a pass over the pattern to compute the +amount of store required to hold the compiled code. This does not have to be +perfect as long as errors are overestimates. At the same time we can detect any +flag settings right at the start, and extract them. Make an attempt to correct +for any counted white space if an "extended" flag setting appears late in the +pattern. We can't be so clever for #-comments. */ + +ptr = (const uschar *)(pattern - 1); +while ((c = *(++ptr)) != 0) + { + int min, max; + int class_optcount; + int bracket_length; + int duplength; + + /* If we are inside a \Q...\E sequence, all chars are literal */ + + if (inescq) + { + if ((options & PCRE_AUTO_CALLOUT) != 0) length += 2 + 2*LINK_SIZE; + goto NORMAL_CHAR; + } + + /* Otherwise, first check for ignored whitespace and comments */ + + if ((options & PCRE_EXTENDED) != 0) + { + if ((compile_block.ctypes[c] & ctype_space) != 0) continue; + if (c == '#') + { + /* The space before the ; is to avoid a warning on a silly compiler + on the Macintosh. */ + while ((c = *(++ptr)) != 0 && c != NEWLINE) ; + if (c == 0) break; + continue; + } + } + + item_count++; /* Is zero for the first non-comment item */ + + /* Allow space for auto callout before every item except quantifiers. */ + + if ((options & PCRE_AUTO_CALLOUT) != 0 && + c != '*' && c != '+' && c != '?' && + (c != '{' || !is_counted_repeat(ptr + 1))) + length += 2 + 2*LINK_SIZE; + + switch(c) + { + /* A backslashed item may be an escaped data character or it may be a + character type. */ + + case '\\': + c = check_escape(&ptr, errorptr, bracount, options, FALSE); + if (*errorptr != NULL) goto PCRE_ERROR_RETURN; + + lastitemlength = 1; /* Default length of last item for repeats */ + + if (c >= 0) /* Data character */ + { + length += 2; /* For a one-byte character */ + +#ifdef SUPPORT_UTF8 + if (utf8 && c > 127) + { + int i; + for (i = 0; i < sizeof(utf8_table1)/sizeof(int); i++) + if (c <= utf8_table1[i]) break; + length += i; + lastitemlength += i; + } +#endif + + continue; + } + + /* If \Q, enter "literal" mode */ + + if (-c == ESC_Q) + { + inescq = TRUE; + continue; + } + + /* \X is supported only if Unicode property support is compiled */ + +#ifndef SUPPORT_UCP + if (-c == ESC_X) + { + *errorptr = ERR45; + goto PCRE_ERROR_RETURN; + } +#endif + + /* \P and \p are for Unicode properties, but only when the support has + been compiled. Each item needs 2 bytes. */ + + else if (-c == ESC_P || -c == ESC_p) + { +#ifdef SUPPORT_UCP + BOOL negated; + length += 2; + lastitemlength = 2; + if (get_ucp(&ptr, &negated, errorptr) < 0) goto PCRE_ERROR_RETURN; + continue; +#else + *errorptr = ERR45; + goto PCRE_ERROR_RETURN; +#endif + } + + /* Other escapes need one byte */ + + length++; + + /* A back reference needs an additional 2 bytes, plus either one or 5 + bytes for a repeat. We also need to keep the value of the highest + back reference. */ + + if (c <= -ESC_REF) + { + int refnum = -c - ESC_REF; + compile_block.backref_map |= (refnum < 32)? (1 << refnum) : 1; + if (refnum > compile_block.top_backref) + compile_block.top_backref = refnum; + length += 2; /* For single back reference */ + if (ptr[1] == '{' && is_counted_repeat(ptr+2)) + { + ptr = read_repeat_counts(ptr+2, &min, &max, errorptr); + if (*errorptr != NULL) goto PCRE_ERROR_RETURN; + if ((min == 0 && (max == 1 || max == -1)) || + (min == 1 && max == -1)) + length++; + else length += 5; + if (ptr[1] == '?') ptr++; + } + } + continue; + + case '^': /* Single-byte metacharacters */ + case '.': + case '$': + length++; + lastitemlength = 1; + continue; + + case '*': /* These repeats won't be after brackets; */ + case '+': /* those are handled separately */ + case '?': + length++; + goto POSESSIVE; /* A few lines below */ + + /* This covers the cases of braced repeats after a single char, metachar, + class, or back reference. */ + + case '{': + if (!is_counted_repeat(ptr+1)) goto NORMAL_CHAR; + ptr = read_repeat_counts(ptr+1, &min, &max, errorptr); + if (*errorptr != NULL) goto PCRE_ERROR_RETURN; + + /* These special cases just insert one extra opcode */ + + if ((min == 0 && (max == 1 || max == -1)) || + (min == 1 && max == -1)) + length++; + + /* These cases might insert additional copies of a preceding character. */ + + else + { + if (min != 1) + { + length -= lastitemlength; /* Uncount the original char or metachar */ + if (min > 0) length += 3 + lastitemlength; + } + length += lastitemlength + ((max > 0)? 3 : 1); + } + + if (ptr[1] == '?') ptr++; /* Needs no extra length */ + + POSESSIVE: /* Test for possessive quantifier */ + if (ptr[1] == '+') + { + ptr++; + length += 2 + 2*LINK_SIZE; /* Allow for atomic brackets */ + } + continue; + + /* An alternation contains an offset to the next branch or ket. If any ims + options changed in the previous branch(es), and/or if we are in a + lookbehind assertion, extra space will be needed at the start of the + branch. This is handled by branch_extra. */ + + case '|': + length += 1 + LINK_SIZE + branch_extra; + continue; + + /* A character class uses 33 characters provided that all the character + values are less than 256. Otherwise, it uses a bit map for low valued + characters, and individual items for others. Don't worry about character + types that aren't allowed in classes - they'll get picked up during the + compile. A character class that contains only one single-byte character + uses 2 or 3 bytes, depending on whether it is negated or not. Notice this + where we can. (In UTF-8 mode we can do this only for chars < 128.) */ + + case '[': + if (*(++ptr) == '^') + { + class_optcount = 10; /* Greater than one */ + ptr++; + } + else class_optcount = 0; + +#ifdef SUPPORT_UTF8 + class_utf8 = FALSE; +#endif + + /* Written as a "do" so that an initial ']' is taken as data */ + + if (*ptr != 0) do + { + /* Inside \Q...\E everything is literal except \E */ + + if (inescq) + { + if (*ptr != '\\' || ptr[1] != 'E') goto GET_ONE_CHARACTER; + inescq = FALSE; + ptr += 1; + continue; + } + + /* Outside \Q...\E, check for escapes */ + + if (*ptr == '\\') + { + c = check_escape(&ptr, errorptr, bracount, options, TRUE); + if (*errorptr != NULL) goto PCRE_ERROR_RETURN; + + /* \b is backspace inside a class; \X is literal */ + + if (-c == ESC_b) c = '\b'; + else if (-c == ESC_X) c = 'X'; + + /* \Q enters quoting mode */ + + else if (-c == ESC_Q) + { + inescq = TRUE; + continue; + } + + /* Handle escapes that turn into characters */ + + if (c >= 0) goto NON_SPECIAL_CHARACTER; + + /* Escapes that are meta-things. The normal ones just affect the + bit map, but Unicode properties require an XCLASS extended item. */ + + else + { + class_optcount = 10; /* \d, \s etc; make sure > 1 */ +#ifdef SUPPORT_UTF8 + if (-c == ESC_p || -c == ESC_P) + { + if (!class_utf8) + { + class_utf8 = TRUE; + length += LINK_SIZE + 2; + } + length += 2; + } +#endif + } + } + + /* Check the syntax for POSIX stuff. The bits we actually handle are + checked during the real compile phase. */ + + else if (*ptr == '[' && check_posix_syntax(ptr, &ptr, &compile_block)) + { + ptr++; + class_optcount = 10; /* Make sure > 1 */ + } + + /* Anything else increments the possible optimization count. We have to + detect ranges here so that we can compute the number of extra ranges for + caseless wide characters when UCP support is available. If there are wide + characters, we are going to have to use an XCLASS, even for single + characters. */ + + else + { + int d; + + GET_ONE_CHARACTER: + +#ifdef SUPPORT_UTF8 + if (utf8) + { + int extra = 0; + GETCHARLEN(c, ptr, extra); + ptr += extra; + } + else c = *ptr; +#else + c = *ptr; +#endif + + /* Come here from handling \ above when it escapes to a char value */ + + NON_SPECIAL_CHARACTER: + class_optcount++; + + d = -1; + if (ptr[1] == '-') + { + uschar const *hyptr = ptr++; + if (ptr[1] == '\\') + { + ptr++; + d = check_escape(&ptr, errorptr, bracount, options, TRUE); + if (*errorptr != NULL) goto PCRE_ERROR_RETURN; + if (-d == ESC_b) d = '\b'; /* backspace */ + else if (-d == ESC_X) d = 'X'; /* literal X in a class */ + } + else if (ptr[1] != 0 && ptr[1] != ']') + { + ptr++; +#ifdef SUPPORT_UTF8 + if (utf8) + { + int extra = 0; + GETCHARLEN(d, ptr, extra); + ptr += extra; + } + else +#endif + d = *ptr; + } + if (d < 0) ptr = hyptr; /* go back to hyphen as data */ + } + + /* If d >= 0 we have a range. In UTF-8 mode, if the end is > 255, or > + 127 for caseless matching, we will need to use an XCLASS. */ + + if (d >= 0) + { + class_optcount = 10; /* Ensure > 1 */ + if (d < c) + { + *errorptr = ERR8; + goto PCRE_ERROR_RETURN; + } + +#ifdef SUPPORT_UTF8 + if (utf8 && (d > 255 || ((options & PCRE_CASELESS) != 0 && d > 127))) + { + uschar buffer[6]; + if (!class_utf8) /* Allow for XCLASS overhead */ + { + class_utf8 = TRUE; + length += LINK_SIZE + 2; + } + +#ifdef SUPPORT_UCP + /* If we have UCP support, find out how many extra ranges are + needed to map the other case of characters within this range. We + have to mimic the range optimization here, because extending the + range upwards might push d over a boundary that makes is use + another byte in the UTF-8 representation. */ + + if ((options & PCRE_CASELESS) != 0) + { + int occ, ocd; + int cc = c; + int origd = d; + while (get_othercase_range(&cc, origd, &occ, &ocd)) + { + if (occ >= c && ocd <= d) continue; /* Skip embedded */ + + if (occ < c && ocd >= c - 1) /* Extend the basic range */ + { /* if there is overlap, */ + c = occ; /* noting that if occ < c */ + continue; /* we can't have ocd > d */ + } /* because a subrange is */ + if (ocd > d && occ <= d + 1) /* always shorter than */ + { /* the basic range. */ + d = ocd; + continue; + } + + /* An extra item is needed */ + + length += 1 + ord2utf8(occ, buffer) + + ((occ == ocd)? 0 : ord2utf8(ocd, buffer)); + } + } +#endif /* SUPPORT_UCP */ + + /* The length of the (possibly extended) range */ + + length += 1 + ord2utf8(c, buffer) + ord2utf8(d, buffer); + } +#endif /* SUPPORT_UTF8 */ + + } + + /* We have a single character. There is nothing to be done unless we + are in UTF-8 mode. If the char is > 255, or 127 when caseless, we must + allow for an XCL_SINGLE item, doubled for caselessness if there is UCP + support. */ + + else + { +#ifdef SUPPORT_UTF8 + if (utf8 && (c > 255 || ((options & PCRE_CASELESS) != 0 && c > 127))) + { + uschar buffer[6]; + class_optcount = 10; /* Ensure > 1 */ + if (!class_utf8) /* Allow for XCLASS overhead */ + { + class_utf8 = TRUE; + length += LINK_SIZE + 2; + } +#ifdef SUPPORT_UCP + length += (((options & PCRE_CASELESS) != 0)? 2 : 1) * + (1 + ord2utf8(c, buffer)); +#else /* SUPPORT_UCP */ + length += 1 + ord2utf8(c, buffer); +#endif /* SUPPORT_UCP */ + } +#endif /* SUPPORT_UTF8 */ + } + } + } + while (*(++ptr) != 0 && (inescq || *ptr != ']')); /* Concludes "do" above */ + + if (*ptr == 0) /* Missing terminating ']' */ + { + *errorptr = ERR6; + goto PCRE_ERROR_RETURN; + } + + /* We can optimize when there was only one optimizable character. Repeats + for positive and negated single one-byte chars are handled by the general + code. Here, we handle repeats for the class opcodes. */ + + if (class_optcount == 1) length += 3; else + { + length += 33; + + /* A repeat needs either 1 or 5 bytes. If it is a possessive quantifier, + we also need extra for wrapping the whole thing in a sub-pattern. */ + + if (*ptr != 0 && ptr[1] == '{' && is_counted_repeat(ptr+2)) + { + ptr = read_repeat_counts(ptr+2, &min, &max, errorptr); + if (*errorptr != NULL) goto PCRE_ERROR_RETURN; + if ((min == 0 && (max == 1 || max == -1)) || + (min == 1 && max == -1)) + length++; + else length += 5; + if (ptr[1] == '+') + { + ptr++; + length += 2 + 2*LINK_SIZE; + } + else if (ptr[1] == '?') ptr++; + } + } + continue; + + /* Brackets may be genuine groups or special things */ + + case '(': + branch_newextra = 0; + bracket_length = 1 + LINK_SIZE; + + /* Handle special forms of bracket, which all start (? */ + + if (ptr[1] == '?') + { + int set, unset; + int *optset; + + switch (c = ptr[2]) + { + /* Skip over comments entirely */ + case '#': + ptr += 3; + while (*ptr != 0 && *ptr != ')') ptr++; + if (*ptr == 0) + { + *errorptr = ERR18; + goto PCRE_ERROR_RETURN; + } + continue; + + /* Non-referencing groups and lookaheads just move the pointer on, and + then behave like a non-special bracket, except that they don't increment + the count of extracting brackets. Ditto for the "once only" bracket, + which is in Perl from version 5.005. */ + + case ':': + case '=': + case '!': + case '>': + ptr += 2; + break; + + /* (?R) specifies a recursive call to the regex, which is an extension + to provide the facility which can be obtained by (?p{perl-code}) in + Perl 5.6. In Perl 5.8 this has become (??{perl-code}). + + From PCRE 4.00, items such as (?3) specify subroutine-like "calls" to + the appropriate numbered brackets. This includes both recursive and + non-recursive calls. (?R) is now synonymous with (?0). */ + + case 'R': + ptr++; + + case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': + ptr += 2; + if (c != 'R') + while ((digitab[*(++ptr)] & ctype_digit) != 0); + if (*ptr != ')') + { + *errorptr = ERR29; + goto PCRE_ERROR_RETURN; + } + length += 1 + LINK_SIZE; + + /* If this item is quantified, it will get wrapped inside brackets so + as to use the code for quantified brackets. We jump down and use the + code that handles this for real brackets. */ + + if (ptr[1] == '+' || ptr[1] == '*' || ptr[1] == '?' || ptr[1] == '{') + { + length += 2 + 2 * LINK_SIZE; /* to make bracketed */ + duplength = 5 + 3 * LINK_SIZE; + goto HANDLE_QUANTIFIED_BRACKETS; + } + continue; + + /* (?C) is an extension which provides "callout" - to provide a bit of + the functionality of the Perl (?{...}) feature. An optional number may + follow (default is zero). */ + + case 'C': + ptr += 2; + while ((digitab[*(++ptr)] & ctype_digit) != 0); + if (*ptr != ')') + { + *errorptr = ERR39; + goto PCRE_ERROR_RETURN; + } + length += 2 + 2*LINK_SIZE; + continue; + + /* Named subpatterns are an extension copied from Python */ + + case 'P': + ptr += 3; + if (*ptr == '<') + { + const uschar *p; /* Don't amalgamate; some compilers */ + p = ++ptr; /* grumble at autoincrement in declaration */ + while ((compile_block.ctypes[*ptr] & ctype_word) != 0) ptr++; + if (*ptr != '>') + { + *errorptr = ERR42; + goto PCRE_ERROR_RETURN; + } + name_count++; + if (ptr - p > max_name_size) max_name_size = (ptr - p); + break; + } + + if (*ptr == '=' || *ptr == '>') + { + while ((compile_block.ctypes[*(++ptr)] & ctype_word) != 0); + if (*ptr != ')') + { + *errorptr = ERR42; + goto PCRE_ERROR_RETURN; + } + break; + } + + /* Unknown character after (?P */ + + *errorptr = ERR41; + goto PCRE_ERROR_RETURN; + + /* Lookbehinds are in Perl from version 5.005 */ + + case '<': + ptr += 3; + if (*ptr == '=' || *ptr == '!') + { + branch_newextra = 1 + LINK_SIZE; + length += 1 + LINK_SIZE; /* For the first branch */ + break; + } + *errorptr = ERR24; + goto PCRE_ERROR_RETURN; + + /* Conditionals are in Perl from version 5.005. The bracket must either + be followed by a number (for bracket reference) or by an assertion + group, or (a PCRE extension) by 'R' for a recursion test. */ + + case '(': + if (ptr[3] == 'R' && ptr[4] == ')') + { + ptr += 4; + length += 3; + } + else if ((digitab[ptr[3]] & ctype_digit) != 0) + { + ptr += 4; + length += 3; + while ((digitab[*ptr] & ctype_digit) != 0) ptr++; + if (*ptr != ')') + { + *errorptr = ERR26; + goto PCRE_ERROR_RETURN; + } + } + else /* An assertion must follow */ + { + ptr++; /* Can treat like ':' as far as spacing is concerned */ + if (ptr[2] != '?' || + (ptr[3] != '=' && ptr[3] != '!' && ptr[3] != '<') ) + { + ptr += 2; /* To get right offset in message */ + *errorptr = ERR28; + goto PCRE_ERROR_RETURN; + } + } + break; + + /* Else loop checking valid options until ) is met. Anything else is an + error. If we are without any brackets, i.e. at top level, the settings + act as if specified in the options, so massage the options immediately. + This is for backward compatibility with Perl 5.004. */ + + default: + set = unset = 0; + optset = &set; + ptr += 2; + + for (;; ptr++) + { + c = *ptr; + switch (c) + { + case 'i': + *optset |= PCRE_CASELESS; + continue; + + case 'm': + *optset |= PCRE_MULTILINE; + continue; + + case 's': + *optset |= PCRE_DOTALL; + continue; + + case 'x': + *optset |= PCRE_EXTENDED; + continue; + + case 'X': + *optset |= PCRE_EXTRA; + continue; + + case 'U': + *optset |= PCRE_UNGREEDY; + continue; + + case '-': + optset = &unset; + continue; + + /* A termination by ')' indicates an options-setting-only item; if + this is at the very start of the pattern (indicated by item_count + being zero), we use it to set the global options. This is helpful + when analyzing the pattern for first characters, etc. Otherwise + nothing is done here and it is handled during the compiling + process. + + [Historical note: Up to Perl 5.8, options settings at top level + were always global settings, wherever they appeared in the pattern. + That is, they were equivalent to an external setting. From 5.8 + onwards, they apply only to what follows (which is what you might + expect).] */ + + case ')': + if (item_count == 0) + { + options = (options | set) & (~unset); + set = unset = 0; /* To save length */ + item_count--; /* To allow for several */ + } + + /* Fall through */ + + /* A termination by ':' indicates the start of a nested group with + the given options set. This is again handled at compile time, but + we must allow for compiled space if any of the ims options are + set. We also have to allow for resetting space at the end of + the group, which is why 4 is added to the length and not just 2. + If there are several changes of options within the same group, this + will lead to an over-estimate on the length, but this shouldn't + matter very much. We also have to allow for resetting options at + the start of any alternations, which we do by setting + branch_newextra to 2. Finally, we record whether the case-dependent + flag ever changes within the regex. This is used by the "required + character" code. */ + + case ':': + if (((set|unset) & PCRE_IMS) != 0) + { + length += 4; + branch_newextra = 2; + if (((set|unset) & PCRE_CASELESS) != 0) options |= PCRE_ICHANGED; + } + goto END_OPTIONS; + + /* Unrecognized option character */ + + default: + *errorptr = ERR12; + goto PCRE_ERROR_RETURN; + } + } + + /* If we hit a closing bracket, that's it - this is a freestanding + option-setting. We need to ensure that branch_extra is updated if + necessary. The only values branch_newextra can have here are 0 or 2. + If the value is 2, then branch_extra must either be 2 or 5, depending + on whether this is a lookbehind group or not. */ + + END_OPTIONS: + if (c == ')') + { + if (branch_newextra == 2 && + (branch_extra == 0 || branch_extra == 1+LINK_SIZE)) + branch_extra += branch_newextra; + continue; + } + + /* If options were terminated by ':' control comes here. Fall through + to handle the group below. */ + } + } + + /* Extracting brackets must be counted so we can process escapes in a + Perlish way. If the number exceeds EXTRACT_BASIC_MAX we are going to + need an additional 3 bytes of store per extracting bracket. However, if + PCRE_NO_AUTO)CAPTURE is set, unadorned brackets become non-capturing, so we + must leave the count alone (it will aways be zero). */ + + else if ((options & PCRE_NO_AUTO_CAPTURE) == 0) + { + bracount++; + if (bracount > EXTRACT_BASIC_MAX) bracket_length += 3; + } + + /* Save length for computing whole length at end if there's a repeat that + requires duplication of the group. Also save the current value of + branch_extra, and start the new group with the new value. If non-zero, this + will either be 2 for a (?imsx: group, or 3 for a lookbehind assertion. */ + + if (brastackptr >= sizeof(brastack)/sizeof(int)) + { + *errorptr = ERR19; + goto PCRE_ERROR_RETURN; + } + + bralenstack[brastackptr] = branch_extra; + branch_extra = branch_newextra; + + brastack[brastackptr++] = length; + length += bracket_length; + continue; + + /* Handle ket. Look for subsequent max/min; for certain sets of values we + have to replicate this bracket up to that many times. If brastackptr is + 0 this is an unmatched bracket which will generate an error, but take care + not to try to access brastack[-1] when computing the length and restoring + the branch_extra value. */ + + case ')': + length += 1 + LINK_SIZE; + if (brastackptr > 0) + { + duplength = length - brastack[--brastackptr]; + branch_extra = bralenstack[brastackptr]; + } + else duplength = 0; + + /* The following code is also used when a recursion such as (?3) is + followed by a quantifier, because in that case, it has to be wrapped inside + brackets so that the quantifier works. The value of duplength must be + set before arrival. */ + + HANDLE_QUANTIFIED_BRACKETS: + + /* Leave ptr at the final char; for read_repeat_counts this happens + automatically; for the others we need an increment. */ + + if ((c = ptr[1]) == '{' && is_counted_repeat(ptr+2)) + { + ptr = read_repeat_counts(ptr+2, &min, &max, errorptr); + if (*errorptr != NULL) goto PCRE_ERROR_RETURN; + } + else if (c == '*') { min = 0; max = -1; ptr++; } + else if (c == '+') { min = 1; max = -1; ptr++; } + else if (c == '?') { min = 0; max = 1; ptr++; } + else { min = 1; max = 1; } + + /* If the minimum is zero, we have to allow for an OP_BRAZERO before the + group, and if the maximum is greater than zero, we have to replicate + maxval-1 times; each replication acquires an OP_BRAZERO plus a nesting + bracket set. */ + + if (min == 0) + { + length++; + if (max > 0) length += (max - 1) * (duplength + 3 + 2*LINK_SIZE); + } + + /* When the minimum is greater than zero, we have to replicate up to + minval-1 times, with no additions required in the copies. Then, if there + is a limited maximum we have to replicate up to maxval-1 times allowing + for a BRAZERO item before each optional copy and nesting brackets for all + but one of the optional copies. */ + + else + { + length += (min - 1) * duplength; + if (max > min) /* Need this test as max=-1 means no limit */ + length += (max - min) * (duplength + 3 + 2*LINK_SIZE) + - (2 + 2*LINK_SIZE); + } + + /* Allow space for once brackets for "possessive quantifier" */ + + if (ptr[1] == '+') + { + ptr++; + length += 2 + 2*LINK_SIZE; + } + continue; + + /* Non-special character. It won't be space or # in extended mode, so it is + always a genuine character. If we are in a \Q...\E sequence, check for the + end; if not, we have a literal. */ + + default: + NORMAL_CHAR: + + if (inescq && c == '\\' && ptr[1] == 'E') + { + inescq = FALSE; + ptr++; + continue; + } + + length += 2; /* For a one-byte character */ + lastitemlength = 1; /* Default length of last item for repeats */ + + /* In UTF-8 mode, check for additional bytes. */ + +#ifdef SUPPORT_UTF8 + if (utf8 && (c & 0xc0) == 0xc0) + { + while ((ptr[1] & 0xc0) == 0x80) /* Can't flow over the end */ + { /* because the end is marked */ + lastitemlength++; /* by a zero byte. */ + length++; + ptr++; + } + } +#endif + + continue; + } + } + +length += 2 + LINK_SIZE; /* For final KET and END */ + +if ((options & PCRE_AUTO_CALLOUT) != 0) + length += 2 + 2*LINK_SIZE; /* For final callout */ + +if (length > MAX_PATTERN_SIZE) + { + *errorptr = ERR20; + return NULL; + } + +/* Compute the size of data block needed and get it, either from malloc or +externally provided function. */ + +size = length + sizeof(real_pcre) + name_count * (max_name_size + 3); +re = (real_pcre *)(pcre_malloc)(size); + +if (re == NULL) + { + *errorptr = ERR21; + return NULL; + } + +/* Put in the magic number, and save the sizes, options, and character table +pointer. NULL is used for the default character tables. The nullpad field is at +the end; it's there to help in the case when a regex compiled on a system with +4-byte pointers is run on another with 8-byte pointers. */ + +re->magic_number = MAGIC_NUMBER; +re->size = size; +re->options = options; +re->dummy1 = re->dummy2 = 0; +re->name_table_offset = sizeof(real_pcre); +re->name_entry_size = max_name_size + 3; +re->name_count = name_count; +re->tables = (tables == pcre_default_tables)? NULL : tables; +re->nullpad = NULL; + +/* The starting points of the name/number translation table and of the code are +passed around in the compile data block. */ + +compile_block.names_found = 0; +compile_block.name_entry_size = max_name_size + 3; +compile_block.name_table = (uschar *)re + re->name_table_offset; +codestart = compile_block.name_table + re->name_entry_size * re->name_count; +compile_block.start_code = codestart; +compile_block.start_pattern = (const uschar *)pattern; +compile_block.req_varyopt = 0; +compile_block.nopartial = FALSE; + +/* Set up a starting, non-extracting bracket, then compile the expression. On +error, *errorptr will be set non-NULL, so we don't need to look at the result +of the function here. */ + +ptr = (const uschar *)pattern; +code = (uschar *)codestart; +*code = OP_BRA; +bracount = 0; +(void)compile_regex(options, options & PCRE_IMS, &bracount, &code, &ptr, + errorptr, FALSE, 0, &firstbyte, &reqbyte, NULL, &compile_block); +re->top_bracket = bracount; +re->top_backref = compile_block.top_backref; + +if (compile_block.nopartial) re->options |= PCRE_NOPARTIAL; + +/* If not reached end of pattern on success, there's an excess bracket. */ + +if (*errorptr == NULL && *ptr != 0) *errorptr = ERR22; + +/* Fill in the terminating state and check for disastrous overflow, but +if debugging, leave the test till after things are printed out. */ + +*code++ = OP_END; + +#ifndef DEBUG +if (code - codestart > length) *errorptr = ERR23; +#endif + +/* Give an error if there's back reference to a non-existent capturing +subpattern. */ + +if (re->top_backref > re->top_bracket) *errorptr = ERR15; + +/* Failed to compile, or error while post-processing */ + +if (*errorptr != NULL) + { + (pcre_free)(re); + PCRE_ERROR_RETURN: + *erroroffset = ptr - (const uschar *)pattern; + return NULL; + } + +/* If the anchored option was not passed, set the flag if we can determine that +the pattern is anchored by virtue of ^ characters or \A or anything else (such +as starting with .* when DOTALL is set). + +Otherwise, if we know what the first character has to be, save it, because that +speeds up unanchored matches no end. If not, see if we can set the +PCRE_STARTLINE flag. This is helpful for multiline matches when all branches +start with ^. and also when all branches start with .* for non-DOTALL matches. +*/ + +if ((options & PCRE_ANCHORED) == 0) + { + int temp_options = options; + if (is_anchored(codestart, &temp_options, 0, compile_block.backref_map)) + re->options |= PCRE_ANCHORED; + else + { + if (firstbyte < 0) + firstbyte = find_firstassertedchar(codestart, &temp_options, FALSE); + if (firstbyte >= 0) /* Remove caseless flag for non-caseable chars */ + { + int ch = firstbyte & 255; + re->first_byte = ((firstbyte & REQ_CASELESS) != 0 && + compile_block.fcc[ch] == ch)? ch : firstbyte; + re->options |= PCRE_FIRSTSET; + } + else if (is_startline(codestart, 0, compile_block.backref_map)) + re->options |= PCRE_STARTLINE; + } + } + +/* For an anchored pattern, we use the "required byte" only if it follows a +variable length item in the regex. Remove the caseless flag for non-caseable +bytes. */ + +if (reqbyte >= 0 && + ((re->options & PCRE_ANCHORED) == 0 || (reqbyte & REQ_VARY) != 0)) + { + int ch = reqbyte & 255; + re->req_byte = ((reqbyte & REQ_CASELESS) != 0 && + compile_block.fcc[ch] == ch)? (reqbyte & ~REQ_CASELESS) : reqbyte; + re->options |= PCRE_REQCHSET; + } + +/* Print out the compiled data for debugging */ + +#ifdef DEBUG + +printf("Length = %d top_bracket = %d top_backref = %d\n", + length, re->top_bracket, re->top_backref); + +if (re->options != 0) + { + printf("%s%s%s%s%s%s%s%s%s%s\n", + ((re->options & PCRE_NOPARTIAL) != 0)? "nopartial " : "", + ((re->options & PCRE_ANCHORED) != 0)? "anchored " : "", + ((re->options & PCRE_CASELESS) != 0)? "caseless " : "", + ((re->options & PCRE_ICHANGED) != 0)? "case state changed " : "", + ((re->options & PCRE_EXTENDED) != 0)? "extended " : "", + ((re->options & PCRE_MULTILINE) != 0)? "multiline " : "", + ((re->options & PCRE_DOTALL) != 0)? "dotall " : "", + ((re->options & PCRE_DOLLAR_ENDONLY) != 0)? "endonly " : "", + ((re->options & PCRE_EXTRA) != 0)? "extra " : "", + ((re->options & PCRE_UNGREEDY) != 0)? "ungreedy " : ""); + } + +if ((re->options & PCRE_FIRSTSET) != 0) + { + int ch = re->first_byte & 255; + const char *caseless = ((re->first_byte & REQ_CASELESS) == 0)? "" : " (caseless)"; + if (isprint(ch)) printf("First char = %c%s\n", ch, caseless); + else printf("First char = \\x%02x%s\n", ch, caseless); + } + +if ((re->options & PCRE_REQCHSET) != 0) + { + int ch = re->req_byte & 255; + const char *caseless = ((re->req_byte & REQ_CASELESS) == 0)? "" : " (caseless)"; + if (isprint(ch)) printf("Req char = %c%s\n", ch, caseless); + else printf("Req char = \\x%02x%s\n", ch, caseless); + } + +print_internals(re, stdout); + +/* This check is done here in the debugging case so that the code that +was compiled can be seen. */ + +if (code - codestart > length) + { + *errorptr = ERR23; + (pcre_free)(re); + *erroroffset = ptr - (uschar *)pattern; + return NULL; + } +#endif + +return (pcre *)re; +} + + + +/************************************************* +* Match a back-reference * +*************************************************/ + +/* If a back reference hasn't been set, the length that is passed is greater +than the number of characters left in the string, so the match fails. + +Arguments: + offset index into the offset vector + eptr points into the subject + length length to be matched + md points to match data block + ims the ims flags + +Returns: TRUE if matched +*/ + +static BOOL +match_ref(int offset, register const uschar *eptr, int length, match_data *md, + unsigned long int ims) +{ +const uschar *p = md->start_subject + md->offset_vector[offset]; + +#ifdef DEBUG +if (eptr >= md->end_subject) + printf("matching subject "); +else + { + printf("matching subject "); + pchars(eptr, length, TRUE, md); + } +printf(" against backref "); +pchars(p, length, FALSE, md); +printf("\n"); +#endif + +/* Always fail if not enough characters left */ + +if (length > md->end_subject - eptr) return FALSE; + +/* Separate the caselesss case for speed */ + +if ((ims & PCRE_CASELESS) != 0) + { + while (length-- > 0) + if (md->lcc[*p++] != md->lcc[*eptr++]) return FALSE; + } +else + { while (length-- > 0) if (*p++ != *eptr++) return FALSE; } + +return TRUE; +} + + +#ifdef SUPPORT_UTF8 +/************************************************* +* Match character against an XCLASS * +*************************************************/ + +/* This function is called from within the XCLASS code below, to match a +character against an extended class which might match values > 255. + +Arguments: + c the character + data points to the flag byte of the XCLASS data + +Returns: TRUE if character matches, else FALSE +*/ + +static BOOL +match_xclass(int c, const uschar *data) +{ +int t; +BOOL negated = (*data & XCL_NOT) != 0; + +/* Character values < 256 are matched against a bitmap, if one is present. If +not, we still carry on, because there may be ranges that start below 256 in the +additional data. */ + +if (c < 256) + { + if ((*data & XCL_MAP) != 0 && (data[1 + c/8] & (1 << (c&7))) != 0) + return !negated; /* char found */ + } + +/* First skip the bit map if present. Then match against the list of Unicode +properties or large chars or ranges that end with a large char. We won't ever +encounter XCL_PROP or XCL_NOTPROP when UCP support is not compiled. */ + +if ((*data++ & XCL_MAP) != 0) data += 32; + +while ((t = *data++) != XCL_END) + { + int x, y; + if (t == XCL_SINGLE) + { + GETCHARINC(x, data); + if (c == x) return !negated; + } + else if (t == XCL_RANGE) + { + GETCHARINC(x, data); + GETCHARINC(y, data); + if (c >= x && c <= y) return !negated; + } + +#ifdef SUPPORT_UCP + else /* XCL_PROP & XCL_NOTPROP */ + { + int chartype, othercase; + int rqdtype = *data++; + int category = ucp_findchar(c, &chartype, &othercase); + if (rqdtype >= 128) + { + if ((rqdtype - 128 == category) == (t == XCL_PROP)) return !negated; + } + else + { + if ((rqdtype == chartype) == (t == XCL_PROP)) return !negated; + } + } +#endif /* SUPPORT_UCP */ + } + +return negated; /* char did not match */ +} +#endif + + +/*************************************************************************** +**************************************************************************** + RECURSION IN THE match() FUNCTION + +The match() function is highly recursive. Some regular expressions can cause +it to recurse thousands of times. I was writing for Unix, so I just let it +call itself recursively. This uses the stack for saving everything that has +to be saved for a recursive call. On Unix, the stack can be large, and this +works fine. + +It turns out that on non-Unix systems there are problems with programs that +use a lot of stack. (This despite the fact that every last chip has oodles +of memory these days, and techniques for extending the stack have been known +for decades.) So.... + +There is a fudge, triggered by defining NO_RECURSE, which avoids recursive +calls by keeping local variables that need to be preserved in blocks of memory +obtained from malloc instead instead of on the stack. Macros are used to +achieve this so that the actual code doesn't look very different to what it +always used to. +**************************************************************************** +***************************************************************************/ + + +/* These versions of the macros use the stack, as normal */ + +#ifndef NO_RECURSE +#define REGISTER register +#define RMATCH(rx,ra,rb,rc,rd,re,rf,rg) rx = match(ra,rb,rc,rd,re,rf,rg) +#define RRETURN(ra) return ra +#else + + +/* These versions of the macros manage a private stack on the heap. Note +that the rd argument of RMATCH isn't actually used. It's the md argument of +match(), which never changes. */ + +#define REGISTER + +#define RMATCH(rx,ra,rb,rc,rd,re,rf,rg)\ + {\ + heapframe *newframe = (pcre_stack_malloc)(sizeof(heapframe));\ + if (setjmp(frame->Xwhere) == 0)\ + {\ + newframe->Xeptr = ra;\ + newframe->Xecode = rb;\ + newframe->Xoffset_top = rc;\ + newframe->Xims = re;\ + newframe->Xeptrb = rf;\ + newframe->Xflags = rg;\ + newframe->Xprevframe = frame;\ + frame = newframe;\ + DPRINTF(("restarting from line %d\n", __LINE__));\ + goto HEAP_RECURSE;\ + }\ + else\ + {\ + DPRINTF(("longjumped back to line %d\n", __LINE__));\ + frame = md->thisframe;\ + rx = frame->Xresult;\ + }\ + } + +#define RRETURN(ra)\ + {\ + heapframe *newframe = frame;\ + frame = newframe->Xprevframe;\ + (pcre_stack_free)(newframe);\ + if (frame != NULL)\ + {\ + frame->Xresult = ra;\ + md->thisframe = frame;\ + longjmp(frame->Xwhere, 1);\ + }\ + return ra;\ + } + + +/* Structure for remembering the local variables in a private frame */ + +typedef struct heapframe { + struct heapframe *Xprevframe; + + /* Function arguments that may change */ + + const uschar *Xeptr; + const uschar *Xecode; + int Xoffset_top; + long int Xims; + eptrblock *Xeptrb; + int Xflags; + + /* Function local variables */ + + const uschar *Xcallpat; + const uschar *Xcharptr; + const uschar *Xdata; + const uschar *Xnext; + const uschar *Xpp; + const uschar *Xprev; + const uschar *Xsaved_eptr; + + recursion_info Xnew_recursive; + + BOOL Xcur_is_word; + BOOL Xcondition; + BOOL Xminimize; + BOOL Xprev_is_word; + + unsigned long int Xoriginal_ims; + +#ifdef SUPPORT_UCP + int Xprop_type; + int Xprop_fail_result; + int Xprop_category; + int Xprop_chartype; + int Xprop_othercase; + int Xprop_test_against; + int *Xprop_test_variable; +#endif + + int Xctype; + int Xfc; + int Xfi; + int Xlength; + int Xmax; + int Xmin; + int Xnumber; + int Xoffset; + int Xop; + int Xsave_capture_last; + int Xsave_offset1, Xsave_offset2, Xsave_offset3; + int Xstacksave[REC_STACK_SAVE_MAX]; + + eptrblock Xnewptrb; + + /* Place to pass back result, and where to jump back to */ + + int Xresult; + jmp_buf Xwhere; + +} heapframe; + +#endif + + +/*************************************************************************** +***************************************************************************/ + + + +/************************************************* +* Match from current position * +*************************************************/ + +/* On entry ecode points to the first opcode, and eptr to the first character +in the subject string, while eptrb holds the value of eptr at the start of the +last bracketed group - used for breaking infinite loops matching zero-length +strings. This function is called recursively in many circumstances. Whenever it +returns a negative (error) response, the outer incarnation must also return the +same response. + +Performance note: It might be tempting to extract commonly used fields from the +md structure (e.g. utf8, end_subject) into individual variables to improve +performance. Tests using gcc on a SPARC disproved this; in the first case, it +made performance worse. + +Arguments: + eptr pointer in subject + ecode position in code + offset_top current top pointer + md pointer to "static" info for the match + ims current /i, /m, and /s options + eptrb pointer to chain of blocks containing eptr at start of + brackets - for testing for empty matches + flags can contain + match_condassert - this is an assertion condition + match_isgroup - this is the start of a bracketed group + +Returns: MATCH_MATCH if matched ) these values are >= 0 + MATCH_NOMATCH if failed to match ) + a negative PCRE_ERROR_xxx value if aborted by an error condition + (e.g. stopped by recursion limit) +*/ + +static int +match(REGISTER const uschar *eptr, REGISTER const uschar *ecode, + int offset_top, match_data *md, unsigned long int ims, eptrblock *eptrb, + int flags) +{ +/* These variables do not need to be preserved over recursion in this function, +so they can be ordinary variables in all cases. Mark them with "register" +because they are used a lot in loops. */ + +register int rrc; /* Returns from recursive calls */ +register int i; /* Used for loops not involving calls to RMATCH() */ +register int c; /* Character values not kept over RMATCH() calls */ + +/* When recursion is not being used, all "local" variables that have to be +preserved over calls to RMATCH() are part of a "frame" which is obtained from +heap storage. Set up the top-level frame here; others are obtained from the +heap whenever RMATCH() does a "recursion". See the macro definitions above. */ + +#ifdef NO_RECURSE +heapframe *frame = (pcre_stack_malloc)(sizeof(heapframe)); +frame->Xprevframe = NULL; /* Marks the top level */ + +/* Copy in the original argument variables */ + +frame->Xeptr = eptr; +frame->Xecode = ecode; +frame->Xoffset_top = offset_top; +frame->Xims = ims; +frame->Xeptrb = eptrb; +frame->Xflags = flags; + +/* This is where control jumps back to to effect "recursion" */ + +HEAP_RECURSE: + +/* Macros make the argument variables come from the current frame */ + +#define eptr frame->Xeptr +#define ecode frame->Xecode +#define offset_top frame->Xoffset_top +#define ims frame->Xims +#define eptrb frame->Xeptrb +#define flags frame->Xflags + +/* Ditto for the local variables */ + +#ifdef SUPPORT_UTF8 +#define charptr frame->Xcharptr +#endif +#define callpat frame->Xcallpat +#define data frame->Xdata +#define next frame->Xnext +#define pp frame->Xpp +#define prev frame->Xprev +#define saved_eptr frame->Xsaved_eptr + +#define new_recursive frame->Xnew_recursive + +#define cur_is_word frame->Xcur_is_word +#define condition frame->Xcondition +#define minimize frame->Xminimize +#define prev_is_word frame->Xprev_is_word + +#define original_ims frame->Xoriginal_ims + +#ifdef SUPPORT_UCP +#define prop_type frame->Xprop_type +#define prop_fail_result frame->Xprop_fail_result +#define prop_category frame->Xprop_category +#define prop_chartype frame->Xprop_chartype +#define prop_othercase frame->Xprop_othercase +#define prop_test_against frame->Xprop_test_against +#define prop_test_variable frame->Xprop_test_variable +#endif + +#define ctype frame->Xctype +#define fc frame->Xfc +#define fi frame->Xfi +#define length frame->Xlength +#define max frame->Xmax +#define min frame->Xmin +#define number frame->Xnumber +#define offset frame->Xoffset +#define op frame->Xop +#define save_capture_last frame->Xsave_capture_last +#define save_offset1 frame->Xsave_offset1 +#define save_offset2 frame->Xsave_offset2 +#define save_offset3 frame->Xsave_offset3 +#define stacksave frame->Xstacksave + +#define newptrb frame->Xnewptrb + +/* When recursion is being used, local variables are allocated on the stack and +get preserved during recursion in the normal way. In this environment, fi and +i, and fc and c, can be the same variables. */ + +#else +#define fi i +#define fc c + + +#ifdef SUPPORT_UTF8 /* Many of these variables are used ony */ +const uschar *charptr; /* small blocks of the code. My normal */ +#endif /* style of coding would have declared */ +const uschar *callpat; /* them within each of those blocks. */ +const uschar *data; /* However, in order to accommodate the */ +const uschar *next; /* version of this code that uses an */ +const uschar *pp; /* external "stack" implemented on the */ +const uschar *prev; /* heap, it is easier to declare them */ +const uschar *saved_eptr; /* all here, so the declarations can */ + /* be cut out in a block. The only */ +recursion_info new_recursive; /* declarations within blocks below are */ + /* for variables that do not have to */ +BOOL cur_is_word; /* be preserved over a recursive call */ +BOOL condition; /* to RMATCH(). */ +BOOL minimize; +BOOL prev_is_word; + +unsigned long int original_ims; + +#ifdef SUPPORT_UCP +int prop_type; +int prop_fail_result; +int prop_category; +int prop_chartype; +int prop_othercase; +int prop_test_against; +int *prop_test_variable; +#endif + +int ctype; +int length; +int max; +int min; +int number; +int offset; +int op; +int save_capture_last; +int save_offset1, save_offset2, save_offset3; +int stacksave[REC_STACK_SAVE_MAX]; + +eptrblock newptrb; +#endif + +/* These statements are here to stop the compiler complaining about unitialized +variables. */ + +#ifdef SUPPORT_UCP +prop_fail_result = 0; +prop_test_against = 0; +prop_test_variable = NULL; +#endif + +/* OK, now we can get on with the real code of the function. Recursion is +specified by the macros RMATCH and RRETURN. When NO_RECURSE is *not* defined, +these just turn into a recursive call to match() and a "return", respectively. +However, RMATCH isn't like a function call because it's quite a complicated +macro. It has to be used in one particular way. This shouldn't, however, impact +performance when true recursion is being used. */ + +if (md->match_call_count++ >= md->match_limit) RRETURN(PCRE_ERROR_MATCHLIMIT); + +original_ims = ims; /* Save for resetting on ')' */ + +/* At the start of a bracketed group, add the current subject pointer to the +stack of such pointers, to be re-instated at the end of the group when we hit +the closing ket. When match() is called in other circumstances, we don't add to +this stack. */ + +if ((flags & match_isgroup) != 0) + { + newptrb.epb_prev = eptrb; + newptrb.epb_saved_eptr = eptr; + eptrb = &newptrb; + } + +/* Now start processing the operations. */ + +for (;;) + { + op = *ecode; + minimize = FALSE; + + /* For partial matching, remember if we ever hit the end of the subject after + matching at least one subject character. */ + + if (md->partial && + eptr >= md->end_subject && + eptr > md->start_match) + md->hitend = TRUE; + + /* Opening capturing bracket. If there is space in the offset vector, save + the current subject position in the working slot at the top of the vector. We + mustn't change the current values of the data slot, because they may be set + from a previous iteration of this group, and be referred to by a reference + inside the group. + + If the bracket fails to match, we need to restore this value and also the + values of the final offsets, in case they were set by a previous iteration of + the same bracket. + + If there isn't enough space in the offset vector, treat this as if it were a + non-capturing bracket. Don't worry about setting the flag for the error case + here; that is handled in the code for KET. */ + + if (op > OP_BRA) + { + number = op - OP_BRA; + + /* For extended extraction brackets (large number), we have to fish out the + number from a dummy opcode at the start. */ + + if (number > EXTRACT_BASIC_MAX) + number = GET2(ecode, 2+LINK_SIZE); + offset = number << 1; + +#ifdef DEBUG + printf("start bracket %d subject=", number); + pchars(eptr, 16, TRUE, md); + printf("\n"); +#endif + + if (offset < md->offset_max) + { + save_offset1 = md->offset_vector[offset]; + save_offset2 = md->offset_vector[offset+1]; + save_offset3 = md->offset_vector[md->offset_end - number]; + save_capture_last = md->capture_last; + + DPRINTF(("saving %d %d %d\n", save_offset1, save_offset2, save_offset3)); + md->offset_vector[md->offset_end - number] = eptr - md->start_subject; + + do + { + RMATCH(rrc, eptr, ecode + 1 + LINK_SIZE, offset_top, md, ims, eptrb, + match_isgroup); + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + md->capture_last = save_capture_last; + ecode += GET(ecode, 1); + } + while (*ecode == OP_ALT); + + DPRINTF(("bracket %d failed\n", number)); + + md->offset_vector[offset] = save_offset1; + md->offset_vector[offset+1] = save_offset2; + md->offset_vector[md->offset_end - number] = save_offset3; + + RRETURN(MATCH_NOMATCH); + } + + /* Insufficient room for saving captured contents */ + + else op = OP_BRA; + } + + /* Other types of node can be handled by a switch */ + + switch(op) + { + case OP_BRA: /* Non-capturing bracket: optimized */ + DPRINTF(("start bracket 0\n")); + do + { + RMATCH(rrc, eptr, ecode + 1 + LINK_SIZE, offset_top, md, ims, eptrb, + match_isgroup); + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + ecode += GET(ecode, 1); + } + while (*ecode == OP_ALT); + DPRINTF(("bracket 0 failed\n")); + RRETURN(MATCH_NOMATCH); + + /* Conditional group: compilation checked that there are no more than + two branches. If the condition is false, skipping the first branch takes us + past the end if there is only one branch, but that's OK because that is + exactly what going to the ket would do. */ + + case OP_COND: + if (ecode[LINK_SIZE+1] == OP_CREF) /* Condition extract or recurse test */ + { + offset = GET2(ecode, LINK_SIZE+2) << 1; /* Doubled ref number */ + condition = (offset == CREF_RECURSE * 2)? + (md->recursive != NULL) : + (offset < offset_top && md->offset_vector[offset] >= 0); + RMATCH(rrc, eptr, ecode + (condition? + (LINK_SIZE + 4) : (LINK_SIZE + 1 + GET(ecode, 1))), + offset_top, md, ims, eptrb, match_isgroup); + RRETURN(rrc); + } + + /* The condition is an assertion. Call match() to evaluate it - setting + the final argument TRUE causes it to stop at the end of an assertion. */ + + else + { + RMATCH(rrc, eptr, ecode + 1 + LINK_SIZE, offset_top, md, ims, NULL, + match_condassert | match_isgroup); + if (rrc == MATCH_MATCH) + { + ecode += 1 + LINK_SIZE + GET(ecode, LINK_SIZE+2); + while (*ecode == OP_ALT) ecode += GET(ecode, 1); + } + else if (rrc != MATCH_NOMATCH) + { + RRETURN(rrc); /* Need braces because of following else */ + } + else ecode += GET(ecode, 1); + RMATCH(rrc, eptr, ecode + 1 + LINK_SIZE, offset_top, md, ims, eptrb, + match_isgroup); + RRETURN(rrc); + } + /* Control never reaches here */ + + /* Skip over conditional reference or large extraction number data if + encountered. */ + + case OP_CREF: + case OP_BRANUMBER: + ecode += 3; + break; + + /* End of the pattern. If we are in a recursion, we should restore the + offsets appropriately and continue from after the call. */ + + case OP_END: + if (md->recursive != NULL && md->recursive->group_num == 0) + { + recursion_info *rec = md->recursive; + DPRINTF(("Hit the end in a (?0) recursion\n")); + md->recursive = rec->prevrec; + memmove(md->offset_vector, rec->offset_save, + rec->saved_max * sizeof(int)); + md->start_match = rec->save_start; + ims = original_ims; + ecode = rec->after_call; + break; + } + + /* Otherwise, if PCRE_NOTEMPTY is set, fail if we have matched an empty + string - backtracking will then try other alternatives, if any. */ + + if (md->notempty && eptr == md->start_match) RRETURN(MATCH_NOMATCH); + md->end_match_ptr = eptr; /* Record where we ended */ + md->end_offset_top = offset_top; /* and how many extracts were taken */ + RRETURN(MATCH_MATCH); + + /* Change option settings */ + + case OP_OPT: + ims = ecode[1]; + ecode += 2; + DPRINTF(("ims set to %02lx\n", ims)); + break; + + /* Assertion brackets. Check the alternative branches in turn - the + matching won't pass the KET for an assertion. If any one branch matches, + the assertion is true. Lookbehind assertions have an OP_REVERSE item at the + start of each branch to move the current point backwards, so the code at + this level is identical to the lookahead case. */ + + case OP_ASSERT: + case OP_ASSERTBACK: + do + { + RMATCH(rrc, eptr, ecode + 1 + LINK_SIZE, offset_top, md, ims, NULL, + match_isgroup); + if (rrc == MATCH_MATCH) break; + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + ecode += GET(ecode, 1); + } + while (*ecode == OP_ALT); + if (*ecode == OP_KET) RRETURN(MATCH_NOMATCH); + + /* If checking an assertion for a condition, return MATCH_MATCH. */ + + if ((flags & match_condassert) != 0) RRETURN(MATCH_MATCH); + + /* Continue from after the assertion, updating the offsets high water + mark, since extracts may have been taken during the assertion. */ + + do ecode += GET(ecode,1); while (*ecode == OP_ALT); + ecode += 1 + LINK_SIZE; + offset_top = md->end_offset_top; + continue; + + /* Negative assertion: all branches must fail to match */ + + case OP_ASSERT_NOT: + case OP_ASSERTBACK_NOT: + do + { + RMATCH(rrc, eptr, ecode + 1 + LINK_SIZE, offset_top, md, ims, NULL, + match_isgroup); + if (rrc == MATCH_MATCH) RRETURN(MATCH_NOMATCH); + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + ecode += GET(ecode,1); + } + while (*ecode == OP_ALT); + + if ((flags & match_condassert) != 0) RRETURN(MATCH_MATCH); + + ecode += 1 + LINK_SIZE; + continue; + + /* Move the subject pointer back. This occurs only at the start of + each branch of a lookbehind assertion. If we are too close to the start to + move back, this match function fails. When working with UTF-8 we move + back a number of characters, not bytes. */ + + case OP_REVERSE: +#ifdef SUPPORT_UTF8 + if (md->utf8) + { + c = GET(ecode,1); + for (i = 0; i < c; i++) + { + eptr--; + if (eptr < md->start_subject) RRETURN(MATCH_NOMATCH); + BACKCHAR(eptr) + } + } + else +#endif + + /* No UTF-8 support, or not in UTF-8 mode: count is byte count */ + + { + eptr -= GET(ecode,1); + if (eptr < md->start_subject) RRETURN(MATCH_NOMATCH); + } + + /* Skip to next op code */ + + ecode += 1 + LINK_SIZE; + break; + + /* The callout item calls an external function, if one is provided, passing + details of the match so far. This is mainly for debugging, though the + function is able to force a failure. */ + + case OP_CALLOUT: + if (pcre_callout != NULL) + { + pcre_callout_block cb; + cb.version = 1; /* Version 1 of the callout block */ + cb.callout_number = ecode[1]; + cb.offset_vector = md->offset_vector; + cb.subject = (const char *)md->start_subject; + cb.subject_length = md->end_subject - md->start_subject; + cb.start_match = md->start_match - md->start_subject; + cb.current_position = eptr - md->start_subject; + cb.pattern_position = GET(ecode, 2); + cb.next_item_length = GET(ecode, 2 + LINK_SIZE); + cb.capture_top = offset_top/2; + cb.capture_last = md->capture_last; + cb.callout_data = md->callout_data; + if ((rrc = (*pcre_callout)(&cb)) > 0) RRETURN(MATCH_NOMATCH); + if (rrc < 0) RRETURN(rrc); + } + ecode += 2 + 2*LINK_SIZE; + break; + + /* Recursion either matches the current regex, or some subexpression. The + offset data is the offset to the starting bracket from the start of the + whole pattern. (This is so that it works from duplicated subpatterns.) + + If there are any capturing brackets started but not finished, we have to + save their starting points and reinstate them after the recursion. However, + we don't know how many such there are (offset_top records the completed + total) so we just have to save all the potential data. There may be up to + 65535 such values, which is too large to put on the stack, but using malloc + for small numbers seems expensive. As a compromise, the stack is used when + there are no more than REC_STACK_SAVE_MAX values to store; otherwise malloc + is used. A problem is what to do if the malloc fails ... there is no way of + returning to the top level with an error. Save the top REC_STACK_SAVE_MAX + values on the stack, and accept that the rest may be wrong. + + There are also other values that have to be saved. We use a chained + sequence of blocks that actually live on the stack. Thanks to Robin Houston + for the original version of this logic. */ + + case OP_RECURSE: + { + callpat = md->start_code + GET(ecode, 1); + new_recursive.group_num = *callpat - OP_BRA; + + /* For extended extraction brackets (large number), we have to fish out + the number from a dummy opcode at the start. */ + + if (new_recursive.group_num > EXTRACT_BASIC_MAX) + new_recursive.group_num = GET2(callpat, 2+LINK_SIZE); + + /* Add to "recursing stack" */ + + new_recursive.prevrec = md->recursive; + md->recursive = &new_recursive; + + /* Find where to continue from afterwards */ + + ecode += 1 + LINK_SIZE; + new_recursive.after_call = ecode; + + /* Now save the offset data. */ + + new_recursive.saved_max = md->offset_end; + if (new_recursive.saved_max <= REC_STACK_SAVE_MAX) + new_recursive.offset_save = stacksave; + else + { + new_recursive.offset_save = + (int *)(pcre_malloc)(new_recursive.saved_max * sizeof(int)); + if (new_recursive.offset_save == NULL) RRETURN(PCRE_ERROR_NOMEMORY); + } + + memcpy(new_recursive.offset_save, md->offset_vector, + new_recursive.saved_max * sizeof(int)); + new_recursive.save_start = md->start_match; + md->start_match = eptr; + + /* OK, now we can do the recursion. For each top-level alternative we + restore the offset and recursion data. */ + + DPRINTF(("Recursing into group %d\n", new_recursive.group_num)); + do + { + RMATCH(rrc, eptr, callpat + 1 + LINK_SIZE, offset_top, md, ims, + eptrb, match_isgroup); + if (rrc == MATCH_MATCH) + { + md->recursive = new_recursive.prevrec; + if (new_recursive.offset_save != stacksave) + (pcre_free)(new_recursive.offset_save); + RRETURN(MATCH_MATCH); + } + else if (rrc != MATCH_NOMATCH) RRETURN(rrc); + + md->recursive = &new_recursive; + memcpy(md->offset_vector, new_recursive.offset_save, + new_recursive.saved_max * sizeof(int)); + callpat += GET(callpat, 1); + } + while (*callpat == OP_ALT); + + DPRINTF(("Recursion didn't match\n")); + md->recursive = new_recursive.prevrec; + if (new_recursive.offset_save != stacksave) + (pcre_free)(new_recursive.offset_save); + RRETURN(MATCH_NOMATCH); + } + /* Control never reaches here */ + + /* "Once" brackets are like assertion brackets except that after a match, + the point in the subject string is not moved back. Thus there can never be + a move back into the brackets. Friedl calls these "atomic" subpatterns. + Check the alternative branches in turn - the matching won't pass the KET + for this kind of subpattern. If any one branch matches, we carry on as at + the end of a normal bracket, leaving the subject pointer. */ + + case OP_ONCE: + { + prev = ecode; + saved_eptr = eptr; + + do + { + RMATCH(rrc, eptr, ecode + 1 + LINK_SIZE, offset_top, md, ims, + eptrb, match_isgroup); + if (rrc == MATCH_MATCH) break; + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + ecode += GET(ecode,1); + } + while (*ecode == OP_ALT); + + /* If hit the end of the group (which could be repeated), fail */ + + if (*ecode != OP_ONCE && *ecode != OP_ALT) RRETURN(MATCH_NOMATCH); + + /* Continue as from after the assertion, updating the offsets high water + mark, since extracts may have been taken. */ + + do ecode += GET(ecode,1); while (*ecode == OP_ALT); + + offset_top = md->end_offset_top; + eptr = md->end_match_ptr; + + /* For a non-repeating ket, just continue at this level. This also + happens for a repeating ket if no characters were matched in the group. + This is the forcible breaking of infinite loops as implemented in Perl + 5.005. If there is an options reset, it will get obeyed in the normal + course of events. */ + + if (*ecode == OP_KET || eptr == saved_eptr) + { + ecode += 1+LINK_SIZE; + break; + } + + /* The repeating kets try the rest of the pattern or restart from the + preceding bracket, in the appropriate order. We need to reset any options + that changed within the bracket before re-running it, so check the next + opcode. */ + + if (ecode[1+LINK_SIZE] == OP_OPT) + { + ims = (ims & ~PCRE_IMS) | ecode[4]; + DPRINTF(("ims set to %02lx at group repeat\n", ims)); + } + + if (*ecode == OP_KETRMIN) + { + RMATCH(rrc, eptr, ecode + 1 + LINK_SIZE, offset_top, md, ims, eptrb, 0); + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + RMATCH(rrc, eptr, prev, offset_top, md, ims, eptrb, match_isgroup); + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + } + else /* OP_KETRMAX */ + { + RMATCH(rrc, eptr, prev, offset_top, md, ims, eptrb, match_isgroup); + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + RMATCH(rrc, eptr, ecode + 1+LINK_SIZE, offset_top, md, ims, eptrb, 0); + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + } + } + RRETURN(MATCH_NOMATCH); + + /* An alternation is the end of a branch; scan along to find the end of the + bracketed group and go to there. */ + + case OP_ALT: + do ecode += GET(ecode,1); while (*ecode == OP_ALT); + break; + + /* BRAZERO and BRAMINZERO occur just before a bracket group, indicating + that it may occur zero times. It may repeat infinitely, or not at all - + i.e. it could be ()* or ()? in the pattern. Brackets with fixed upper + repeat limits are compiled as a number of copies, with the optional ones + preceded by BRAZERO or BRAMINZERO. */ + + case OP_BRAZERO: + { + next = ecode+1; + RMATCH(rrc, eptr, next, offset_top, md, ims, eptrb, match_isgroup); + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + do next += GET(next,1); while (*next == OP_ALT); + ecode = next + 1+LINK_SIZE; + } + break; + + case OP_BRAMINZERO: + { + next = ecode+1; + do next += GET(next,1); while (*next == OP_ALT); + RMATCH(rrc, eptr, next + 1+LINK_SIZE, offset_top, md, ims, eptrb, + match_isgroup); + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + ecode++; + } + break; + + /* End of a group, repeated or non-repeating. If we are at the end of + an assertion "group", stop matching and return MATCH_MATCH, but record the + current high water mark for use by positive assertions. Do this also + for the "once" (not-backup up) groups. */ + + case OP_KET: + case OP_KETRMIN: + case OP_KETRMAX: + { + prev = ecode - GET(ecode, 1); + saved_eptr = eptrb->epb_saved_eptr; + + /* Back up the stack of bracket start pointers. */ + + eptrb = eptrb->epb_prev; + + if (*prev == OP_ASSERT || *prev == OP_ASSERT_NOT || + *prev == OP_ASSERTBACK || *prev == OP_ASSERTBACK_NOT || + *prev == OP_ONCE) + { + md->end_match_ptr = eptr; /* For ONCE */ + md->end_offset_top = offset_top; + RRETURN(MATCH_MATCH); + } + + /* In all other cases except a conditional group we have to check the + group number back at the start and if necessary complete handling an + extraction by setting the offsets and bumping the high water mark. */ + + if (*prev != OP_COND) + { + number = *prev - OP_BRA; + + /* For extended extraction brackets (large number), we have to fish out + the number from a dummy opcode at the start. */ + + if (number > EXTRACT_BASIC_MAX) number = GET2(prev, 2+LINK_SIZE); + offset = number << 1; + +#ifdef DEBUG + printf("end bracket %d", number); + printf("\n"); +#endif + + /* Test for a numbered group. This includes groups called as a result + of recursion. Note that whole-pattern recursion is coded as a recurse + into group 0, so it won't be picked up here. Instead, we catch it when + the OP_END is reached. */ + + if (number > 0) + { + md->capture_last = number; + if (offset >= md->offset_max) md->offset_overflow = TRUE; else + { + md->offset_vector[offset] = + md->offset_vector[md->offset_end - number]; + md->offset_vector[offset+1] = eptr - md->start_subject; + if (offset_top <= offset) offset_top = offset + 2; + } + + /* Handle a recursively called group. Restore the offsets + appropriately and continue from after the call. */ + + if (md->recursive != NULL && md->recursive->group_num == number) + { + recursion_info *rec = md->recursive; + DPRINTF(("Recursion (%d) succeeded - continuing\n", number)); + md->recursive = rec->prevrec; + md->start_match = rec->save_start; + memcpy(md->offset_vector, rec->offset_save, + rec->saved_max * sizeof(int)); + ecode = rec->after_call; + ims = original_ims; + break; + } + } + } + + /* Reset the value of the ims flags, in case they got changed during + the group. */ + + ims = original_ims; + DPRINTF(("ims reset to %02lx\n", ims)); + + /* For a non-repeating ket, just continue at this level. This also + happens for a repeating ket if no characters were matched in the group. + This is the forcible breaking of infinite loops as implemented in Perl + 5.005. If there is an options reset, it will get obeyed in the normal + course of events. */ + + if (*ecode == OP_KET || eptr == saved_eptr) + { + ecode += 1 + LINK_SIZE; + break; + } + + /* The repeating kets try the rest of the pattern or restart from the + preceding bracket, in the appropriate order. */ + + if (*ecode == OP_KETRMIN) + { + RMATCH(rrc, eptr, ecode + 1+LINK_SIZE, offset_top, md, ims, eptrb, 0); + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + RMATCH(rrc, eptr, prev, offset_top, md, ims, eptrb, match_isgroup); + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + } + else /* OP_KETRMAX */ + { + RMATCH(rrc, eptr, prev, offset_top, md, ims, eptrb, match_isgroup); + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + RMATCH(rrc, eptr, ecode + 1+LINK_SIZE, offset_top, md, ims, eptrb, 0); + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + } + } + + RRETURN(MATCH_NOMATCH); + + /* Start of subject unless notbol, or after internal newline if multiline */ + + case OP_CIRC: + if (md->notbol && eptr == md->start_subject) RRETURN(MATCH_NOMATCH); + if ((ims & PCRE_MULTILINE) != 0) + { + if (eptr != md->start_subject && eptr[-1] != NEWLINE) + RRETURN(MATCH_NOMATCH); + ecode++; + break; + } + /* ... else fall through */ + + /* Start of subject assertion */ + + case OP_SOD: + if (eptr != md->start_subject) RRETURN(MATCH_NOMATCH); + ecode++; + break; + + /* Start of match assertion */ + + case OP_SOM: + if (eptr != md->start_subject + md->start_offset) RRETURN(MATCH_NOMATCH); + ecode++; + break; + + /* Assert before internal newline if multiline, or before a terminating + newline unless endonly is set, else end of subject unless noteol is set. */ + + case OP_DOLL: + if ((ims & PCRE_MULTILINE) != 0) + { + if (eptr < md->end_subject) + { if (*eptr != NEWLINE) RRETURN(MATCH_NOMATCH); } + else + { if (md->noteol) RRETURN(MATCH_NOMATCH); } + ecode++; + break; + } + else + { + if (md->noteol) RRETURN(MATCH_NOMATCH); + if (!md->endonly) + { + if (eptr < md->end_subject - 1 || + (eptr == md->end_subject - 1 && *eptr != NEWLINE)) + RRETURN(MATCH_NOMATCH); + ecode++; + break; + } + } + /* ... else fall through */ + + /* End of subject assertion (\z) */ + + case OP_EOD: + if (eptr < md->end_subject) RRETURN(MATCH_NOMATCH); + ecode++; + break; + + /* End of subject or ending \n assertion (\Z) */ + + case OP_EODN: + if (eptr < md->end_subject - 1 || + (eptr == md->end_subject - 1 && *eptr != NEWLINE)) RRETURN(MATCH_NOMATCH); + ecode++; + break; + + /* Word boundary assertions */ + + case OP_NOT_WORD_BOUNDARY: + case OP_WORD_BOUNDARY: + { + + /* Find out if the previous and current characters are "word" characters. + It takes a bit more work in UTF-8 mode. Characters > 255 are assumed to + be "non-word" characters. */ + +#ifdef SUPPORT_UTF8 + if (md->utf8) + { + if (eptr == md->start_subject) prev_is_word = FALSE; else + { + const uschar *lastptr = eptr - 1; + while((*lastptr & 0xc0) == 0x80) lastptr--; + GETCHAR(c, lastptr); + prev_is_word = c < 256 && (md->ctypes[c] & ctype_word) != 0; + } + if (eptr >= md->end_subject) cur_is_word = FALSE; else + { + GETCHAR(c, eptr); + cur_is_word = c < 256 && (md->ctypes[c] & ctype_word) != 0; + } + } + else +#endif + + /* More streamlined when not in UTF-8 mode */ + + { + prev_is_word = (eptr != md->start_subject) && + ((md->ctypes[eptr[-1]] & ctype_word) != 0); + cur_is_word = (eptr < md->end_subject) && + ((md->ctypes[*eptr] & ctype_word) != 0); + } + + /* Now see if the situation is what we want */ + + if ((*ecode++ == OP_WORD_BOUNDARY)? + cur_is_word == prev_is_word : cur_is_word != prev_is_word) + RRETURN(MATCH_NOMATCH); + } + break; + + /* Match a single character type; inline for speed */ + + case OP_ANY: + if ((ims & PCRE_DOTALL) == 0 && eptr < md->end_subject && *eptr == NEWLINE) + RRETURN(MATCH_NOMATCH); + if (eptr++ >= md->end_subject) RRETURN(MATCH_NOMATCH); +#ifdef SUPPORT_UTF8 + if (md->utf8) + while (eptr < md->end_subject && (*eptr & 0xc0) == 0x80) eptr++; +#endif + ecode++; + break; + + /* Match a single byte, even in UTF-8 mode. This opcode really does match + any byte, even newline, independent of the setting of PCRE_DOTALL. */ + + case OP_ANYBYTE: + if (eptr++ >= md->end_subject) RRETURN(MATCH_NOMATCH); + ecode++; + break; + + case OP_NOT_DIGIT: + if (eptr >= md->end_subject) RRETURN(MATCH_NOMATCH); + GETCHARINCTEST(c, eptr); + if ( +#ifdef SUPPORT_UTF8 + c < 256 && +#endif + (md->ctypes[c] & ctype_digit) != 0 + ) + RRETURN(MATCH_NOMATCH); + ecode++; + break; + + case OP_DIGIT: + if (eptr >= md->end_subject) RRETURN(MATCH_NOMATCH); + GETCHARINCTEST(c, eptr); + if ( +#ifdef SUPPORT_UTF8 + c >= 256 || +#endif + (md->ctypes[c] & ctype_digit) == 0 + ) + RRETURN(MATCH_NOMATCH); + ecode++; + break; + + case OP_NOT_WHITESPACE: + if (eptr >= md->end_subject) RRETURN(MATCH_NOMATCH); + GETCHARINCTEST(c, eptr); + if ( +#ifdef SUPPORT_UTF8 + c < 256 && +#endif + (md->ctypes[c] & ctype_space) != 0 + ) + RRETURN(MATCH_NOMATCH); + ecode++; + break; + + case OP_WHITESPACE: + if (eptr >= md->end_subject) RRETURN(MATCH_NOMATCH); + GETCHARINCTEST(c, eptr); + if ( +#ifdef SUPPORT_UTF8 + c >= 256 || +#endif + (md->ctypes[c] & ctype_space) == 0 + ) + RRETURN(MATCH_NOMATCH); + ecode++; + break; + + case OP_NOT_WORDCHAR: + if (eptr >= md->end_subject) RRETURN(MATCH_NOMATCH); + GETCHARINCTEST(c, eptr); + if ( +#ifdef SUPPORT_UTF8 + c < 256 && +#endif + (md->ctypes[c] & ctype_word) != 0 + ) + RRETURN(MATCH_NOMATCH); + ecode++; + break; + + case OP_WORDCHAR: + if (eptr >= md->end_subject) RRETURN(MATCH_NOMATCH); + GETCHARINCTEST(c, eptr); + if ( +#ifdef SUPPORT_UTF8 + c >= 256 || +#endif + (md->ctypes[c] & ctype_word) == 0 + ) + RRETURN(MATCH_NOMATCH); + ecode++; + break; + +#ifdef SUPPORT_UCP + /* Check the next character by Unicode property. We will get here only + if the support is in the binary; otherwise a compile-time error occurs. */ + + case OP_PROP: + case OP_NOTPROP: + if (eptr >= md->end_subject) RRETURN(MATCH_NOMATCH); + GETCHARINCTEST(c, eptr); + { + int chartype, rqdtype; + int othercase; + int category = ucp_findchar(c, &chartype, &othercase); + + rqdtype = *(++ecode); + ecode++; + + if (rqdtype >= 128) + { + if ((rqdtype - 128 != category) == (op == OP_PROP)) + RRETURN(MATCH_NOMATCH); + } + else + { + if ((rqdtype != chartype) == (op == OP_PROP)) + RRETURN(MATCH_NOMATCH); + } + } + break; + + /* Match an extended Unicode sequence. We will get here only if the support + is in the binary; otherwise a compile-time error occurs. */ + + case OP_EXTUNI: + if (eptr >= md->end_subject) RRETURN(MATCH_NOMATCH); + GETCHARINCTEST(c, eptr); + { + int chartype; + int othercase; + int category = ucp_findchar(c, &chartype, &othercase); + if (category == ucp_M) RRETURN(MATCH_NOMATCH); + while (eptr < md->end_subject) + { + int len = 1; + if (!md->utf8) c = *eptr; else + { + GETCHARLEN(c, eptr, len); + } + category = ucp_findchar(c, &chartype, &othercase); + if (category != ucp_M) break; + eptr += len; + } + } + ecode++; + break; +#endif + + + /* Match a back reference, possibly repeatedly. Look past the end of the + item to see if there is repeat information following. The code is similar + to that for character classes, but repeated for efficiency. Then obey + similar code to character type repeats - written out again for speed. + However, if the referenced string is the empty string, always treat + it as matched, any number of times (otherwise there could be infinite + loops). */ + + case OP_REF: + { + offset = GET2(ecode, 1) << 1; /* Doubled ref number */ + ecode += 3; /* Advance past item */ + + /* If the reference is unset, set the length to be longer than the amount + of subject left; this ensures that every attempt at a match fails. We + can't just fail here, because of the possibility of quantifiers with zero + minima. */ + + length = (offset >= offset_top || md->offset_vector[offset] < 0)? + md->end_subject - eptr + 1 : + md->offset_vector[offset+1] - md->offset_vector[offset]; + + /* Set up for repetition, or handle the non-repeated case */ + + switch (*ecode) + { + case OP_CRSTAR: + case OP_CRMINSTAR: + case OP_CRPLUS: + case OP_CRMINPLUS: + case OP_CRQUERY: + case OP_CRMINQUERY: + c = *ecode++ - OP_CRSTAR; + minimize = (c & 1) != 0; + min = rep_min[c]; /* Pick up values from tables; */ + max = rep_max[c]; /* zero for max => infinity */ + if (max == 0) max = INT_MAX; + break; + + case OP_CRRANGE: + case OP_CRMINRANGE: + minimize = (*ecode == OP_CRMINRANGE); + min = GET2(ecode, 1); + max = GET2(ecode, 3); + if (max == 0) max = INT_MAX; + ecode += 5; + break; + + default: /* No repeat follows */ + if (!match_ref(offset, eptr, length, md, ims)) RRETURN(MATCH_NOMATCH); + eptr += length; + continue; /* With the main loop */ + } + + /* If the length of the reference is zero, just continue with the + main loop. */ + + if (length == 0) continue; + + /* First, ensure the minimum number of matches are present. We get back + the length of the reference string explicitly rather than passing the + address of eptr, so that eptr can be a register variable. */ + + for (i = 1; i <= min; i++) + { + if (!match_ref(offset, eptr, length, md, ims)) RRETURN(MATCH_NOMATCH); + eptr += length; + } + + /* If min = max, continue at the same level without recursion. + They are not both allowed to be zero. */ + + if (min == max) continue; + + /* If minimizing, keep trying and advancing the pointer */ + + if (minimize) + { + for (fi = min;; fi++) + { + RMATCH(rrc, eptr, ecode, offset_top, md, ims, eptrb, 0); + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + if (fi >= max || !match_ref(offset, eptr, length, md, ims)) + RRETURN(MATCH_NOMATCH); + eptr += length; + } + /* Control never gets here */ + } + + /* If maximizing, find the longest string and work backwards */ + + else + { + pp = eptr; + for (i = min; i < max; i++) + { + if (!match_ref(offset, eptr, length, md, ims)) break; + eptr += length; + } + while (eptr >= pp) + { + RMATCH(rrc, eptr, ecode, offset_top, md, ims, eptrb, 0); + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + eptr -= length; + } + RRETURN(MATCH_NOMATCH); + } + } + /* Control never gets here */ + + + + /* Match a bit-mapped character class, possibly repeatedly. This op code is + used when all the characters in the class have values in the range 0-255, + and either the matching is caseful, or the characters are in the range + 0-127 when UTF-8 processing is enabled. The only difference between + OP_CLASS and OP_NCLASS occurs when a data character outside the range is + encountered. + + First, look past the end of the item to see if there is repeat information + following. Then obey similar code to character type repeats - written out + again for speed. */ + + case OP_NCLASS: + case OP_CLASS: + { + data = ecode + 1; /* Save for matching */ + ecode += 33; /* Advance past the item */ + + switch (*ecode) + { + case OP_CRSTAR: + case OP_CRMINSTAR: + case OP_CRPLUS: + case OP_CRMINPLUS: + case OP_CRQUERY: + case OP_CRMINQUERY: + c = *ecode++ - OP_CRSTAR; + minimize = (c & 1) != 0; + min = rep_min[c]; /* Pick up values from tables; */ + max = rep_max[c]; /* zero for max => infinity */ + if (max == 0) max = INT_MAX; + break; + + case OP_CRRANGE: + case OP_CRMINRANGE: + minimize = (*ecode == OP_CRMINRANGE); + min = GET2(ecode, 1); + max = GET2(ecode, 3); + if (max == 0) max = INT_MAX; + ecode += 5; + break; + + default: /* No repeat follows */ + min = max = 1; + break; + } + + /* First, ensure the minimum number of matches are present. */ + +#ifdef SUPPORT_UTF8 + /* UTF-8 mode */ + if (md->utf8) + { + for (i = 1; i <= min; i++) + { + if (eptr >= md->end_subject) RRETURN(MATCH_NOMATCH); + GETCHARINC(c, eptr); + if (c > 255) + { + if (op == OP_CLASS) RRETURN(MATCH_NOMATCH); + } + else + { + if ((data[c/8] & (1 << (c&7))) == 0) RRETURN(MATCH_NOMATCH); + } + } + } + else +#endif + /* Not UTF-8 mode */ + { + for (i = 1; i <= min; i++) + { + if (eptr >= md->end_subject) RRETURN(MATCH_NOMATCH); + c = *eptr++; + if ((data[c/8] & (1 << (c&7))) == 0) RRETURN(MATCH_NOMATCH); + } + } + + /* If max == min we can continue with the main loop without the + need to recurse. */ + + if (min == max) continue; + + /* If minimizing, keep testing the rest of the expression and advancing + the pointer while it matches the class. */ + + if (minimize) + { +#ifdef SUPPORT_UTF8 + /* UTF-8 mode */ + if (md->utf8) + { + for (fi = min;; fi++) + { + RMATCH(rrc, eptr, ecode, offset_top, md, ims, eptrb, 0); + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + if (fi >= max || eptr >= md->end_subject) RRETURN(MATCH_NOMATCH); + GETCHARINC(c, eptr); + if (c > 255) + { + if (op == OP_CLASS) RRETURN(MATCH_NOMATCH); + } + else + { + if ((data[c/8] & (1 << (c&7))) == 0) RRETURN(MATCH_NOMATCH); + } + } + } + else +#endif + /* Not UTF-8 mode */ + { + for (fi = min;; fi++) + { + RMATCH(rrc, eptr, ecode, offset_top, md, ims, eptrb, 0); + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + if (fi >= max || eptr >= md->end_subject) RRETURN(MATCH_NOMATCH); + c = *eptr++; + if ((data[c/8] & (1 << (c&7))) == 0) RRETURN(MATCH_NOMATCH); + } + } + /* Control never gets here */ + } + + /* If maximizing, find the longest possible run, then work backwards. */ + + else + { + pp = eptr; + +#ifdef SUPPORT_UTF8 + /* UTF-8 mode */ + if (md->utf8) + { + for (i = min; i < max; i++) + { + int len = 1; + if (eptr >= md->end_subject) break; + GETCHARLEN(c, eptr, len); + if (c > 255) + { + if (op == OP_CLASS) break; + } + else + { + if ((data[c/8] & (1 << (c&7))) == 0) break; + } + eptr += len; + } + for (;;) + { + RMATCH(rrc, eptr, ecode, offset_top, md, ims, eptrb, 0); + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + if (eptr-- == pp) break; /* Stop if tried at original pos */ + BACKCHAR(eptr); + } + } + else +#endif + /* Not UTF-8 mode */ + { + for (i = min; i < max; i++) + { + if (eptr >= md->end_subject) break; + c = *eptr; + if ((data[c/8] & (1 << (c&7))) == 0) break; + eptr++; + } + while (eptr >= pp) + { + RMATCH(rrc, eptr, ecode, offset_top, md, ims, eptrb, 0); + eptr--; + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + } + } + + RRETURN(MATCH_NOMATCH); + } + } + /* Control never gets here */ + + + /* Match an extended character class. This opcode is encountered only + in UTF-8 mode, because that's the only time it is compiled. */ + +#ifdef SUPPORT_UTF8 + case OP_XCLASS: + { + data = ecode + 1 + LINK_SIZE; /* Save for matching */ + ecode += GET(ecode, 1); /* Advance past the item */ + + switch (*ecode) + { + case OP_CRSTAR: + case OP_CRMINSTAR: + case OP_CRPLUS: + case OP_CRMINPLUS: + case OP_CRQUERY: + case OP_CRMINQUERY: + c = *ecode++ - OP_CRSTAR; + minimize = (c & 1) != 0; + min = rep_min[c]; /* Pick up values from tables; */ + max = rep_max[c]; /* zero for max => infinity */ + if (max == 0) max = INT_MAX; + break; + + case OP_CRRANGE: + case OP_CRMINRANGE: + minimize = (*ecode == OP_CRMINRANGE); + min = GET2(ecode, 1); + max = GET2(ecode, 3); + if (max == 0) max = INT_MAX; + ecode += 5; + break; + + default: /* No repeat follows */ + min = max = 1; + break; + } + + /* First, ensure the minimum number of matches are present. */ + + for (i = 1; i <= min; i++) + { + if (eptr >= md->end_subject) RRETURN(MATCH_NOMATCH); + GETCHARINC(c, eptr); + if (!match_xclass(c, data)) RRETURN(MATCH_NOMATCH); + } + + /* If max == min we can continue with the main loop without the + need to recurse. */ + + if (min == max) continue; + + /* If minimizing, keep testing the rest of the expression and advancing + the pointer while it matches the class. */ + + if (minimize) + { + for (fi = min;; fi++) + { + RMATCH(rrc, eptr, ecode, offset_top, md, ims, eptrb, 0); + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + if (fi >= max || eptr >= md->end_subject) RRETURN(MATCH_NOMATCH); + GETCHARINC(c, eptr); + if (!match_xclass(c, data)) RRETURN(MATCH_NOMATCH); + } + /* Control never gets here */ + } + + /* If maximizing, find the longest possible run, then work backwards. */ + + else + { + pp = eptr; + for (i = min; i < max; i++) + { + int len = 1; + if (eptr >= md->end_subject) break; + GETCHARLEN(c, eptr, len); + if (!match_xclass(c, data)) break; + eptr += len; + } + for(;;) + { + RMATCH(rrc, eptr, ecode, offset_top, md, ims, eptrb, 0); + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + if (eptr-- == pp) break; /* Stop if tried at original pos */ + BACKCHAR(eptr) + } + RRETURN(MATCH_NOMATCH); + } + + /* Control never gets here */ + } +#endif /* End of XCLASS */ + + /* Match a single character, casefully */ + + case OP_CHAR: +#ifdef SUPPORT_UTF8 + if (md->utf8) + { + length = 1; + ecode++; + GETCHARLEN(fc, ecode, length); + if (length > md->end_subject - eptr) RRETURN(MATCH_NOMATCH); + while (length-- > 0) if (*ecode++ != *eptr++) RRETURN(MATCH_NOMATCH); + } + else +#endif + + /* Non-UTF-8 mode */ + { + if (md->end_subject - eptr < 1) RRETURN(MATCH_NOMATCH); + if (ecode[1] != *eptr++) RRETURN(MATCH_NOMATCH); + ecode += 2; + } + break; + + /* Match a single character, caselessly */ + + case OP_CHARNC: +#ifdef SUPPORT_UTF8 + if (md->utf8) + { + length = 1; + ecode++; + GETCHARLEN(fc, ecode, length); + + if (length > md->end_subject - eptr) RRETURN(MATCH_NOMATCH); + + /* If the pattern character's value is < 128, we have only one byte, and + can use the fast lookup table. */ + + if (fc < 128) + { + if (md->lcc[*ecode++] != md->lcc[*eptr++]) RRETURN(MATCH_NOMATCH); + } + + /* Otherwise we must pick up the subject character */ + + else + { + int dc; + GETCHARINC(dc, eptr); + ecode += length; + + /* If we have Unicode property support, we can use it to test the other + case of the character, if there is one. The result of ucp_findchar() is + < 0 if the char isn't found, and othercase is returned as zero if there + isn't one. */ + + if (fc != dc) + { +#ifdef SUPPORT_UCP + int chartype; + int othercase; + if (ucp_findchar(fc, &chartype, &othercase) < 0 || dc != othercase) +#endif + RRETURN(MATCH_NOMATCH); + } + } + } + else +#endif /* SUPPORT_UTF8 */ + + /* Non-UTF-8 mode */ + { + if (md->end_subject - eptr < 1) RRETURN(MATCH_NOMATCH); + if (md->lcc[ecode[1]] != md->lcc[*eptr++]) RRETURN(MATCH_NOMATCH); + ecode += 2; + } + break; + + /* Match a single character repeatedly; different opcodes share code. */ + + case OP_EXACT: + min = max = GET2(ecode, 1); + ecode += 3; + goto REPEATCHAR; + + case OP_UPTO: + case OP_MINUPTO: + min = 0; + max = GET2(ecode, 1); + minimize = *ecode == OP_MINUPTO; + ecode += 3; + goto REPEATCHAR; + + case OP_STAR: + case OP_MINSTAR: + case OP_PLUS: + case OP_MINPLUS: + case OP_QUERY: + case OP_MINQUERY: + c = *ecode++ - OP_STAR; + minimize = (c & 1) != 0; + min = rep_min[c]; /* Pick up values from tables; */ + max = rep_max[c]; /* zero for max => infinity */ + if (max == 0) max = INT_MAX; + + /* Common code for all repeated single-character matches. We can give + up quickly if there are fewer than the minimum number of characters left in + the subject. */ + + REPEATCHAR: +#ifdef SUPPORT_UTF8 + if (md->utf8) + { + length = 1; + charptr = ecode; + GETCHARLEN(fc, ecode, length); + if (min * length > md->end_subject - eptr) RRETURN(MATCH_NOMATCH); + ecode += length; + + /* Handle multibyte character matching specially here. There is + support for caseless matching if UCP support is present. */ + + if (length > 1) + { + int oclength = 0; + uschar occhars[8]; + +#ifdef SUPPORT_UCP + int othercase; + int chartype; + if ((ims & PCRE_CASELESS) != 0 && + ucp_findchar(fc, &chartype, &othercase) >= 0 && + othercase > 0) + oclength = ord2utf8(othercase, occhars); +#endif /* SUPPORT_UCP */ + + for (i = 1; i <= min; i++) + { + if (memcmp(eptr, charptr, length) == 0) eptr += length; + /* Need braces because of following else */ + else if (oclength == 0) { RRETURN(MATCH_NOMATCH); } + else + { + if (memcmp(eptr, occhars, oclength) != 0) RRETURN(MATCH_NOMATCH); + eptr += oclength; + } + } + + if (min == max) continue; + + if (minimize) + { + for (fi = min;; fi++) + { + RMATCH(rrc, eptr, ecode, offset_top, md, ims, eptrb, 0); + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + if (fi >= max || eptr >= md->end_subject) RRETURN(MATCH_NOMATCH); + if (memcmp(eptr, charptr, length) == 0) eptr += length; + /* Need braces because of following else */ + else if (oclength == 0) { RRETURN(MATCH_NOMATCH); } + else + { + if (memcmp(eptr, occhars, oclength) != 0) RRETURN(MATCH_NOMATCH); + eptr += oclength; + } + } + /* Control never gets here */ + } + else + { + pp = eptr; + for (i = min; i < max; i++) + { + if (eptr > md->end_subject - length) break; + if (memcmp(eptr, charptr, length) == 0) eptr += length; + else if (oclength == 0) break; + else + { + if (memcmp(eptr, occhars, oclength) != 0) break; + eptr += oclength; + } + } + while (eptr >= pp) + { + RMATCH(rrc, eptr, ecode, offset_top, md, ims, eptrb, 0); + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + eptr -= length; + } + RRETURN(MATCH_NOMATCH); + } + /* Control never gets here */ + } + + /* If the length of a UTF-8 character is 1, we fall through here, and + obey the code as for non-UTF-8 characters below, though in this case the + value of fc will always be < 128. */ + } + else +#endif /* SUPPORT_UTF8 */ + + /* When not in UTF-8 mode, load a single-byte character. */ + { + if (min > md->end_subject - eptr) RRETURN(MATCH_NOMATCH); + fc = *ecode++; + } + + /* The value of fc at this point is always less than 256, though we may or + may not be in UTF-8 mode. The code is duplicated for the caseless and + caseful cases, for speed, since matching characters is likely to be quite + common. First, ensure the minimum number of matches are present. If min = + max, continue at the same level without recursing. Otherwise, if + minimizing, keep trying the rest of the expression and advancing one + matching character if failing, up to the maximum. Alternatively, if + maximizing, find the maximum number of characters and work backwards. */ + + DPRINTF(("matching %c{%d,%d} against subject %.*s\n", fc, min, max, + max, eptr)); + + if ((ims & PCRE_CASELESS) != 0) + { + fc = md->lcc[fc]; + for (i = 1; i <= min; i++) + if (fc != md->lcc[*eptr++]) RRETURN(MATCH_NOMATCH); + if (min == max) continue; + if (minimize) + { + for (fi = min;; fi++) + { + RMATCH(rrc, eptr, ecode, offset_top, md, ims, eptrb, 0); + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + if (fi >= max || eptr >= md->end_subject || + fc != md->lcc[*eptr++]) + RRETURN(MATCH_NOMATCH); + } + /* Control never gets here */ + } + else + { + pp = eptr; + for (i = min; i < max; i++) + { + if (eptr >= md->end_subject || fc != md->lcc[*eptr]) break; + eptr++; + } + while (eptr >= pp) + { + RMATCH(rrc, eptr, ecode, offset_top, md, ims, eptrb, 0); + eptr--; + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + } + RRETURN(MATCH_NOMATCH); + } + /* Control never gets here */ + } + + /* Caseful comparisons (includes all multi-byte characters) */ + + else + { + for (i = 1; i <= min; i++) if (fc != *eptr++) RRETURN(MATCH_NOMATCH); + if (min == max) continue; + if (minimize) + { + for (fi = min;; fi++) + { + RMATCH(rrc, eptr, ecode, offset_top, md, ims, eptrb, 0); + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + if (fi >= max || eptr >= md->end_subject || fc != *eptr++) + RRETURN(MATCH_NOMATCH); + } + /* Control never gets here */ + } + else + { + pp = eptr; + for (i = min; i < max; i++) + { + if (eptr >= md->end_subject || fc != *eptr) break; + eptr++; + } + while (eptr >= pp) + { + RMATCH(rrc, eptr, ecode, offset_top, md, ims, eptrb, 0); + eptr--; + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + } + RRETURN(MATCH_NOMATCH); + } + } + /* Control never gets here */ + + /* Match a negated single one-byte character. The character we are + checking can be multibyte. */ + + case OP_NOT: + if (eptr >= md->end_subject) RRETURN(MATCH_NOMATCH); + ecode++; + GETCHARINCTEST(c, eptr); + if ((ims & PCRE_CASELESS) != 0) + { +#ifdef SUPPORT_UTF8 + if (c < 256) +#endif + c = md->lcc[c]; + if (md->lcc[*ecode++] == c) RRETURN(MATCH_NOMATCH); + } + else + { + if (*ecode++ == c) RRETURN(MATCH_NOMATCH); + } + break; + + /* Match a negated single one-byte character repeatedly. This is almost a + repeat of the code for a repeated single character, but I haven't found a + nice way of commoning these up that doesn't require a test of the + positive/negative option for each character match. Maybe that wouldn't add + very much to the time taken, but character matching *is* what this is all + about... */ + + case OP_NOTEXACT: + min = max = GET2(ecode, 1); + ecode += 3; + goto REPEATNOTCHAR; + + case OP_NOTUPTO: + case OP_NOTMINUPTO: + min = 0; + max = GET2(ecode, 1); + minimize = *ecode == OP_NOTMINUPTO; + ecode += 3; + goto REPEATNOTCHAR; + + case OP_NOTSTAR: + case OP_NOTMINSTAR: + case OP_NOTPLUS: + case OP_NOTMINPLUS: + case OP_NOTQUERY: + case OP_NOTMINQUERY: + c = *ecode++ - OP_NOTSTAR; + minimize = (c & 1) != 0; + min = rep_min[c]; /* Pick up values from tables; */ + max = rep_max[c]; /* zero for max => infinity */ + if (max == 0) max = INT_MAX; + + /* Common code for all repeated single-byte matches. We can give up quickly + if there are fewer than the minimum number of bytes left in the + subject. */ + + REPEATNOTCHAR: + if (min > md->end_subject - eptr) RRETURN(MATCH_NOMATCH); + fc = *ecode++; + + /* The code is duplicated for the caseless and caseful cases, for speed, + since matching characters is likely to be quite common. First, ensure the + minimum number of matches are present. If min = max, continue at the same + level without recursing. Otherwise, if minimizing, keep trying the rest of + the expression and advancing one matching character if failing, up to the + maximum. Alternatively, if maximizing, find the maximum number of + characters and work backwards. */ + + DPRINTF(("negative matching %c{%d,%d} against subject %.*s\n", fc, min, max, + max, eptr)); + + if ((ims & PCRE_CASELESS) != 0) + { + fc = md->lcc[fc]; + +#ifdef SUPPORT_UTF8 + /* UTF-8 mode */ + if (md->utf8) + { + register int d; + for (i = 1; i <= min; i++) + { + GETCHARINC(d, eptr); + if (d < 256) d = md->lcc[d]; + if (fc == d) RRETURN(MATCH_NOMATCH); + } + } + else +#endif + + /* Not UTF-8 mode */ + { + for (i = 1; i <= min; i++) + if (fc == md->lcc[*eptr++]) RRETURN(MATCH_NOMATCH); + } + + if (min == max) continue; + + if (minimize) + { +#ifdef SUPPORT_UTF8 + /* UTF-8 mode */ + if (md->utf8) + { + register int d; + for (fi = min;; fi++) + { + RMATCH(rrc, eptr, ecode, offset_top, md, ims, eptrb, 0); + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + GETCHARINC(d, eptr); + if (d < 256) d = md->lcc[d]; + if (fi >= max || eptr >= md->end_subject || fc == d) + RRETURN(MATCH_NOMATCH); + } + } + else +#endif + /* Not UTF-8 mode */ + { + for (fi = min;; fi++) + { + RMATCH(rrc, eptr, ecode, offset_top, md, ims, eptrb, 0); + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + if (fi >= max || eptr >= md->end_subject || fc == md->lcc[*eptr++]) + RRETURN(MATCH_NOMATCH); + } + } + /* Control never gets here */ + } + + /* Maximize case */ + + else + { + pp = eptr; + +#ifdef SUPPORT_UTF8 + /* UTF-8 mode */ + if (md->utf8) + { + register int d; + for (i = min; i < max; i++) + { + int len = 1; + if (eptr >= md->end_subject) break; + GETCHARLEN(d, eptr, len); + if (d < 256) d = md->lcc[d]; + if (fc == d) break; + eptr += len; + } + for(;;) + { + RMATCH(rrc, eptr, ecode, offset_top, md, ims, eptrb, 0); + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + if (eptr-- == pp) break; /* Stop if tried at original pos */ + BACKCHAR(eptr); + } + } + else +#endif + /* Not UTF-8 mode */ + { + for (i = min; i < max; i++) + { + if (eptr >= md->end_subject || fc == md->lcc[*eptr]) break; + eptr++; + } + while (eptr >= pp) + { + RMATCH(rrc, eptr, ecode, offset_top, md, ims, eptrb, 0); + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + eptr--; + } + } + + RRETURN(MATCH_NOMATCH); + } + /* Control never gets here */ + } + + /* Caseful comparisons */ + + else + { +#ifdef SUPPORT_UTF8 + /* UTF-8 mode */ + if (md->utf8) + { + register int d; + for (i = 1; i <= min; i++) + { + GETCHARINC(d, eptr); + if (fc == d) RRETURN(MATCH_NOMATCH); + } + } + else +#endif + /* Not UTF-8 mode */ + { + for (i = 1; i <= min; i++) + if (fc == *eptr++) RRETURN(MATCH_NOMATCH); + } + + if (min == max) continue; + + if (minimize) + { +#ifdef SUPPORT_UTF8 + /* UTF-8 mode */ + if (md->utf8) + { + register int d; + for (fi = min;; fi++) + { + RMATCH(rrc, eptr, ecode, offset_top, md, ims, eptrb, 0); + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + GETCHARINC(d, eptr); + if (fi >= max || eptr >= md->end_subject || fc == d) + RRETURN(MATCH_NOMATCH); + } + } + else +#endif + /* Not UTF-8 mode */ + { + for (fi = min;; fi++) + { + RMATCH(rrc, eptr, ecode, offset_top, md, ims, eptrb, 0); + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + if (fi >= max || eptr >= md->end_subject || fc == *eptr++) + RRETURN(MATCH_NOMATCH); + } + } + /* Control never gets here */ + } + + /* Maximize case */ + + else + { + pp = eptr; + +#ifdef SUPPORT_UTF8 + /* UTF-8 mode */ + if (md->utf8) + { + register int d; + for (i = min; i < max; i++) + { + int len = 1; + if (eptr >= md->end_subject) break; + GETCHARLEN(d, eptr, len); + if (fc == d) break; + eptr += len; + } + for(;;) + { + RMATCH(rrc, eptr, ecode, offset_top, md, ims, eptrb, 0); + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + if (eptr-- == pp) break; /* Stop if tried at original pos */ + BACKCHAR(eptr); + } + } + else +#endif + /* Not UTF-8 mode */ + { + for (i = min; i < max; i++) + { + if (eptr >= md->end_subject || fc == *eptr) break; + eptr++; + } + while (eptr >= pp) + { + RMATCH(rrc, eptr, ecode, offset_top, md, ims, eptrb, 0); + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + eptr--; + } + } + + RRETURN(MATCH_NOMATCH); + } + } + /* Control never gets here */ + + /* Match a single character type repeatedly; several different opcodes + share code. This is very similar to the code for single characters, but we + repeat it in the interests of efficiency. */ + + case OP_TYPEEXACT: + min = max = GET2(ecode, 1); + minimize = TRUE; + ecode += 3; + goto REPEATTYPE; + + case OP_TYPEUPTO: + case OP_TYPEMINUPTO: + min = 0; + max = GET2(ecode, 1); + minimize = *ecode == OP_TYPEMINUPTO; + ecode += 3; + goto REPEATTYPE; + + case OP_TYPESTAR: + case OP_TYPEMINSTAR: + case OP_TYPEPLUS: + case OP_TYPEMINPLUS: + case OP_TYPEQUERY: + case OP_TYPEMINQUERY: + c = *ecode++ - OP_TYPESTAR; + minimize = (c & 1) != 0; + min = rep_min[c]; /* Pick up values from tables; */ + max = rep_max[c]; /* zero for max => infinity */ + if (max == 0) max = INT_MAX; + + /* Common code for all repeated single character type matches. Note that + in UTF-8 mode, '.' matches a character of any length, but for the other + character types, the valid characters are all one-byte long. */ + + REPEATTYPE: + ctype = *ecode++; /* Code for the character type */ + +#ifdef SUPPORT_UCP + if (ctype == OP_PROP || ctype == OP_NOTPROP) + { + prop_fail_result = ctype == OP_NOTPROP; + prop_type = *ecode++; + if (prop_type >= 128) + { + prop_test_against = prop_type - 128; + prop_test_variable = &prop_category; + } + else + { + prop_test_against = prop_type; + prop_test_variable = &prop_chartype; + } + } + else prop_type = -1; +#endif + + /* First, ensure the minimum number of matches are present. Use inline + code for maximizing the speed, and do the type test once at the start + (i.e. keep it out of the loop). Also we can test that there are at least + the minimum number of bytes before we start. This isn't as effective in + UTF-8 mode, but it does no harm. Separate the UTF-8 code completely as that + is tidier. Also separate the UCP code, which can be the same for both UTF-8 + and single-bytes. */ + + if (min > md->end_subject - eptr) RRETURN(MATCH_NOMATCH); + if (min > 0) + { +#ifdef SUPPORT_UCP + if (prop_type > 0) + { + for (i = 1; i <= min; i++) + { + GETCHARINC(c, eptr); + prop_category = ucp_findchar(c, &prop_chartype, &prop_othercase); + if ((*prop_test_variable == prop_test_against) == prop_fail_result) + RRETURN(MATCH_NOMATCH); + } + } + + /* Match extended Unicode sequences. We will get here only if the + support is in the binary; otherwise a compile-time error occurs. */ + + else if (ctype == OP_EXTUNI) + { + for (i = 1; i <= min; i++) + { + GETCHARINCTEST(c, eptr); + prop_category = ucp_findchar(c, &prop_chartype, &prop_othercase); + if (prop_category == ucp_M) RRETURN(MATCH_NOMATCH); + while (eptr < md->end_subject) + { + int len = 1; + if (!md->utf8) c = *eptr; else + { + GETCHARLEN(c, eptr, len); + } + prop_category = ucp_findchar(c, &prop_chartype, &prop_othercase); + if (prop_category != ucp_M) break; + eptr += len; + } + } + } + + else +#endif /* SUPPORT_UCP */ + +/* Handle all other cases when the coding is UTF-8 */ + +#ifdef SUPPORT_UTF8 + if (md->utf8) switch(ctype) + { + case OP_ANY: + for (i = 1; i <= min; i++) + { + if (eptr >= md->end_subject || + (*eptr++ == NEWLINE && (ims & PCRE_DOTALL) == 0)) + RRETURN(MATCH_NOMATCH); + while (eptr < md->end_subject && (*eptr & 0xc0) == 0x80) eptr++; + } + break; + + case OP_ANYBYTE: + eptr += min; + break; + + case OP_NOT_DIGIT: + for (i = 1; i <= min; i++) + { + if (eptr >= md->end_subject) RRETURN(MATCH_NOMATCH); + GETCHARINC(c, eptr); + if (c < 128 && (md->ctypes[c] & ctype_digit) != 0) + RRETURN(MATCH_NOMATCH); + } + break; + + case OP_DIGIT: + for (i = 1; i <= min; i++) + { + if (eptr >= md->end_subject || + *eptr >= 128 || (md->ctypes[*eptr++] & ctype_digit) == 0) + RRETURN(MATCH_NOMATCH); + /* No need to skip more bytes - we know it's a 1-byte character */ + } + break; + + case OP_NOT_WHITESPACE: + for (i = 1; i <= min; i++) + { + if (eptr >= md->end_subject || + (*eptr < 128 && (md->ctypes[*eptr++] & ctype_space) != 0)) + RRETURN(MATCH_NOMATCH); + while (eptr < md->end_subject && (*eptr & 0xc0) == 0x80) eptr++; + } + break; + + case OP_WHITESPACE: + for (i = 1; i <= min; i++) + { + if (eptr >= md->end_subject || + *eptr >= 128 || (md->ctypes[*eptr++] & ctype_space) == 0) + RRETURN(MATCH_NOMATCH); + /* No need to skip more bytes - we know it's a 1-byte character */ + } + break; + + case OP_NOT_WORDCHAR: + for (i = 1; i <= min; i++) + { + if (eptr >= md->end_subject || + (*eptr < 128 && (md->ctypes[*eptr++] & ctype_word) != 0)) + RRETURN(MATCH_NOMATCH); + while (eptr < md->end_subject && (*eptr & 0xc0) == 0x80) eptr++; + } + break; + + case OP_WORDCHAR: + for (i = 1; i <= min; i++) + { + if (eptr >= md->end_subject || + *eptr >= 128 || (md->ctypes[*eptr++] & ctype_word) == 0) + RRETURN(MATCH_NOMATCH); + /* No need to skip more bytes - we know it's a 1-byte character */ + } + break; + + default: + RRETURN(PCRE_ERROR_INTERNAL); + } /* End switch(ctype) */ + + else +#endif /* SUPPORT_UTF8 */ + + /* Code for the non-UTF-8 case for minimum matching of operators other + than OP_PROP and OP_NOTPROP. */ + + switch(ctype) + { + case OP_ANY: + if ((ims & PCRE_DOTALL) == 0) + { + for (i = 1; i <= min; i++) + if (*eptr++ == NEWLINE) RRETURN(MATCH_NOMATCH); + } + else eptr += min; + break; + + case OP_ANYBYTE: + eptr += min; + break; + + case OP_NOT_DIGIT: + for (i = 1; i <= min; i++) + if ((md->ctypes[*eptr++] & ctype_digit) != 0) RRETURN(MATCH_NOMATCH); + break; + + case OP_DIGIT: + for (i = 1; i <= min; i++) + if ((md->ctypes[*eptr++] & ctype_digit) == 0) RRETURN(MATCH_NOMATCH); + break; + + case OP_NOT_WHITESPACE: + for (i = 1; i <= min; i++) + if ((md->ctypes[*eptr++] & ctype_space) != 0) RRETURN(MATCH_NOMATCH); + break; + + case OP_WHITESPACE: + for (i = 1; i <= min; i++) + if ((md->ctypes[*eptr++] & ctype_space) == 0) RRETURN(MATCH_NOMATCH); + break; + + case OP_NOT_WORDCHAR: + for (i = 1; i <= min; i++) + if ((md->ctypes[*eptr++] & ctype_word) != 0) + RRETURN(MATCH_NOMATCH); + break; + + case OP_WORDCHAR: + for (i = 1; i <= min; i++) + if ((md->ctypes[*eptr++] & ctype_word) == 0) + RRETURN(MATCH_NOMATCH); + break; + + default: + RRETURN(PCRE_ERROR_INTERNAL); + } + } + + /* If min = max, continue at the same level without recursing */ + + if (min == max) continue; + + /* If minimizing, we have to test the rest of the pattern before each + subsequent match. Again, separate the UTF-8 case for speed, and also + separate the UCP cases. */ + + if (minimize) + { +#ifdef SUPPORT_UCP + if (prop_type > 0) + { + for (fi = min;; fi++) + { + RMATCH(rrc, eptr, ecode, offset_top, md, ims, eptrb, 0); + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + if (fi >= max || eptr >= md->end_subject) RRETURN(MATCH_NOMATCH); + GETCHARINC(c, eptr); + prop_category = ucp_findchar(c, &prop_chartype, &prop_othercase); + if ((*prop_test_variable == prop_test_against) == prop_fail_result) + RRETURN(MATCH_NOMATCH); + } + } + + /* Match extended Unicode sequences. We will get here only if the + support is in the binary; otherwise a compile-time error occurs. */ + + else if (ctype == OP_EXTUNI) + { + for (fi = min;; fi++) + { + RMATCH(rrc, eptr, ecode, offset_top, md, ims, eptrb, 0); + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + if (fi >= max || eptr >= md->end_subject) RRETURN(MATCH_NOMATCH); + GETCHARINCTEST(c, eptr); + prop_category = ucp_findchar(c, &prop_chartype, &prop_othercase); + if (prop_category == ucp_M) RRETURN(MATCH_NOMATCH); + while (eptr < md->end_subject) + { + int len = 1; + if (!md->utf8) c = *eptr; else + { + GETCHARLEN(c, eptr, len); + } + prop_category = ucp_findchar(c, &prop_chartype, &prop_othercase); + if (prop_category != ucp_M) break; + eptr += len; + } + } + } + + else +#endif /* SUPPORT_UCP */ + +#ifdef SUPPORT_UTF8 + /* UTF-8 mode */ + if (md->utf8) + { + for (fi = min;; fi++) + { + RMATCH(rrc, eptr, ecode, offset_top, md, ims, eptrb, 0); + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + if (fi >= max || eptr >= md->end_subject) RRETURN(MATCH_NOMATCH); + + GETCHARINC(c, eptr); + switch(ctype) + { + case OP_ANY: + if ((ims & PCRE_DOTALL) == 0 && c == NEWLINE) RRETURN(MATCH_NOMATCH); + break; + + case OP_ANYBYTE: + break; + + case OP_NOT_DIGIT: + if (c < 256 && (md->ctypes[c] & ctype_digit) != 0) + RRETURN(MATCH_NOMATCH); + break; + + case OP_DIGIT: + if (c >= 256 || (md->ctypes[c] & ctype_digit) == 0) + RRETURN(MATCH_NOMATCH); + break; + + case OP_NOT_WHITESPACE: + if (c < 256 && (md->ctypes[c] & ctype_space) != 0) + RRETURN(MATCH_NOMATCH); + break; + + case OP_WHITESPACE: + if (c >= 256 || (md->ctypes[c] & ctype_space) == 0) + RRETURN(MATCH_NOMATCH); + break; + + case OP_NOT_WORDCHAR: + if (c < 256 && (md->ctypes[c] & ctype_word) != 0) + RRETURN(MATCH_NOMATCH); + break; + + case OP_WORDCHAR: + if (c >= 256 && (md->ctypes[c] & ctype_word) == 0) + RRETURN(MATCH_NOMATCH); + break; + + default: + RRETURN(PCRE_ERROR_INTERNAL); + } + } + } + else +#endif + /* Not UTF-8 mode */ + { + for (fi = min;; fi++) + { + RMATCH(rrc, eptr, ecode, offset_top, md, ims, eptrb, 0); + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + if (fi >= max || eptr >= md->end_subject) RRETURN(MATCH_NOMATCH); + c = *eptr++; + switch(ctype) + { + case OP_ANY: + if ((ims & PCRE_DOTALL) == 0 && c == NEWLINE) RRETURN(MATCH_NOMATCH); + break; + + case OP_ANYBYTE: + break; + + case OP_NOT_DIGIT: + if ((md->ctypes[c] & ctype_digit) != 0) RRETURN(MATCH_NOMATCH); + break; + + case OP_DIGIT: + if ((md->ctypes[c] & ctype_digit) == 0) RRETURN(MATCH_NOMATCH); + break; + + case OP_NOT_WHITESPACE: + if ((md->ctypes[c] & ctype_space) != 0) RRETURN(MATCH_NOMATCH); + break; + + case OP_WHITESPACE: + if ((md->ctypes[c] & ctype_space) == 0) RRETURN(MATCH_NOMATCH); + break; + + case OP_NOT_WORDCHAR: + if ((md->ctypes[c] & ctype_word) != 0) RRETURN(MATCH_NOMATCH); + break; + + case OP_WORDCHAR: + if ((md->ctypes[c] & ctype_word) == 0) RRETURN(MATCH_NOMATCH); + break; + + default: + RRETURN(PCRE_ERROR_INTERNAL); + } + } + } + /* Control never gets here */ + } + + /* If maximizing it is worth using inline code for speed, doing the type + test once at the start (i.e. keep it out of the loop). Again, keep the + UTF-8 and UCP stuff separate. */ + + else + { + pp = eptr; /* Remember where we started */ + +#ifdef SUPPORT_UCP + if (prop_type > 0) + { + for (i = min; i < max; i++) + { + int len = 1; + if (eptr >= md->end_subject) break; + GETCHARLEN(c, eptr, len); + prop_category = ucp_findchar(c, &prop_chartype, &prop_othercase); + if ((*prop_test_variable == prop_test_against) == prop_fail_result) + break; + eptr+= len; + } + + /* eptr is now past the end of the maximum run */ + + for(;;) + { + RMATCH(rrc, eptr, ecode, offset_top, md, ims, eptrb, 0); + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + if (eptr-- == pp) break; /* Stop if tried at original pos */ + BACKCHAR(eptr); + } + } + + /* Match extended Unicode sequences. We will get here only if the + support is in the binary; otherwise a compile-time error occurs. */ + + else if (ctype == OP_EXTUNI) + { + for (i = min; i < max; i++) + { + if (eptr >= md->end_subject) break; + GETCHARINCTEST(c, eptr); + prop_category = ucp_findchar(c, &prop_chartype, &prop_othercase); + if (prop_category == ucp_M) break; + while (eptr < md->end_subject) + { + int len = 1; + if (!md->utf8) c = *eptr; else + { + GETCHARLEN(c, eptr, len); + } + prop_category = ucp_findchar(c, &prop_chartype, &prop_othercase); + if (prop_category != ucp_M) break; + eptr += len; + } + } + + /* eptr is now past the end of the maximum run */ + + for(;;) + { + RMATCH(rrc, eptr, ecode, offset_top, md, ims, eptrb, 0); + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + if (eptr-- == pp) break; /* Stop if tried at original pos */ + for (;;) /* Move back over one extended */ + { + int len = 1; + BACKCHAR(eptr); + if (!md->utf8) c = *eptr; else + { + GETCHARLEN(c, eptr, len); + } + prop_category = ucp_findchar(c, &prop_chartype, &prop_othercase); + if (prop_category != ucp_M) break; + eptr--; + } + } + } + + else +#endif /* SUPPORT_UCP */ + +#ifdef SUPPORT_UTF8 + /* UTF-8 mode */ + + if (md->utf8) + { + switch(ctype) + { + case OP_ANY: + + /* Special code is required for UTF8, but when the maximum is unlimited + we don't need it, so we repeat the non-UTF8 code. This is probably + worth it, because .* is quite a common idiom. */ + + if (max < INT_MAX) + { + if ((ims & PCRE_DOTALL) == 0) + { + for (i = min; i < max; i++) + { + if (eptr >= md->end_subject || *eptr == NEWLINE) break; + eptr++; + while (eptr < md->end_subject && (*eptr & 0xc0) == 0x80) eptr++; + } + } + else + { + for (i = min; i < max; i++) + { + eptr++; + while (eptr < md->end_subject && (*eptr & 0xc0) == 0x80) eptr++; + } + } + } + + /* Handle unlimited UTF-8 repeat */ + + else + { + if ((ims & PCRE_DOTALL) == 0) + { + for (i = min; i < max; i++) + { + if (eptr >= md->end_subject || *eptr == NEWLINE) break; + eptr++; + } + break; + } + else + { + c = max - min; + if (c > md->end_subject - eptr) c = md->end_subject - eptr; + eptr += c; + } + } + break; + + /* The byte case is the same as non-UTF8 */ + + case OP_ANYBYTE: + c = max - min; + if (c > md->end_subject - eptr) c = md->end_subject - eptr; + eptr += c; + break; + + case OP_NOT_DIGIT: + for (i = min; i < max; i++) + { + int len = 1; + if (eptr >= md->end_subject) break; + GETCHARLEN(c, eptr, len); + if (c < 256 && (md->ctypes[c] & ctype_digit) != 0) break; + eptr+= len; + } + break; + + case OP_DIGIT: + for (i = min; i < max; i++) + { + int len = 1; + if (eptr >= md->end_subject) break; + GETCHARLEN(c, eptr, len); + if (c >= 256 ||(md->ctypes[c] & ctype_digit) == 0) break; + eptr+= len; + } + break; + + case OP_NOT_WHITESPACE: + for (i = min; i < max; i++) + { + int len = 1; + if (eptr >= md->end_subject) break; + GETCHARLEN(c, eptr, len); + if (c < 256 && (md->ctypes[c] & ctype_space) != 0) break; + eptr+= len; + } + break; + + case OP_WHITESPACE: + for (i = min; i < max; i++) + { + int len = 1; + if (eptr >= md->end_subject) break; + GETCHARLEN(c, eptr, len); + if (c >= 256 ||(md->ctypes[c] & ctype_space) == 0) break; + eptr+= len; + } + break; + + case OP_NOT_WORDCHAR: + for (i = min; i < max; i++) + { + int len = 1; + if (eptr >= md->end_subject) break; + GETCHARLEN(c, eptr, len); + if (c < 256 && (md->ctypes[c] & ctype_word) != 0) break; + eptr+= len; + } + break; + + case OP_WORDCHAR: + for (i = min; i < max; i++) + { + int len = 1; + if (eptr >= md->end_subject) break; + GETCHARLEN(c, eptr, len); + if (c >= 256 || (md->ctypes[c] & ctype_word) == 0) break; + eptr+= len; + } + break; + + default: + RRETURN(PCRE_ERROR_INTERNAL); + } + + /* eptr is now past the end of the maximum run */ + + for(;;) + { + RMATCH(rrc, eptr, ecode, offset_top, md, ims, eptrb, 0); + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + if (eptr-- == pp) break; /* Stop if tried at original pos */ + BACKCHAR(eptr); + } + } + else +#endif + + /* Not UTF-8 mode */ + { + switch(ctype) + { + case OP_ANY: + if ((ims & PCRE_DOTALL) == 0) + { + for (i = min; i < max; i++) + { + if (eptr >= md->end_subject || *eptr == NEWLINE) break; + eptr++; + } + break; + } + /* For DOTALL case, fall through and treat as \C */ + + case OP_ANYBYTE: + c = max - min; + if (c > md->end_subject - eptr) c = md->end_subject - eptr; + eptr += c; + break; + + case OP_NOT_DIGIT: + for (i = min; i < max; i++) + { + if (eptr >= md->end_subject || (md->ctypes[*eptr] & ctype_digit) != 0) + break; + eptr++; + } + break; + + case OP_DIGIT: + for (i = min; i < max; i++) + { + if (eptr >= md->end_subject || (md->ctypes[*eptr] & ctype_digit) == 0) + break; + eptr++; + } + break; + + case OP_NOT_WHITESPACE: + for (i = min; i < max; i++) + { + if (eptr >= md->end_subject || (md->ctypes[*eptr] & ctype_space) != 0) + break; + eptr++; + } + break; + + case OP_WHITESPACE: + for (i = min; i < max; i++) + { + if (eptr >= md->end_subject || (md->ctypes[*eptr] & ctype_space) == 0) + break; + eptr++; + } + break; + + case OP_NOT_WORDCHAR: + for (i = min; i < max; i++) + { + if (eptr >= md->end_subject || (md->ctypes[*eptr] & ctype_word) != 0) + break; + eptr++; + } + break; + + case OP_WORDCHAR: + for (i = min; i < max; i++) + { + if (eptr >= md->end_subject || (md->ctypes[*eptr] & ctype_word) == 0) + break; + eptr++; + } + break; + + default: + RRETURN(PCRE_ERROR_INTERNAL); + } + + /* eptr is now past the end of the maximum run */ + + while (eptr >= pp) + { + RMATCH(rrc, eptr, ecode, offset_top, md, ims, eptrb, 0); + eptr--; + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + } + } + + /* Get here if we can't make it match with any permitted repetitions */ + + RRETURN(MATCH_NOMATCH); + } + /* Control never gets here */ + + /* There's been some horrible disaster. Since all codes > OP_BRA are + for capturing brackets, and there shouldn't be any gaps between 0 and + OP_BRA, arrival here can only mean there is something seriously wrong + in the code above or the OP_xxx definitions. */ + + default: + DPRINTF(("Unknown opcode %d\n", *ecode)); + RRETURN(PCRE_ERROR_UNKNOWN_NODE); + } + + /* Do not stick any code in here without much thought; it is assumed + that "continue" in the code above comes out to here to repeat the main + loop. */ + + } /* End of main loop */ +/* Control never reaches here */ +} + + +/*************************************************************************** +**************************************************************************** + RECURSION IN THE match() FUNCTION + +Undefine all the macros that were defined above to handle this. */ + +#ifdef NO_RECURSE +#undef eptr +#undef ecode +#undef offset_top +#undef ims +#undef eptrb +#undef flags + +#undef callpat +#undef charptr +#undef data +#undef next +#undef pp +#undef prev +#undef saved_eptr + +#undef new_recursive + +#undef cur_is_word +#undef condition +#undef minimize +#undef prev_is_word + +#undef original_ims + +#undef ctype +#undef length +#undef max +#undef min +#undef number +#undef offset +#undef op +#undef save_capture_last +#undef save_offset1 +#undef save_offset2 +#undef save_offset3 +#undef stacksave + +#undef newptrb + +#endif + +/* These two are defined as macros in both cases */ + +#undef fc +#undef fi + +/*************************************************************************** +***************************************************************************/ + + + +/************************************************* +* Execute a Regular Expression * +*************************************************/ + +/* This function applies a compiled re to a subject string and picks out +portions of the string if it matches. Two elements in the vector are set for +each substring: the offsets to the start and end of the substring. + +Arguments: + argument_re points to the compiled expression + extra_data points to extra data or is NULL + subject points to the subject string + length length of subject string (may contain binary zeros) + start_offset where to start in the subject string + options option bits + offsets points to a vector of ints to be filled in with offsets + offsetcount the number of elements in the vector + +Returns: > 0 => success; value is the number of elements filled in + = 0 => success, but offsets is not big enough + -1 => failed to match + < -1 => some kind of unexpected problem +*/ + +EXPORT int +pcre_exec(const pcre *argument_re, const pcre_extra *extra_data, + const char *subject, int length, int start_offset, int options, int *offsets, + int offsetcount) +{ +int rc, resetcount, ocount; +int first_byte = -1; +int req_byte = -1; +int req_byte2 = -1; +unsigned long int ims = 0; +BOOL using_temporary_offsets = FALSE; +BOOL anchored; +BOOL startline; +BOOL first_byte_caseless = FALSE; +BOOL req_byte_caseless = FALSE; +match_data match_block; +const uschar *tables; +const uschar *start_bits = NULL; +const uschar *start_match = (const uschar *)subject + start_offset; +const uschar *end_subject; +const uschar *req_byte_ptr = start_match - 1; + +pcre_study_data internal_study; +const pcre_study_data *study; + +real_pcre internal_re; +const real_pcre *external_re = (const real_pcre *)argument_re; +const real_pcre *re = external_re; + +/* Plausibility checks */ + +if ((options & ~PUBLIC_EXEC_OPTIONS) != 0) return PCRE_ERROR_BADOPTION; +if (re == NULL || subject == NULL || + (offsets == NULL && offsetcount > 0)) return PCRE_ERROR_NULL; +if (offsetcount < 0) return PCRE_ERROR_BADCOUNT; + +/* Fish out the optional data from the extra_data structure, first setting +the default values. */ + +study = NULL; +match_block.match_limit = MATCH_LIMIT; +match_block.callout_data = NULL; + +/* The table pointer is always in native byte order. */ + +tables = external_re->tables; + +if (extra_data != NULL) + { + register unsigned int flags = extra_data->flags; + if ((flags & PCRE_EXTRA_STUDY_DATA) != 0) + study = (const pcre_study_data *)extra_data->study_data; + if ((flags & PCRE_EXTRA_MATCH_LIMIT) != 0) + match_block.match_limit = extra_data->match_limit; + if ((flags & PCRE_EXTRA_CALLOUT_DATA) != 0) + match_block.callout_data = extra_data->callout_data; + if ((flags & PCRE_EXTRA_TABLES) != 0) tables = extra_data->tables; + } + +/* If the exec call supplied NULL for tables, use the inbuilt ones. This +is a feature that makes it possible to save compiled regex and re-use them +in other programs later. */ + +if (tables == NULL) tables = pcre_default_tables; + +/* Check that the first field in the block is the magic number. If it is not, +test for a regex that was compiled on a host of opposite endianness. If this is +the case, flipped values are put in internal_re and internal_study if there was +study data too. */ + +if (re->magic_number != MAGIC_NUMBER) + { + re = try_flipped(re, &internal_re, study, &internal_study); + if (re == NULL) return PCRE_ERROR_BADMAGIC; + if (study != NULL) study = &internal_study; + } + +/* Set up other data */ + +anchored = ((re->options | options) & PCRE_ANCHORED) != 0; +startline = (re->options & PCRE_STARTLINE) != 0; + +/* The code starts after the real_pcre block and the capture name table. */ + +match_block.start_code = (const uschar *)external_re + re->name_table_offset + + re->name_count * re->name_entry_size; + +match_block.start_subject = (const uschar *)subject; +match_block.start_offset = start_offset; +match_block.end_subject = match_block.start_subject + length; +end_subject = match_block.end_subject; + +match_block.endonly = (re->options & PCRE_DOLLAR_ENDONLY) != 0; +match_block.utf8 = (re->options & PCRE_UTF8) != 0; + +match_block.notbol = (options & PCRE_NOTBOL) != 0; +match_block.noteol = (options & PCRE_NOTEOL) != 0; +match_block.notempty = (options & PCRE_NOTEMPTY) != 0; +match_block.partial = (options & PCRE_PARTIAL) != 0; +match_block.hitend = FALSE; + +match_block.recursive = NULL; /* No recursion at top level */ + +match_block.lcc = tables + lcc_offset; +match_block.ctypes = tables + ctypes_offset; + +/* Partial matching is supported only for a restricted set of regexes at the +moment. */ + +if (match_block.partial && (re->options & PCRE_NOPARTIAL) != 0) + return PCRE_ERROR_BADPARTIAL; + +/* Check a UTF-8 string if required. Unfortunately there's no way of passing +back the character offset. */ + +#ifdef SUPPORT_UTF8 +if (match_block.utf8 && (options & PCRE_NO_UTF8_CHECK) == 0) + { + if (valid_utf8((uschar *)subject, length) >= 0) + return PCRE_ERROR_BADUTF8; + if (start_offset > 0 && start_offset < length) + { + int tb = ((uschar *)subject)[start_offset]; + if (tb > 127) + { + tb &= 0xc0; + if (tb != 0 && tb != 0xc0) return PCRE_ERROR_BADUTF8_OFFSET; + } + } + } +#endif + +/* The ims options can vary during the matching as a result of the presence +of (?ims) items in the pattern. They are kept in a local variable so that +restoring at the exit of a group is easy. */ + +ims = re->options & (PCRE_CASELESS|PCRE_MULTILINE|PCRE_DOTALL); + +/* If the expression has got more back references than the offsets supplied can +hold, we get a temporary chunk of working store to use during the matching. +Otherwise, we can use the vector supplied, rounding down its size to a multiple +of 3. */ + +ocount = offsetcount - (offsetcount % 3); + +if (re->top_backref > 0 && re->top_backref >= ocount/3) + { + ocount = re->top_backref * 3 + 3; + match_block.offset_vector = (int *)(pcre_malloc)(ocount * sizeof(int)); + if (match_block.offset_vector == NULL) return PCRE_ERROR_NOMEMORY; + using_temporary_offsets = TRUE; + DPRINTF(("Got memory to hold back references\n")); + } +else match_block.offset_vector = offsets; + +match_block.offset_end = ocount; +match_block.offset_max = (2*ocount)/3; +match_block.offset_overflow = FALSE; +match_block.capture_last = -1; + +/* Compute the minimum number of offsets that we need to reset each time. Doing +this makes a huge difference to execution time when there aren't many brackets +in the pattern. */ + +resetcount = 2 + re->top_bracket * 2; +if (resetcount > offsetcount) resetcount = ocount; + +/* Reset the working variable associated with each extraction. These should +never be used unless previously set, but they get saved and restored, and so we +initialize them to avoid reading uninitialized locations. */ + +if (match_block.offset_vector != NULL) + { + register int *iptr = match_block.offset_vector + ocount; + register int *iend = iptr - resetcount/2 + 1; + while (--iptr >= iend) *iptr = -1; + } + +/* Set up the first character to match, if available. The first_byte value is +never set for an anchored regular expression, but the anchoring may be forced +at run time, so we have to test for anchoring. The first char may be unset for +an unanchored pattern, of course. If there's no first char and the pattern was +studied, there may be a bitmap of possible first characters. */ + +if (!anchored) + { + if ((re->options & PCRE_FIRSTSET) != 0) + { + first_byte = re->first_byte & 255; + if ((first_byte_caseless = ((re->first_byte & REQ_CASELESS) != 0)) == TRUE) + first_byte = match_block.lcc[first_byte]; + } + else + if (!startline && study != NULL && + (study->options & PCRE_STUDY_MAPPED) != 0) + start_bits = study->start_bits; + } + +/* For anchored or unanchored matches, there may be a "last known required +character" set. */ + +if ((re->options & PCRE_REQCHSET) != 0) + { + req_byte = re->req_byte & 255; + req_byte_caseless = (re->req_byte & REQ_CASELESS) != 0; + req_byte2 = (tables + fcc_offset)[req_byte]; /* case flipped */ + } + +/* Loop for handling unanchored repeated matching attempts; for anchored regexs +the loop runs just once. */ + +do + { + /* Reset the maximum number of extractions we might see. */ + + if (match_block.offset_vector != NULL) + { + register int *iptr = match_block.offset_vector; + register int *iend = iptr + resetcount; + while (iptr < iend) *iptr++ = -1; + } + + /* Advance to a unique first char if possible */ + + if (first_byte >= 0) + { + if (first_byte_caseless) + while (start_match < end_subject && + match_block.lcc[*start_match] != first_byte) + start_match++; + else + while (start_match < end_subject && *start_match != first_byte) + start_match++; + } + + /* Or to just after \n for a multiline match if possible */ + + else if (startline) + { + if (start_match > match_block.start_subject + start_offset) + { + while (start_match < end_subject && start_match[-1] != NEWLINE) + start_match++; + } + } + + /* Or to a non-unique first char after study */ + + else if (start_bits != NULL) + { + while (start_match < end_subject) + { + register unsigned int c = *start_match; + if ((start_bits[c/8] & (1 << (c&7))) == 0) start_match++; else break; + } + } + +#ifdef DEBUG /* Sigh. Some compilers never learn. */ + printf(">>>> Match against: "); + pchars(start_match, end_subject - start_match, TRUE, &match_block); + printf("\n"); +#endif + + /* If req_byte is set, we know that that character must appear in the subject + for the match to succeed. If the first character is set, req_byte must be + later in the subject; otherwise the test starts at the match point. This + optimization can save a huge amount of backtracking in patterns with nested + unlimited repeats that aren't going to match. Writing separate code for + cased/caseless versions makes it go faster, as does using an autoincrement + and backing off on a match. + + HOWEVER: when the subject string is very, very long, searching to its end can + take a long time, and give bad performance on quite ordinary patterns. This + showed up when somebody was matching /^C/ on a 32-megabyte string... so we + don't do this when the string is sufficiently long. + + ALSO: this processing is disabled when partial matching is requested. + */ + + if (req_byte >= 0 && + end_subject - start_match < REQ_BYTE_MAX && + !match_block.partial) + { + register const uschar *p = start_match + ((first_byte >= 0)? 1 : 0); + + /* We don't need to repeat the search if we haven't yet reached the + place we found it at last time. */ + + if (p > req_byte_ptr) + { + if (req_byte_caseless) + { + while (p < end_subject) + { + register int pp = *p++; + if (pp == req_byte || pp == req_byte2) { p--; break; } + } + } + else + { + while (p < end_subject) + { + if (*p++ == req_byte) { p--; break; } + } + } + + /* If we can't find the required character, break the matching loop */ + + if (p >= end_subject) break; + + /* If we have found the required character, save the point where we + found it, so that we don't search again next time round the loop if + the start hasn't passed this character yet. */ + + req_byte_ptr = p; + } + } + + /* When a match occurs, substrings will be set for all internal extractions; + we just need to set up the whole thing as substring 0 before returning. If + there were too many extractions, set the return code to zero. In the case + where we had to get some local store to hold offsets for backreferences, copy + those back references that we can. In this case there need not be overflow + if certain parts of the pattern were not used. */ + + match_block.start_match = start_match; + match_block.match_call_count = 0; + + rc = match(start_match, match_block.start_code, 2, &match_block, ims, NULL, + match_isgroup); + + if (rc == MATCH_NOMATCH) + { + start_match++; +#ifdef SUPPORT_UTF8 + if (match_block.utf8) + while(start_match < end_subject && (*start_match & 0xc0) == 0x80) + start_match++; +#endif + continue; + } + + if (rc != MATCH_MATCH) + { + DPRINTF((">>>> error: returning %d\n", rc)); + return rc; + } + + /* We have a match! Copy the offset information from temporary store if + necessary */ + + if (using_temporary_offsets) + { + if (offsetcount >= 4) + { + memcpy(offsets + 2, match_block.offset_vector + 2, + (offsetcount - 2) * sizeof(int)); + DPRINTF(("Copied offsets from temporary memory\n")); + } + if (match_block.end_offset_top > offsetcount) + match_block.offset_overflow = TRUE; + + DPRINTF(("Freeing temporary memory\n")); + (pcre_free)(match_block.offset_vector); + } + + rc = match_block.offset_overflow? 0 : match_block.end_offset_top/2; + + if (offsetcount < 2) rc = 0; else + { + offsets[0] = start_match - match_block.start_subject; + offsets[1] = match_block.end_match_ptr - match_block.start_subject; + } + + DPRINTF((">>>> returning %d\n", rc)); + return rc; + } + +/* This "while" is the end of the "do" above */ + +while (!anchored && start_match <= end_subject); + +if (using_temporary_offsets) + { + DPRINTF(("Freeing temporary memory\n")); + (pcre_free)(match_block.offset_vector); + } + +if (match_block.partial && match_block.hitend) + { + DPRINTF((">>>> returning PCRE_ERROR_PARTIAL\n")); + return PCRE_ERROR_PARTIAL; + } +else + { + DPRINTF((">>>> returning PCRE_ERROR_NOMATCH\n")); + return PCRE_ERROR_NOMATCH; + } +} + +/* End of pcre.c */ diff --git a/Foundation/src/pcre.h b/Foundation/src/pcre.h index aa373893b..ee5bf16e7 100644 --- a/Foundation/src/pcre.h +++ b/Foundation/src/pcre.h @@ -1,239 +1,239 @@ -/************************************************* -* Perl-Compatible Regular Expressions * -*************************************************/ - -/* In its original form, this is the .in file that is transformed by -"configure" into pcre.h. - - Copyright (c) 1997-2004 University of Cambridge - ------------------------------------------------------------------------------ -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - * 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. - - * Neither the name of the University of Cambridge nor the names of its - contributors may be used to endorse or promote products derived from - this software without specific prior written permission. - -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 _PCRE_H -#define _PCRE_H - -/* The file pcre.h is build by "configure". Do not edit it; instead -make changes to pcre.in. */ - -#define PCRE_MAJOR 5 -#define PCRE_MINOR 0 -#define PCRE_DATE 13-Sep-2004 - -/* Win32 uses DLL by default */ - -#ifdef _WIN32 -# ifdef PCRE_DEFINITION -# ifdef DLL_EXPORT -# define PCRE_DATA_SCOPE __declspec(dllexport) -# endif -# else -# ifndef PCRE_STATIC -# define PCRE_DATA_SCOPE extern __declspec(dllimport) -# endif -# endif -#endif -#ifndef PCRE_DATA_SCOPE -# define PCRE_DATA_SCOPE extern -#endif - -/* Have to include stdlib.h in order to ensure that size_t is defined; -it is needed here for malloc. */ - -#include - -/* Allow for C++ users */ - -#ifdef __cplusplus -extern "C" { -#endif - -/* Options */ - -#define PCRE_CASELESS 0x0001 -#define PCRE_MULTILINE 0x0002 -#define PCRE_DOTALL 0x0004 -#define PCRE_EXTENDED 0x0008 -#define PCRE_ANCHORED 0x0010 -#define PCRE_DOLLAR_ENDONLY 0x0020 -#define PCRE_EXTRA 0x0040 -#define PCRE_NOTBOL 0x0080 -#define PCRE_NOTEOL 0x0100 -#define PCRE_UNGREEDY 0x0200 -#define PCRE_NOTEMPTY 0x0400 -#define PCRE_UTF8 0x0800 -#define PCRE_NO_AUTO_CAPTURE 0x1000 -#define PCRE_NO_UTF8_CHECK 0x2000 -#define PCRE_AUTO_CALLOUT 0x4000 -#define PCRE_PARTIAL 0x8000 - -/* Exec-time and get/set-time error codes */ - -#define PCRE_ERROR_NOMATCH (-1) -#define PCRE_ERROR_NULL (-2) -#define PCRE_ERROR_BADOPTION (-3) -#define PCRE_ERROR_BADMAGIC (-4) -#define PCRE_ERROR_UNKNOWN_NODE (-5) -#define PCRE_ERROR_NOMEMORY (-6) -#define PCRE_ERROR_NOSUBSTRING (-7) -#define PCRE_ERROR_MATCHLIMIT (-8) -#define PCRE_ERROR_CALLOUT (-9) /* Never used by PCRE itself */ -#define PCRE_ERROR_BADUTF8 (-10) -#define PCRE_ERROR_BADUTF8_OFFSET (-11) -#define PCRE_ERROR_PARTIAL (-12) -#define PCRE_ERROR_BADPARTIAL (-13) -#define PCRE_ERROR_INTERNAL (-14) -#define PCRE_ERROR_BADCOUNT (-15) - -/* Request types for pcre_fullinfo() */ - -#define PCRE_INFO_OPTIONS 0 -#define PCRE_INFO_SIZE 1 -#define PCRE_INFO_CAPTURECOUNT 2 -#define PCRE_INFO_BACKREFMAX 3 -#define PCRE_INFO_FIRSTBYTE 4 -#define PCRE_INFO_FIRSTCHAR 4 /* For backwards compatibility */ -#define PCRE_INFO_FIRSTTABLE 5 -#define PCRE_INFO_LASTLITERAL 6 -#define PCRE_INFO_NAMEENTRYSIZE 7 -#define PCRE_INFO_NAMECOUNT 8 -#define PCRE_INFO_NAMETABLE 9 -#define PCRE_INFO_STUDYSIZE 10 -#define PCRE_INFO_DEFAULT_TABLES 11 - -/* Request types for pcre_config() */ - -#define PCRE_CONFIG_UTF8 0 -#define PCRE_CONFIG_NEWLINE 1 -#define PCRE_CONFIG_LINK_SIZE 2 -#define PCRE_CONFIG_POSIX_MALLOC_THRESHOLD 3 -#define PCRE_CONFIG_MATCH_LIMIT 4 -#define PCRE_CONFIG_STACKRECURSE 5 -#define PCRE_CONFIG_UNICODE_PROPERTIES 6 - -/* Bit flags for the pcre_extra structure */ - -#define PCRE_EXTRA_STUDY_DATA 0x0001 -#define PCRE_EXTRA_MATCH_LIMIT 0x0002 -#define PCRE_EXTRA_CALLOUT_DATA 0x0004 -#define PCRE_EXTRA_TABLES 0x0008 - -/* Types */ - -struct real_pcre; /* declaration; the definition is private */ -typedef struct real_pcre pcre; - -/* The structure for passing additional data to pcre_exec(). This is defined in -such as way as to be extensible. Always add new fields at the end, in order to -remain compatible. */ - -typedef struct pcre_extra { - unsigned long int flags; /* Bits for which fields are set */ - void *study_data; /* Opaque data from pcre_study() */ - unsigned long int match_limit; /* Maximum number of calls to match() */ - void *callout_data; /* Data passed back in callouts */ - const unsigned char *tables; /* Pointer to character tables */ -} pcre_extra; - -/* The structure for passing out data via the pcre_callout_function. We use a -structure so that new fields can be added on the end in future versions, -without changing the API of the function, thereby allowing old clients to work -without modification. */ - -typedef struct pcre_callout_block { - int version; /* Identifies version of block */ - /* ------------------------ Version 0 ------------------------------- */ - int callout_number; /* Number compiled into pattern */ - int *offset_vector; /* The offset vector */ - const char *subject; /* The subject being matched */ - int subject_length; /* The length of the subject */ - int start_match; /* Offset to start of this match attempt */ - int current_position; /* Where we currently are in the subject */ - int capture_top; /* Max current capture */ - int capture_last; /* Most recently closed capture */ - void *callout_data; /* Data passed in with the call */ - /* ------------------- Added for Version 1 -------------------------- */ - int pattern_position; /* Offset to next item in the pattern */ - int next_item_length; /* Length of next item in the pattern */ - /* ------------------------------------------------------------------ */ -} pcre_callout_block; - -/* Indirection for store get and free functions. These can be set to -alternative malloc/free functions if required. Special ones are used in the -non-recursive case for "frames". There is also an optional callout function -that is triggered by the (?) regex item. Some magic is required for Win32 DLL; -it is null on other OS. For Virtual Pascal, these have to be different again. -*/ - -#ifndef VPCOMPAT -PCRE_DATA_SCOPE void *(*pcre_malloc)(size_t); -PCRE_DATA_SCOPE void (*pcre_free)(void *); -PCRE_DATA_SCOPE void *(*pcre_stack_malloc)(size_t); -PCRE_DATA_SCOPE void (*pcre_stack_free)(void *); -PCRE_DATA_SCOPE int (*pcre_callout)(pcre_callout_block *); -#else /* VPCOMPAT */ -extern void *pcre_malloc(size_t); -extern void pcre_free(void *); -extern void *pcre_stack_malloc(size_t); -extern void pcre_stack_free(void *); -extern int pcre_callout(pcre_callout_block *); -#endif /* VPCOMPAT */ - -/* Exported PCRE functions */ - -extern pcre *pcre_compile(const char *, int, const char **, - int *, const unsigned char *); -extern int pcre_config(int, void *); -extern int pcre_copy_named_substring(const pcre *, const char *, - int *, int, const char *, char *, int); -extern int pcre_copy_substring(const char *, int *, int, int, - char *, int); -extern int pcre_exec(const pcre *, const pcre_extra *, - const char *, int, int, int, int *, int); -extern void pcre_free_substring(const char *); -extern void pcre_free_substring_list(const char **); -extern int pcre_fullinfo(const pcre *, const pcre_extra *, int, - void *); -extern int pcre_get_named_substring(const pcre *, const char *, - int *, int, const char *, const char **); -extern int pcre_get_stringnumber(const pcre *, const char *); -extern int pcre_get_substring(const char *, int *, int, int, - const char **); -extern int pcre_get_substring_list(const char *, int *, int, - const char ***); -extern int pcre_info(const pcre *, int *, int *); -extern const unsigned char *pcre_maketables(void); -extern pcre_extra *pcre_study(const pcre *, int, const char **); -extern const char *pcre_version(void); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif /* End of pcre.h */ +/************************************************* +* Perl-Compatible Regular Expressions * +*************************************************/ + +/* In its original form, this is the .in file that is transformed by +"configure" into pcre.h. + + Copyright (c) 1997-2004 University of Cambridge + +----------------------------------------------------------------------------- +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + * 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. + + * Neither the name of the University of Cambridge nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +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 _PCRE_H +#define _PCRE_H + +/* The file pcre.h is build by "configure". Do not edit it; instead +make changes to pcre.in. */ + +#define PCRE_MAJOR 5 +#define PCRE_MINOR 0 +#define PCRE_DATE 13-Sep-2004 + +/* Win32 uses DLL by default */ + +#ifdef _WIN32 +# ifdef PCRE_DEFINITION +# ifdef DLL_EXPORT +# define PCRE_DATA_SCOPE __declspec(dllexport) +# endif +# else +# ifndef PCRE_STATIC +# define PCRE_DATA_SCOPE extern __declspec(dllimport) +# endif +# endif +#endif +#ifndef PCRE_DATA_SCOPE +# define PCRE_DATA_SCOPE extern +#endif + +/* Have to include stdlib.h in order to ensure that size_t is defined; +it is needed here for malloc. */ + +#include + +/* Allow for C++ users */ + +#ifdef __cplusplus +extern "C" { +#endif + +/* Options */ + +#define PCRE_CASELESS 0x0001 +#define PCRE_MULTILINE 0x0002 +#define PCRE_DOTALL 0x0004 +#define PCRE_EXTENDED 0x0008 +#define PCRE_ANCHORED 0x0010 +#define PCRE_DOLLAR_ENDONLY 0x0020 +#define PCRE_EXTRA 0x0040 +#define PCRE_NOTBOL 0x0080 +#define PCRE_NOTEOL 0x0100 +#define PCRE_UNGREEDY 0x0200 +#define PCRE_NOTEMPTY 0x0400 +#define PCRE_UTF8 0x0800 +#define PCRE_NO_AUTO_CAPTURE 0x1000 +#define PCRE_NO_UTF8_CHECK 0x2000 +#define PCRE_AUTO_CALLOUT 0x4000 +#define PCRE_PARTIAL 0x8000 + +/* Exec-time and get/set-time error codes */ + +#define PCRE_ERROR_NOMATCH (-1) +#define PCRE_ERROR_NULL (-2) +#define PCRE_ERROR_BADOPTION (-3) +#define PCRE_ERROR_BADMAGIC (-4) +#define PCRE_ERROR_UNKNOWN_NODE (-5) +#define PCRE_ERROR_NOMEMORY (-6) +#define PCRE_ERROR_NOSUBSTRING (-7) +#define PCRE_ERROR_MATCHLIMIT (-8) +#define PCRE_ERROR_CALLOUT (-9) /* Never used by PCRE itself */ +#define PCRE_ERROR_BADUTF8 (-10) +#define PCRE_ERROR_BADUTF8_OFFSET (-11) +#define PCRE_ERROR_PARTIAL (-12) +#define PCRE_ERROR_BADPARTIAL (-13) +#define PCRE_ERROR_INTERNAL (-14) +#define PCRE_ERROR_BADCOUNT (-15) + +/* Request types for pcre_fullinfo() */ + +#define PCRE_INFO_OPTIONS 0 +#define PCRE_INFO_SIZE 1 +#define PCRE_INFO_CAPTURECOUNT 2 +#define PCRE_INFO_BACKREFMAX 3 +#define PCRE_INFO_FIRSTBYTE 4 +#define PCRE_INFO_FIRSTCHAR 4 /* For backwards compatibility */ +#define PCRE_INFO_FIRSTTABLE 5 +#define PCRE_INFO_LASTLITERAL 6 +#define PCRE_INFO_NAMEENTRYSIZE 7 +#define PCRE_INFO_NAMECOUNT 8 +#define PCRE_INFO_NAMETABLE 9 +#define PCRE_INFO_STUDYSIZE 10 +#define PCRE_INFO_DEFAULT_TABLES 11 + +/* Request types for pcre_config() */ + +#define PCRE_CONFIG_UTF8 0 +#define PCRE_CONFIG_NEWLINE 1 +#define PCRE_CONFIG_LINK_SIZE 2 +#define PCRE_CONFIG_POSIX_MALLOC_THRESHOLD 3 +#define PCRE_CONFIG_MATCH_LIMIT 4 +#define PCRE_CONFIG_STACKRECURSE 5 +#define PCRE_CONFIG_UNICODE_PROPERTIES 6 + +/* Bit flags for the pcre_extra structure */ + +#define PCRE_EXTRA_STUDY_DATA 0x0001 +#define PCRE_EXTRA_MATCH_LIMIT 0x0002 +#define PCRE_EXTRA_CALLOUT_DATA 0x0004 +#define PCRE_EXTRA_TABLES 0x0008 + +/* Types */ + +struct real_pcre; /* declaration; the definition is private */ +typedef struct real_pcre pcre; + +/* The structure for passing additional data to pcre_exec(). This is defined in +such as way as to be extensible. Always add new fields at the end, in order to +remain compatible. */ + +typedef struct pcre_extra { + unsigned long int flags; /* Bits for which fields are set */ + void *study_data; /* Opaque data from pcre_study() */ + unsigned long int match_limit; /* Maximum number of calls to match() */ + void *callout_data; /* Data passed back in callouts */ + const unsigned char *tables; /* Pointer to character tables */ +} pcre_extra; + +/* The structure for passing out data via the pcre_callout_function. We use a +structure so that new fields can be added on the end in future versions, +without changing the API of the function, thereby allowing old clients to work +without modification. */ + +typedef struct pcre_callout_block { + int version; /* Identifies version of block */ + /* ------------------------ Version 0 ------------------------------- */ + int callout_number; /* Number compiled into pattern */ + int *offset_vector; /* The offset vector */ + const char *subject; /* The subject being matched */ + int subject_length; /* The length of the subject */ + int start_match; /* Offset to start of this match attempt */ + int current_position; /* Where we currently are in the subject */ + int capture_top; /* Max current capture */ + int capture_last; /* Most recently closed capture */ + void *callout_data; /* Data passed in with the call */ + /* ------------------- Added for Version 1 -------------------------- */ + int pattern_position; /* Offset to next item in the pattern */ + int next_item_length; /* Length of next item in the pattern */ + /* ------------------------------------------------------------------ */ +} pcre_callout_block; + +/* Indirection for store get and free functions. These can be set to +alternative malloc/free functions if required. Special ones are used in the +non-recursive case for "frames". There is also an optional callout function +that is triggered by the (?) regex item. Some magic is required for Win32 DLL; +it is null on other OS. For Virtual Pascal, these have to be different again. +*/ + +#ifndef VPCOMPAT +PCRE_DATA_SCOPE void *(*pcre_malloc)(size_t); +PCRE_DATA_SCOPE void (*pcre_free)(void *); +PCRE_DATA_SCOPE void *(*pcre_stack_malloc)(size_t); +PCRE_DATA_SCOPE void (*pcre_stack_free)(void *); +PCRE_DATA_SCOPE int (*pcre_callout)(pcre_callout_block *); +#else /* VPCOMPAT */ +extern void *pcre_malloc(size_t); +extern void pcre_free(void *); +extern void *pcre_stack_malloc(size_t); +extern void pcre_stack_free(void *); +extern int pcre_callout(pcre_callout_block *); +#endif /* VPCOMPAT */ + +/* Exported PCRE functions */ + +extern pcre *pcre_compile(const char *, int, const char **, + int *, const unsigned char *); +extern int pcre_config(int, void *); +extern int pcre_copy_named_substring(const pcre *, const char *, + int *, int, const char *, char *, int); +extern int pcre_copy_substring(const char *, int *, int, int, + char *, int); +extern int pcre_exec(const pcre *, const pcre_extra *, + const char *, int, int, int, int *, int); +extern void pcre_free_substring(const char *); +extern void pcre_free_substring_list(const char **); +extern int pcre_fullinfo(const pcre *, const pcre_extra *, int, + void *); +extern int pcre_get_named_substring(const pcre *, const char *, + int *, int, const char *, const char **); +extern int pcre_get_stringnumber(const pcre *, const char *); +extern int pcre_get_substring(const char *, int *, int, int, + const char **); +extern int pcre_get_substring_list(const char *, int *, int, + const char ***); +extern int pcre_info(const pcre *, int *, int *); +extern const unsigned char *pcre_maketables(void); +extern pcre_extra *pcre_study(const pcre *, int, const char **); +extern const char *pcre_version(void); + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +#endif /* End of pcre.h */ diff --git a/Foundation/src/pcreconfig.h b/Foundation/src/pcreconfig.h index 2d837518b..9e220ea66 100644 --- a/Foundation/src/pcreconfig.h +++ b/Foundation/src/pcreconfig.h @@ -1,125 +1,125 @@ - -/* On Unix systems config.in is converted by configure into config.h. PCRE is -written in Standard C, but there are a few non-standard things it can cope -with, allowing it to run on SunOS4 and other "close to standard" systems. - -On a non-Unix system you should just copy this file into config.h, and set up -the macros the way you need them. You should normally change the definitions of -HAVE_STRERROR and HAVE_MEMMOVE to 1. Unfortunately, because of the way autoconf -works, these cannot be made the defaults. If your system has bcopy() and not -memmove(), change the definition of HAVE_BCOPY instead of HAVE_MEMMOVE. If your -system has neither bcopy() nor memmove(), leave them both as 0; an emulation -function will be used. */ - -/* If you are compiling for a system that uses EBCDIC instead of ASCII -character codes, define this macro as 1. On systems that can use "configure", -this can be done via --enable-ebcdic. */ - -#ifndef EBCDIC -#define EBCDIC 0 -#endif - -/* If you are compiling for a system that needs some magic to be inserted -before the definition of an exported function, define this macro to contain the -relevant magic. It apears at the start of every exported function. */ - -#define EXPORT - -/* Define to empty if the "const" keyword does not work. */ - -#undef const - -/* Define to "unsigned" if doesn't define size_t. */ - -#undef size_t - -/* The following two definitions are mainly for the benefit of SunOS4, which -doesn't have the strerror() or memmove() functions that should be present in -all Standard C libraries. The macros HAVE_STRERROR and HAVE_MEMMOVE should -normally be defined with the value 1 for other systems, but unfortunately we -can't make this the default because "configure" files generated by autoconf -will only change 0 to 1; they won't change 1 to 0 if the functions are not -found. */ - -#define HAVE_STRERROR 1 -#define HAVE_MEMMOVE 1 - -/* There are some non-Unix systems that don't even have bcopy(). If this macro -is false, an emulation is used. If HAVE_MEMMOVE is set to 1, the value of -HAVE_BCOPY is not relevant. */ - -#define HAVE_BCOPY 0 - -/* The value of NEWLINE determines the newline character. The default is to -leave it up to the compiler, but some sites want to force a particular value. -On Unix systems, "configure" can be used to override this default. */ - -#ifndef NEWLINE -#define NEWLINE '\n' -#endif - -/* The value of LINK_SIZE determines the number of bytes used to store -links as offsets within the compiled regex. The default is 2, which allows for -compiled patterns up to 64K long. This covers the vast majority of cases. -However, PCRE can also be compiled to use 3 or 4 bytes instead. This allows for -longer patterns in extreme cases. On Unix systems, "configure" can be used to -override this default. */ - -#ifndef LINK_SIZE -#define LINK_SIZE 2 -#endif - -/* The value of MATCH_LIMIT determines the default number of times the match() -function can be called during a single execution of pcre_exec(). (There is a -runtime method of setting a different limit.) The limit exists in order to -catch runaway regular expressions that take for ever to determine that they do -not match. The default is set very large so that it does not accidentally catch -legitimate cases. On Unix systems, "configure" can be used to override this -default default. */ - -#ifndef MATCH_LIMIT -#define MATCH_LIMIT 10000000 -#endif - -/* When calling PCRE via the POSIX interface, additional working storage is -required for holding the pointers to capturing substrings because PCRE requires -three integers per substring, whereas the POSIX interface provides only two. If -the number of expected substrings is small, the wrapper function uses space on -the stack, because this is faster than using malloc() for each call. The -threshold above which the stack is no longer use is defined by POSIX_MALLOC_ -THRESHOLD. On Unix systems, "configure" can be used to override this default. -*/ - -#ifndef POSIX_MALLOC_THRESHOLD -#define POSIX_MALLOC_THRESHOLD 10 -#endif - -/* PCRE uses recursive function calls to handle backtracking while matching. -This can sometimes be a problem on systems that have stacks of limited size. -Define NO_RECURSE to get a version that doesn't use recursion in the match() -function; instead it creates its own stack by steam using pcre_recurse_malloc -to get memory. For more detail, see comments and other stuff just above the -match() function. On Unix systems, "configure" can be used to set this in the -Makefile (use --disable-stack-for-recursion). */ - -/* #define NO_RECURSE */ - - -#ifndef POSIX_MALLOC_THRESHOLD -#define POSIX_MALLOC_THRESHOLD 10 -#endif - - -#ifndef SUPPORT_UTF8 -#define SUPPORT_UTF8 1 -#endif - - -#if defined(_MSC_VER) -#pragma warning(disable:4244) -#pragma warning(disable:4267) -#pragma warning(disable:4090) -#endif - - -/* End */ + +/* On Unix systems config.in is converted by configure into config.h. PCRE is +written in Standard C, but there are a few non-standard things it can cope +with, allowing it to run on SunOS4 and other "close to standard" systems. + +On a non-Unix system you should just copy this file into config.h, and set up +the macros the way you need them. You should normally change the definitions of +HAVE_STRERROR and HAVE_MEMMOVE to 1. Unfortunately, because of the way autoconf +works, these cannot be made the defaults. If your system has bcopy() and not +memmove(), change the definition of HAVE_BCOPY instead of HAVE_MEMMOVE. If your +system has neither bcopy() nor memmove(), leave them both as 0; an emulation +function will be used. */ + +/* If you are compiling for a system that uses EBCDIC instead of ASCII +character codes, define this macro as 1. On systems that can use "configure", +this can be done via --enable-ebcdic. */ + +#ifndef EBCDIC +#define EBCDIC 0 +#endif + +/* If you are compiling for a system that needs some magic to be inserted +before the definition of an exported function, define this macro to contain the +relevant magic. It apears at the start of every exported function. */ + +#define EXPORT + +/* Define to empty if the "const" keyword does not work. */ + +#undef const + +/* Define to "unsigned" if doesn't define size_t. */ + +#undef size_t + +/* The following two definitions are mainly for the benefit of SunOS4, which +doesn't have the strerror() or memmove() functions that should be present in +all Standard C libraries. The macros HAVE_STRERROR and HAVE_MEMMOVE should +normally be defined with the value 1 for other systems, but unfortunately we +can't make this the default because "configure" files generated by autoconf +will only change 0 to 1; they won't change 1 to 0 if the functions are not +found. */ + +#define HAVE_STRERROR 1 +#define HAVE_MEMMOVE 1 + +/* There are some non-Unix systems that don't even have bcopy(). If this macro +is false, an emulation is used. If HAVE_MEMMOVE is set to 1, the value of +HAVE_BCOPY is not relevant. */ + +#define HAVE_BCOPY 0 + +/* The value of NEWLINE determines the newline character. The default is to +leave it up to the compiler, but some sites want to force a particular value. +On Unix systems, "configure" can be used to override this default. */ + +#ifndef NEWLINE +#define NEWLINE '\n' +#endif + +/* The value of LINK_SIZE determines the number of bytes used to store +links as offsets within the compiled regex. The default is 2, which allows for +compiled patterns up to 64K long. This covers the vast majority of cases. +However, PCRE can also be compiled to use 3 or 4 bytes instead. This allows for +longer patterns in extreme cases. On Unix systems, "configure" can be used to +override this default. */ + +#ifndef LINK_SIZE +#define LINK_SIZE 2 +#endif + +/* The value of MATCH_LIMIT determines the default number of times the match() +function can be called during a single execution of pcre_exec(). (There is a +runtime method of setting a different limit.) The limit exists in order to +catch runaway regular expressions that take for ever to determine that they do +not match. The default is set very large so that it does not accidentally catch +legitimate cases. On Unix systems, "configure" can be used to override this +default default. */ + +#ifndef MATCH_LIMIT +#define MATCH_LIMIT 10000000 +#endif + +/* When calling PCRE via the POSIX interface, additional working storage is +required for holding the pointers to capturing substrings because PCRE requires +three integers per substring, whereas the POSIX interface provides only two. If +the number of expected substrings is small, the wrapper function uses space on +the stack, because this is faster than using malloc() for each call. The +threshold above which the stack is no longer use is defined by POSIX_MALLOC_ +THRESHOLD. On Unix systems, "configure" can be used to override this default. +*/ + +#ifndef POSIX_MALLOC_THRESHOLD +#define POSIX_MALLOC_THRESHOLD 10 +#endif + +/* PCRE uses recursive function calls to handle backtracking while matching. +This can sometimes be a problem on systems that have stacks of limited size. +Define NO_RECURSE to get a version that doesn't use recursion in the match() +function; instead it creates its own stack by steam using pcre_recurse_malloc +to get memory. For more detail, see comments and other stuff just above the +match() function. On Unix systems, "configure" can be used to set this in the +Makefile (use --disable-stack-for-recursion). */ + +/* #define NO_RECURSE */ + + +#ifndef POSIX_MALLOC_THRESHOLD +#define POSIX_MALLOC_THRESHOLD 10 +#endif + + +#ifndef SUPPORT_UTF8 +#define SUPPORT_UTF8 1 +#endif + + +#if defined(_MSC_VER) +#pragma warning(disable:4244) +#pragma warning(disable:4267) +#pragma warning(disable:4090) +#endif + + +/* End */ diff --git a/Foundation/src/pcreinternal.h b/Foundation/src/pcreinternal.h index a71a3b10d..937c9a228 100644 --- a/Foundation/src/pcreinternal.h +++ b/Foundation/src/pcreinternal.h @@ -1,752 +1,752 @@ -/************************************************* -* Perl-Compatible Regular Expressions * -*************************************************/ - - -/* This is a library of functions to support regular expressions whose syntax -and semantics are as close as possible to those of the Perl 5 language. See -the file doc/Tech.Notes for some information on the internals. - -Written by: Philip Hazel - - Copyright (c) 1997-2004 University of Cambridge - ------------------------------------------------------------------------------ -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - * 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. - - * Neither the name of the University of Cambridge nor the names of its - contributors may be used to endorse or promote products derived from - this software without specific prior written permission. - -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. ------------------------------------------------------------------------------ -*/ - -/* This header contains definitions that are shared between the different -modules, but which are not relevant to the outside. */ - -/* Get the definitions provided by running "configure" */ - -#include "pcreconfig.h" - -/* Standard C headers plus the external interface definition. The only time -setjmp and stdarg are used is when NO_RECURSE is set. */ - -#include -#include -#include -#include -#include -#include -#include -#include - -#ifndef PCRE_SPY -#define PCRE_DEFINITION /* Win32 __declspec(export) trigger for .dll */ -#endif - -/* We need to have types that specify unsigned 16-bit and 32-bit integers. We -cannot determine these outside the compilation (e.g. by running a program as -part of "configure") because PCRE is often cross-compiled for use on other -systems. Instead we make use of the maximum sizes that are available at -preprocessor time in standard C environments. */ - -#if USHRT_MAX == 65535 - typedef unsigned short pcre_uint16; -#elif UINT_MAX == 65535 - typedef unsigned int pcre_uint16; -#else - #error Cannot determine a type for 16-bit unsigned integers -#endif - -#if UINT_MAX == 4294967295 - typedef unsigned int pcre_uint32; -#elif ULONG_MAX == 4294967295 - typedef unsigned long int pcre_uint32; -#else - #error Cannot determine a type for 32-bit unsigned integers -#endif - -/* All character handling must be done as unsigned characters. Otherwise there -are problems with top-bit-set characters and functions such as isspace(). -However, we leave the interface to the outside world as char *, because that -should make things easier for callers. We define a short type for unsigned char -to save lots of typing. I tried "uchar", but it causes problems on Digital -Unix, where it is defined in sys/types, so use "uschar" instead. */ - -typedef unsigned char uschar; - -/* Include the public PCRE header */ - -#include "pcre.h" - -/* When compiling for use with the Virtual Pascal compiler, these functions -need to have their names changed. PCRE must be compiled with the -DVPCOMPAT -option on the command line. */ - -#ifdef VPCOMPAT -#define strncmp(s1,s2,m) _strncmp(s1,s2,m) -#define memcpy(d,s,n) _memcpy(d,s,n) -#define memmove(d,s,n) _memmove(d,s,n) -#define memset(s,c,n) _memset(s,c,n) -#else /* VPCOMPAT */ - -/* To cope with SunOS4 and other systems that lack memmove() but have bcopy(), -define a macro for memmove() if HAVE_MEMMOVE is false, provided that HAVE_BCOPY -is set. Otherwise, include an emulating function for those systems that have -neither (there some non-Unix environments where this is the case). This assumes -that all calls to memmove are moving strings upwards in store, which is the -case in PCRE. */ - -#if ! HAVE_MEMMOVE -#undef memmove /* some systems may have a macro */ -#if HAVE_BCOPY -#define memmove(a, b, c) bcopy(b, a, c) -#else /* HAVE_BCOPY */ -void * -pcre_memmove(unsigned char *dest, const unsigned char *src, size_t n) -{ -int i; -dest += n; -src += n; -for (i = 0; i < n; ++i) *(--dest) = *(--src); -} -#define memmove(a, b, c) pcre_memmove(a, b, c) -#endif /* not HAVE_BCOPY */ -#endif /* not HAVE_MEMMOVE */ -#endif /* not VPCOMPAT */ - - -/* PCRE keeps offsets in its compiled code as 2-byte quantities (always stored -in big-endian order) by default. These are used, for example, to link from the -start of a subpattern to its alternatives and its end. The use of 2 bytes per -offset limits the size of the compiled regex to around 64K, which is big enough -for almost everybody. However, I received a request for an even bigger limit. -For this reason, and also to make the code easier to maintain, the storing and -loading of offsets from the byte string is now handled by the macros that are -defined here. - -The macros are controlled by the value of LINK_SIZE. This defaults to 2 in -the config.h file, but can be overridden by using -D on the command line. This -is automated on Unix systems via the "configure" command. */ - -#if LINK_SIZE == 2 - -#define PUT(a,n,d) \ - (a[n] = (d) >> 8), \ - (a[(n)+1] = (d) & 255) - -#define GET(a,n) \ - (((a)[n] << 8) | (a)[(n)+1]) - -#define MAX_PATTERN_SIZE (1 << 16) - - -#elif LINK_SIZE == 3 - -#define PUT(a,n,d) \ - (a[n] = (d) >> 16), \ - (a[(n)+1] = (d) >> 8), \ - (a[(n)+2] = (d) & 255) - -#define GET(a,n) \ - (((a)[n] << 16) | ((a)[(n)+1] << 8) | (a)[(n)+2]) - -#define MAX_PATTERN_SIZE (1 << 24) - - -#elif LINK_SIZE == 4 - -#define PUT(a,n,d) \ - (a[n] = (d) >> 24), \ - (a[(n)+1] = (d) >> 16), \ - (a[(n)+2] = (d) >> 8), \ - (a[(n)+3] = (d) & 255) - -#define GET(a,n) \ - (((a)[n] << 24) | ((a)[(n)+1] << 16) | ((a)[(n)+2] << 8) | (a)[(n)+3]) - -#define MAX_PATTERN_SIZE (1 << 30) /* Keep it positive */ - - -#else -#error LINK_SIZE must be either 2, 3, or 4 -#endif - - -/* Convenience macro defined in terms of the others */ - -#define PUTINC(a,n,d) PUT(a,n,d), a += LINK_SIZE - - -/* PCRE uses some other 2-byte quantities that do not change when the size of -offsets changes. There are used for repeat counts and for other things such as -capturing parenthesis numbers in back references. */ - -#define PUT2(a,n,d) \ - a[n] = (d) >> 8; \ - a[(n)+1] = (d) & 255 - -#define GET2(a,n) \ - (((a)[n] << 8) | (a)[(n)+1]) - -#define PUT2INC(a,n,d) PUT2(a,n,d), a += 2 - - -/* In case there is no definition of offsetof() provided - though any proper -Standard C system should have one. */ - -#ifndef offsetof -#define offsetof(p_type,field) ((size_t)&(((p_type *)0)->field)) -#endif - - -/* These are the public options that can change during matching. */ - -#define PCRE_IMS (PCRE_CASELESS|PCRE_MULTILINE|PCRE_DOTALL) - -/* Private options flags start at the most significant end of the four bytes, -but skip the top bit so we can use ints for convenience without getting tangled -with negative values. The public options defined in pcre.h start at the least -significant end. Make sure they don't overlap, though now that we have expanded -to four bytes, there is plenty of space. */ - -#define PCRE_FIRSTSET 0x40000000 /* first_byte is set */ -#define PCRE_REQCHSET 0x20000000 /* req_byte is set */ -#define PCRE_STARTLINE 0x10000000 /* start after \n for multiline */ -#define PCRE_ICHANGED 0x08000000 /* i option changes within regex */ -#define PCRE_NOPARTIAL 0x04000000 /* can't use partial with this regex */ - -/* Options for the "extra" block produced by pcre_study(). */ - -#define PCRE_STUDY_MAPPED 0x01 /* a map of starting chars exists */ - -/* Masks for identifying the public options which are permitted at compile -time, run time or study time, respectively. */ - -#define PUBLIC_OPTIONS \ - (PCRE_CASELESS|PCRE_EXTENDED|PCRE_ANCHORED|PCRE_MULTILINE| \ - PCRE_DOTALL|PCRE_DOLLAR_ENDONLY|PCRE_EXTRA|PCRE_UNGREEDY|PCRE_UTF8| \ - PCRE_NO_AUTO_CAPTURE|PCRE_NO_UTF8_CHECK|PCRE_AUTO_CALLOUT) - -#define PUBLIC_EXEC_OPTIONS \ - (PCRE_ANCHORED|PCRE_NOTBOL|PCRE_NOTEOL|PCRE_NOTEMPTY|PCRE_NO_UTF8_CHECK| \ - PCRE_PARTIAL) - -#define PUBLIC_STUDY_OPTIONS 0 /* None defined */ - -/* Magic number to provide a small check against being handed junk. */ - -#define MAGIC_NUMBER 0x50435245UL /* 'PCRE' */ - -/* Negative values for the firstchar and reqchar variables */ - -#define REQ_UNSET (-2) -#define REQ_NONE (-1) - -/* Flags added to firstbyte or reqbyte; a "non-literal" item is either a -variable-length repeat, or a anything other than literal characters. */ - -#define REQ_CASELESS 0x0100 /* indicates caselessness */ -#define REQ_VARY 0x0200 /* reqbyte followed non-literal item */ - -/* Miscellaneous definitions */ - -typedef int BOOL; - -#define FALSE 0 -#define TRUE 1 - -/* Escape items that are just an encoding of a particular data value. Note that -ESC_n is defined as yet another macro, which is set in config.h to either \n -(the default) or \r (which some people want). */ - -#ifndef ESC_e -#define ESC_e 27 -#endif - -#ifndef ESC_f -#define ESC_f '\f' -#endif - -#ifndef ESC_n -#define ESC_n NEWLINE -#endif - -#ifndef ESC_r -#define ESC_r '\r' -#endif - -/* We can't officially use ESC_t because it is a POSIX reserved identifier -(presumably because of all the others like size_t). */ - -#ifndef ESC_tee -#define ESC_tee '\t' -#endif - -/* These are escaped items that aren't just an encoding of a particular data -value such as \n. They must have non-zero values, as check_escape() returns -their negation. Also, they must appear in the same order as in the opcode -definitions below, up to ESC_z. There's a dummy for OP_ANY because it -corresponds to "." rather than an escape sequence. The final one must be -ESC_REF as subsequent values are used for \1, \2, \3, etc. There is are two -tests in the code for an escape greater than ESC_b and less than ESC_Z to -detect the types that may be repeated. These are the types that consume -characters. If any new escapes are put in between that don't consume a -character, that code will have to change. */ - -enum { ESC_A = 1, ESC_G, ESC_B, ESC_b, ESC_D, ESC_d, ESC_S, ESC_s, ESC_W, - ESC_w, ESC_dum1, ESC_C, ESC_P, ESC_p, ESC_X, ESC_Z, ESC_z, ESC_E, - ESC_Q, ESC_REF }; - -/* Flag bits and data types for the extended class (OP_XCLASS) for classes that -contain UTF-8 characters with values greater than 255. */ - -#define XCL_NOT 0x01 /* Flag: this is a negative class */ -#define XCL_MAP 0x02 /* Flag: a 32-byte map is present */ - -#define XCL_END 0 /* Marks end of individual items */ -#define XCL_SINGLE 1 /* Single item (one multibyte char) follows */ -#define XCL_RANGE 2 /* A range (two multibyte chars) follows */ -#define XCL_PROP 3 /* Unicode property (one property code) follows */ -#define XCL_NOTPROP 4 /* Unicode inverted property (ditto) */ - - -/* Opcode table: OP_BRA must be last, as all values >= it are used for brackets -that extract substrings. Starting from 1 (i.e. after OP_END), the values up to -OP_EOD must correspond in order to the list of escapes immediately above. -Note that whenever this list is updated, the two macro definitions that follow -must also be updated to match. */ - -enum { - OP_END, /* 0 End of pattern */ - - /* Values corresponding to backslashed metacharacters */ - - OP_SOD, /* 1 Start of data: \A */ - OP_SOM, /* 2 Start of match (subject + offset): \G */ - OP_NOT_WORD_BOUNDARY, /* 3 \B */ - OP_WORD_BOUNDARY, /* 4 \b */ - OP_NOT_DIGIT, /* 5 \D */ - OP_DIGIT, /* 6 \d */ - OP_NOT_WHITESPACE, /* 7 \S */ - OP_WHITESPACE, /* 8 \s */ - OP_NOT_WORDCHAR, /* 9 \W */ - OP_WORDCHAR, /* 10 \w */ - OP_ANY, /* 11 Match any character */ - OP_ANYBYTE, /* 12 Match any byte (\C); different to OP_ANY for UTF-8 */ - OP_NOTPROP, /* 13 \P (not Unicode property) */ - OP_PROP, /* 14 \p (Unicode property) */ - OP_EXTUNI, /* 15 \X (extended Unicode sequence */ - OP_EODN, /* 16 End of data or \n at end of data: \Z. */ - OP_EOD, /* 17 End of data: \z */ - - OP_OPT, /* 18 Set runtime options */ - OP_CIRC, /* 19 Start of line - varies with multiline switch */ - OP_DOLL, /* 20 End of line - varies with multiline switch */ - OP_CHAR, /* 21 Match one character, casefully */ - OP_CHARNC, /* 22 Match one character, caselessly */ - OP_NOT, /* 23 Match anything but the following char */ - - OP_STAR, /* 24 The maximizing and minimizing versions of */ - OP_MINSTAR, /* 25 all these opcodes must come in pairs, with */ - OP_PLUS, /* 26 the minimizing one second. */ - OP_MINPLUS, /* 27 This first set applies to single characters */ - OP_QUERY, /* 28 */ - OP_MINQUERY, /* 29 */ - OP_UPTO, /* 30 From 0 to n matches */ - OP_MINUPTO, /* 31 */ - OP_EXACT, /* 32 Exactly n matches */ - - OP_NOTSTAR, /* 33 The maximizing and minimizing versions of */ - OP_NOTMINSTAR, /* 34 all these opcodes must come in pairs, with */ - OP_NOTPLUS, /* 35 the minimizing one second. */ - OP_NOTMINPLUS, /* 36 This set applies to "not" single characters */ - OP_NOTQUERY, /* 37 */ - OP_NOTMINQUERY, /* 38 */ - OP_NOTUPTO, /* 39 From 0 to n matches */ - OP_NOTMINUPTO, /* 40 */ - OP_NOTEXACT, /* 41 Exactly n matches */ - - OP_TYPESTAR, /* 42 The maximizing and minimizing versions of */ - OP_TYPEMINSTAR, /* 43 all these opcodes must come in pairs, with */ - OP_TYPEPLUS, /* 44 the minimizing one second. These codes must */ - OP_TYPEMINPLUS, /* 45 be in exactly the same order as those above. */ - OP_TYPEQUERY, /* 46 This set applies to character types such as \d */ - OP_TYPEMINQUERY, /* 47 */ - OP_TYPEUPTO, /* 48 From 0 to n matches */ - OP_TYPEMINUPTO, /* 49 */ - OP_TYPEEXACT, /* 50 Exactly n matches */ - - OP_CRSTAR, /* 51 The maximizing and minimizing versions of */ - OP_CRMINSTAR, /* 52 all these opcodes must come in pairs, with */ - OP_CRPLUS, /* 53 the minimizing one second. These codes must */ - OP_CRMINPLUS, /* 54 be in exactly the same order as those above. */ - OP_CRQUERY, /* 55 These are for character classes and back refs */ - OP_CRMINQUERY, /* 56 */ - OP_CRRANGE, /* 57 These are different to the three sets above. */ - OP_CRMINRANGE, /* 58 */ - - OP_CLASS, /* 59 Match a character class, chars < 256 only */ - OP_NCLASS, /* 60 Same, but the bitmap was created from a negative - class - the difference is relevant only when a UTF-8 - character > 255 is encountered. */ - - OP_XCLASS, /* 61 Extended class for handling UTF-8 chars within the - class. This does both positive and negative. */ - - OP_REF, /* 62 Match a back reference */ - OP_RECURSE, /* 63 Match a numbered subpattern (possibly recursive) */ - OP_CALLOUT, /* 64 Call out to external function if provided */ - - OP_ALT, /* 65 Start of alternation */ - OP_KET, /* 66 End of group that doesn't have an unbounded repeat */ - OP_KETRMAX, /* 67 These two must remain together and in this */ - OP_KETRMIN, /* 68 order. They are for groups the repeat for ever. */ - - /* The assertions must come before ONCE and COND */ - - OP_ASSERT, /* 69 Positive lookahead */ - OP_ASSERT_NOT, /* 70 Negative lookahead */ - OP_ASSERTBACK, /* 71 Positive lookbehind */ - OP_ASSERTBACK_NOT, /* 72 Negative lookbehind */ - OP_REVERSE, /* 73 Move pointer back - used in lookbehind assertions */ - - /* ONCE and COND must come after the assertions, with ONCE first, as there's - a test for >= ONCE for a subpattern that isn't an assertion. */ - - OP_ONCE, /* 74 Once matched, don't back up into the subpattern */ - OP_COND, /* 75 Conditional group */ - OP_CREF, /* 76 Used to hold an extraction string number (cond ref) */ - - OP_BRAZERO, /* 77 These two must remain together and in this */ - OP_BRAMINZERO, /* 78 order. */ - - OP_BRANUMBER, /* 79 Used for extracting brackets whose number is greater - than can fit into an opcode. */ - - OP_BRA /* 80 This and greater values are used for brackets that - extract substrings up to EXTRACT_BASIC_MAX. After - that, use is made of OP_BRANUMBER. */ -}; - -/* WARNING WARNING WARNING: There is an implicit assumption in pcre.c and -study.c that all opcodes are less than 128 in value. This makes handling UTF-8 -character sequences easier. */ - -/* The highest extraction number before we have to start using additional -bytes. (Originally PCRE didn't have support for extraction counts highter than -this number.) The value is limited by the number of opcodes left after OP_BRA, -i.e. 255 - OP_BRA. We actually set it a bit lower to leave room for additional -opcodes. */ - -#define EXTRACT_BASIC_MAX 100 - - -/* This macro defines textual names for all the opcodes. There are used only -for debugging, in pcre.c when DEBUG is defined, and also in pcretest.c. The -macro is referenced only in printint.c. */ - -#define OP_NAME_LIST \ - "End", "\\A", "\\G", "\\B", "\\b", "\\D", "\\d", \ - "\\S", "\\s", "\\W", "\\w", "Any", "Anybyte", \ - "notprop", "prop", "extuni", \ - "\\Z", "\\z", \ - "Opt", "^", "$", "char", "charnc", "not", \ - "*", "*?", "+", "+?", "?", "??", "{", "{", "{", \ - "*", "*?", "+", "+?", "?", "??", "{", "{", "{", \ - "*", "*?", "+", "+?", "?", "??", "{", "{", "{", \ - "*", "*?", "+", "+?", "?", "??", "{", "{", \ - "class", "nclass", "xclass", "Ref", "Recurse", "Callout", \ - "Alt", "Ket", "KetRmax", "KetRmin", "Assert", "Assert not", \ - "AssertB", "AssertB not", "Reverse", "Once", "Cond", "Cond ref",\ - "Brazero", "Braminzero", "Branumber", "Bra" - - -/* This macro defines the length of fixed length operations in the compiled -regex. The lengths are used when searching for specific things, and also in the -debugging printing of a compiled regex. We use a macro so that it can be -incorporated both into pcre.c and pcretest.c without being publicly exposed. - -As things have been extended, some of these are no longer fixed lenths, but are -minima instead. For example, the length of a single-character repeat may vary -in UTF-8 mode. The code that uses this table must know about such things. */ - -#define OP_LENGTHS \ - 1, /* End */ \ - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* \A, \G, \B, \B, \D, \d, \S, \s, \W, \w */ \ - 1, 1, /* Any, Anybyte */ \ - 2, 2, 1, /* NOTPROP, PROP, EXTUNI */ \ - 1, 1, 2, 1, 1, /* \Z, \z, Opt, ^, $ */ \ - 2, /* Char - the minimum length */ \ - 2, /* Charnc - the minimum length */ \ - 2, /* not */ \ - /* Positive single-char repeats ** These are */ \ - 2, 2, 2, 2, 2, 2, /* *, *?, +, +?, ?, ?? ** minima in */ \ - 4, 4, 4, /* upto, minupto, exact ** UTF-8 mode */ \ - /* Negative single-char repeats - only for chars < 256 */ \ - 2, 2, 2, 2, 2, 2, /* NOT *, *?, +, +?, ?, ?? */ \ - 4, 4, 4, /* NOT upto, minupto, exact */ \ - /* Positive type repeats */ \ - 2, 2, 2, 2, 2, 2, /* Type *, *?, +, +?, ?, ?? */ \ - 4, 4, 4, /* Type upto, minupto, exact */ \ - /* Character class & ref repeats */ \ - 1, 1, 1, 1, 1, 1, /* *, *?, +, +?, ?, ?? */ \ - 5, 5, /* CRRANGE, CRMINRANGE */ \ - 33, /* CLASS */ \ - 33, /* NCLASS */ \ - 0, /* XCLASS - variable length */ \ - 3, /* REF */ \ - 1+LINK_SIZE, /* RECURSE */ \ - 2+2*LINK_SIZE, /* CALLOUT */ \ - 1+LINK_SIZE, /* Alt */ \ - 1+LINK_SIZE, /* Ket */ \ - 1+LINK_SIZE, /* KetRmax */ \ - 1+LINK_SIZE, /* KetRmin */ \ - 1+LINK_SIZE, /* Assert */ \ - 1+LINK_SIZE, /* Assert not */ \ - 1+LINK_SIZE, /* Assert behind */ \ - 1+LINK_SIZE, /* Assert behind not */ \ - 1+LINK_SIZE, /* Reverse */ \ - 1+LINK_SIZE, /* Once */ \ - 1+LINK_SIZE, /* COND */ \ - 3, /* CREF */ \ - 1, 1, /* BRAZERO, BRAMINZERO */ \ - 3, /* BRANUMBER */ \ - 1+LINK_SIZE /* BRA */ \ - - -/* A magic value for OP_CREF to indicate the "in recursion" condition. */ - -#define CREF_RECURSE 0xffff - -/* The texts of compile-time error messages are defined as macros here so that -they can be accessed by the POSIX wrapper and converted into error codes. Yes, -I could have used error codes in the first place, but didn't feel like changing -just to accommodate the POSIX wrapper. */ - -#define ERR1 "\\ at end of pattern" -#define ERR2 "\\c at end of pattern" -#define ERR3 "unrecognized character follows \\" -#define ERR4 "numbers out of order in {} quantifier" -#define ERR5 "number too big in {} quantifier" -#define ERR6 "missing terminating ] for character class" -#define ERR7 "invalid escape sequence in character class" -#define ERR8 "range out of order in character class" -#define ERR9 "nothing to repeat" -#define ERR10 "operand of unlimited repeat could match the empty string" -#define ERR11 "internal error: unexpected repeat" -#define ERR12 "unrecognized character after (?" -#define ERR13 "POSIX named classes are supported only within a class" -#define ERR14 "missing )" -#define ERR15 "reference to non-existent subpattern" -#define ERR16 "erroffset passed as NULL" -#define ERR17 "unknown option bit(s) set" -#define ERR18 "missing ) after comment" -#define ERR19 "parentheses nested too deeply" -#define ERR20 "regular expression too large" -#define ERR21 "failed to get memory" -#define ERR22 "unmatched parentheses" -#define ERR23 "internal error: code overflow" -#define ERR24 "unrecognized character after (?<" -#define ERR25 "lookbehind assertion is not fixed length" -#define ERR26 "malformed number after (?(" -#define ERR27 "conditional group contains more than two branches" -#define ERR28 "assertion expected after (?(" -#define ERR29 "(?R or (?digits must be followed by )" -#define ERR30 "unknown POSIX class name" -#define ERR31 "POSIX collating elements are not supported" -#define ERR32 "this version of PCRE is not compiled with PCRE_UTF8 support" -#define ERR33 "spare error" -#define ERR34 "character value in \\x{...} sequence is too large" -#define ERR35 "invalid condition (?(0)" -#define ERR36 "\\C not allowed in lookbehind assertion" -#define ERR37 "PCRE does not support \\L, \\l, \\N, \\U, or \\u" -#define ERR38 "number after (?C is > 255" -#define ERR39 "closing ) for (?C expected" -#define ERR40 "recursive call could loop indefinitely" -#define ERR41 "unrecognized character after (?P" -#define ERR42 "syntax error after (?P" -#define ERR43 "two named groups have the same name" -#define ERR44 "invalid UTF-8 string" -#define ERR45 "support for \\P, \\p, and \\X has not been compiled" -#define ERR46 "malformed \\P or \\p sequence" -#define ERR47 "unknown property name after \\P or \\p" - -/* The real format of the start of the pcre block; the index of names and the -code vector run on as long as necessary after the end. We store an explicit -offset to the name table so that if a regex is compiled on one host, saved, and -then run on another where the size of pointers is different, all might still -be well. For the case of compiled-on-4 and run-on-8, we include an extra -pointer that is always NULL. For future-proofing, we also include a few dummy -fields - even though you can never get this planning right! - -NOTE NOTE NOTE: -Because people can now save and re-use compiled patterns, any additions to this -structure should be made at the end, and something earlier (e.g. a new -flag in the options or one of the dummy fields) should indicate that the new -fields are present. Currently PCRE always sets the dummy fields to zero. -NOTE NOTE NOTE: -*/ - -typedef struct real_pcre { - pcre_uint32 magic_number; - pcre_uint32 size; /* Total that was malloced */ - pcre_uint32 options; - pcre_uint32 dummy1; /* For future use, maybe */ - - pcre_uint16 top_bracket; - pcre_uint16 top_backref; - pcre_uint16 first_byte; - pcre_uint16 req_byte; - pcre_uint16 name_table_offset; /* Offset to name table that follows */ - pcre_uint16 name_entry_size; /* Size of any name items */ - pcre_uint16 name_count; /* Number of name items */ - pcre_uint16 dummy2; /* For future use, maybe */ - - const unsigned char *tables; /* Pointer to tables or NULL for std */ - const unsigned char *nullpad; /* NULL padding */ -} real_pcre; - -/* The format of the block used to store data from pcre_study(). The same -remark (see NOTE above) about extending this structure applies. */ - -typedef struct pcre_study_data { - pcre_uint32 size; /* Total that was malloced */ - pcre_uint32 options; - uschar start_bits[32]; -} pcre_study_data; - -/* Structure for passing "static" information around between the functions -doing the compiling, so that they are thread-safe. */ - -typedef struct compile_data { - const uschar *lcc; /* Points to lower casing table */ - const uschar *fcc; /* Points to case-flipping table */ - const uschar *cbits; /* Points to character type table */ - const uschar *ctypes; /* Points to table of type maps */ - const uschar *start_code; /* The start of the compiled code */ - const uschar *start_pattern; /* The start of the pattern */ - uschar *name_table; /* The name/number table */ - int names_found; /* Number of entries so far */ - int name_entry_size; /* Size of each entry */ - int top_backref; /* Maximum back reference */ - unsigned int backref_map; /* Bitmap of low back refs */ - int req_varyopt; /* "After variable item" flag for reqbyte */ - BOOL nopartial; /* Set TRUE if partial won't work */ -} compile_data; - -/* Structure for maintaining a chain of pointers to the currently incomplete -branches, for testing for left recursion. */ - -typedef struct branch_chain { - struct branch_chain *outer; - uschar *current; -} branch_chain; - -/* Structure for items in a linked list that represents an explicit recursive -call within the pattern. */ - -typedef struct recursion_info { - struct recursion_info *prevrec; /* Previous recursion record (or NULL) */ - int group_num; /* Number of group that was called */ - const uschar *after_call; /* "Return value": points after the call in the expr */ - const uschar *save_start; /* Old value of md->start_match */ - int *offset_save; /* Pointer to start of saved offsets */ - int saved_max; /* Number of saved offsets */ -} recursion_info; - -/* When compiling in a mode that doesn't use recursive calls to match(), -a structure is used to remember local variables on the heap. It is defined in -pcre.c, close to the match() function, so that it is easy to keep it in step -with any changes of local variable. However, the pointer to the current frame -must be saved in some "static" place over a longjmp(). We declare the -structure here so that we can put a pointer in the match_data structure. -NOTE: This isn't used for a "normal" compilation of pcre. */ - -struct heapframe; - -/* Structure for passing "static" information around between the functions -doing the matching, so that they are thread-safe. */ - -typedef struct match_data { - unsigned long int match_call_count; /* As it says */ - unsigned long int match_limit;/* As it says */ - int *offset_vector; /* Offset vector */ - int offset_end; /* One past the end */ - int offset_max; /* The maximum usable for return data */ - const uschar *lcc; /* Points to lower casing table */ - const uschar *ctypes; /* Points to table of type maps */ - BOOL offset_overflow; /* Set if too many extractions */ - BOOL notbol; /* NOTBOL flag */ - BOOL noteol; /* NOTEOL flag */ - BOOL utf8; /* UTF8 flag */ - BOOL endonly; /* Dollar not before final \n */ - BOOL notempty; /* Empty string match not wanted */ - BOOL partial; /* PARTIAL flag */ - BOOL hitend; /* Hit the end of the subject at some point */ - const uschar *start_code; /* For use when recursing */ - const uschar *start_subject; /* Start of the subject string */ - const uschar *end_subject; /* End of the subject string */ - const uschar *start_match; /* Start of this match attempt */ - const uschar *end_match_ptr; /* Subject position at end match */ - int end_offset_top; /* Highwater mark at end of match */ - int capture_last; /* Most recent capture number */ - int start_offset; /* The start offset value */ - recursion_info *recursive; /* Linked list of recursion data */ - void *callout_data; /* To pass back to callouts */ - struct heapframe *thisframe; /* Used only when compiling for no recursion */ -} match_data; - -/* Bit definitions for entries in the pcre_ctypes table. */ - -#define ctype_space 0x01 -#define ctype_letter 0x02 -#define ctype_digit 0x04 -#define ctype_xdigit 0x08 -#define ctype_word 0x10 /* alphameric or '_' */ -#define ctype_meta 0x80 /* regexp meta char or zero (end pattern) */ - -/* Offsets for the bitmap tables in pcre_cbits. Each table contains a set -of bits for a class map. Some classes are built by combining these tables. */ - -#define cbit_space 0 /* [:space:] or \s */ -#define cbit_xdigit 32 /* [:xdigit:] */ -#define cbit_digit 64 /* [:digit:] or \d */ -#define cbit_upper 96 /* [:upper:] */ -#define cbit_lower 128 /* [:lower:] */ -#define cbit_word 160 /* [:word:] or \w */ -#define cbit_graph 192 /* [:graph:] */ -#define cbit_print 224 /* [:print:] */ -#define cbit_punct 256 /* [:punct:] */ -#define cbit_cntrl 288 /* [:cntrl:] */ -#define cbit_length 320 /* Length of the cbits table */ - -/* Offsets of the various tables from the base tables pointer, and -total length. */ - -#define lcc_offset 0 -#define fcc_offset 256 -#define cbits_offset 512 -#define ctypes_offset (cbits_offset + cbit_length) -#define tables_length (ctypes_offset + 256) - -/* End of internal.h */ +/************************************************* +* Perl-Compatible Regular Expressions * +*************************************************/ + + +/* This is a library of functions to support regular expressions whose syntax +and semantics are as close as possible to those of the Perl 5 language. See +the file doc/Tech.Notes for some information on the internals. + +Written by: Philip Hazel + + Copyright (c) 1997-2004 University of Cambridge + +----------------------------------------------------------------------------- +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + * 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. + + * Neither the name of the University of Cambridge nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +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. +----------------------------------------------------------------------------- +*/ + +/* This header contains definitions that are shared between the different +modules, but which are not relevant to the outside. */ + +/* Get the definitions provided by running "configure" */ + +#include "pcreconfig.h" + +/* Standard C headers plus the external interface definition. The only time +setjmp and stdarg are used is when NO_RECURSE is set. */ + +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef PCRE_SPY +#define PCRE_DEFINITION /* Win32 __declspec(export) trigger for .dll */ +#endif + +/* We need to have types that specify unsigned 16-bit and 32-bit integers. We +cannot determine these outside the compilation (e.g. by running a program as +part of "configure") because PCRE is often cross-compiled for use on other +systems. Instead we make use of the maximum sizes that are available at +preprocessor time in standard C environments. */ + +#if USHRT_MAX == 65535 + typedef unsigned short pcre_uint16; +#elif UINT_MAX == 65535 + typedef unsigned int pcre_uint16; +#else + #error Cannot determine a type for 16-bit unsigned integers +#endif + +#if UINT_MAX == 4294967295 + typedef unsigned int pcre_uint32; +#elif ULONG_MAX == 4294967295 + typedef unsigned long int pcre_uint32; +#else + #error Cannot determine a type for 32-bit unsigned integers +#endif + +/* All character handling must be done as unsigned characters. Otherwise there +are problems with top-bit-set characters and functions such as isspace(). +However, we leave the interface to the outside world as char *, because that +should make things easier for callers. We define a short type for unsigned char +to save lots of typing. I tried "uchar", but it causes problems on Digital +Unix, where it is defined in sys/types, so use "uschar" instead. */ + +typedef unsigned char uschar; + +/* Include the public PCRE header */ + +#include "pcre.h" + +/* When compiling for use with the Virtual Pascal compiler, these functions +need to have their names changed. PCRE must be compiled with the -DVPCOMPAT +option on the command line. */ + +#ifdef VPCOMPAT +#define strncmp(s1,s2,m) _strncmp(s1,s2,m) +#define memcpy(d,s,n) _memcpy(d,s,n) +#define memmove(d,s,n) _memmove(d,s,n) +#define memset(s,c,n) _memset(s,c,n) +#else /* VPCOMPAT */ + +/* To cope with SunOS4 and other systems that lack memmove() but have bcopy(), +define a macro for memmove() if HAVE_MEMMOVE is false, provided that HAVE_BCOPY +is set. Otherwise, include an emulating function for those systems that have +neither (there some non-Unix environments where this is the case). This assumes +that all calls to memmove are moving strings upwards in store, which is the +case in PCRE. */ + +#if ! HAVE_MEMMOVE +#undef memmove /* some systems may have a macro */ +#if HAVE_BCOPY +#define memmove(a, b, c) bcopy(b, a, c) +#else /* HAVE_BCOPY */ +void * +pcre_memmove(unsigned char *dest, const unsigned char *src, size_t n) +{ +int i; +dest += n; +src += n; +for (i = 0; i < n; ++i) *(--dest) = *(--src); +} +#define memmove(a, b, c) pcre_memmove(a, b, c) +#endif /* not HAVE_BCOPY */ +#endif /* not HAVE_MEMMOVE */ +#endif /* not VPCOMPAT */ + + +/* PCRE keeps offsets in its compiled code as 2-byte quantities (always stored +in big-endian order) by default. These are used, for example, to link from the +start of a subpattern to its alternatives and its end. The use of 2 bytes per +offset limits the size of the compiled regex to around 64K, which is big enough +for almost everybody. However, I received a request for an even bigger limit. +For this reason, and also to make the code easier to maintain, the storing and +loading of offsets from the byte string is now handled by the macros that are +defined here. + +The macros are controlled by the value of LINK_SIZE. This defaults to 2 in +the config.h file, but can be overridden by using -D on the command line. This +is automated on Unix systems via the "configure" command. */ + +#if LINK_SIZE == 2 + +#define PUT(a,n,d) \ + (a[n] = (d) >> 8), \ + (a[(n)+1] = (d) & 255) + +#define GET(a,n) \ + (((a)[n] << 8) | (a)[(n)+1]) + +#define MAX_PATTERN_SIZE (1 << 16) + + +#elif LINK_SIZE == 3 + +#define PUT(a,n,d) \ + (a[n] = (d) >> 16), \ + (a[(n)+1] = (d) >> 8), \ + (a[(n)+2] = (d) & 255) + +#define GET(a,n) \ + (((a)[n] << 16) | ((a)[(n)+1] << 8) | (a)[(n)+2]) + +#define MAX_PATTERN_SIZE (1 << 24) + + +#elif LINK_SIZE == 4 + +#define PUT(a,n,d) \ + (a[n] = (d) >> 24), \ + (a[(n)+1] = (d) >> 16), \ + (a[(n)+2] = (d) >> 8), \ + (a[(n)+3] = (d) & 255) + +#define GET(a,n) \ + (((a)[n] << 24) | ((a)[(n)+1] << 16) | ((a)[(n)+2] << 8) | (a)[(n)+3]) + +#define MAX_PATTERN_SIZE (1 << 30) /* Keep it positive */ + + +#else +#error LINK_SIZE must be either 2, 3, or 4 +#endif + + +/* Convenience macro defined in terms of the others */ + +#define PUTINC(a,n,d) PUT(a,n,d), a += LINK_SIZE + + +/* PCRE uses some other 2-byte quantities that do not change when the size of +offsets changes. There are used for repeat counts and for other things such as +capturing parenthesis numbers in back references. */ + +#define PUT2(a,n,d) \ + a[n] = (d) >> 8; \ + a[(n)+1] = (d) & 255 + +#define GET2(a,n) \ + (((a)[n] << 8) | (a)[(n)+1]) + +#define PUT2INC(a,n,d) PUT2(a,n,d), a += 2 + + +/* In case there is no definition of offsetof() provided - though any proper +Standard C system should have one. */ + +#ifndef offsetof +#define offsetof(p_type,field) ((size_t)&(((p_type *)0)->field)) +#endif + + +/* These are the public options that can change during matching. */ + +#define PCRE_IMS (PCRE_CASELESS|PCRE_MULTILINE|PCRE_DOTALL) + +/* Private options flags start at the most significant end of the four bytes, +but skip the top bit so we can use ints for convenience without getting tangled +with negative values. The public options defined in pcre.h start at the least +significant end. Make sure they don't overlap, though now that we have expanded +to four bytes, there is plenty of space. */ + +#define PCRE_FIRSTSET 0x40000000 /* first_byte is set */ +#define PCRE_REQCHSET 0x20000000 /* req_byte is set */ +#define PCRE_STARTLINE 0x10000000 /* start after \n for multiline */ +#define PCRE_ICHANGED 0x08000000 /* i option changes within regex */ +#define PCRE_NOPARTIAL 0x04000000 /* can't use partial with this regex */ + +/* Options for the "extra" block produced by pcre_study(). */ + +#define PCRE_STUDY_MAPPED 0x01 /* a map of starting chars exists */ + +/* Masks for identifying the public options which are permitted at compile +time, run time or study time, respectively. */ + +#define PUBLIC_OPTIONS \ + (PCRE_CASELESS|PCRE_EXTENDED|PCRE_ANCHORED|PCRE_MULTILINE| \ + PCRE_DOTALL|PCRE_DOLLAR_ENDONLY|PCRE_EXTRA|PCRE_UNGREEDY|PCRE_UTF8| \ + PCRE_NO_AUTO_CAPTURE|PCRE_NO_UTF8_CHECK|PCRE_AUTO_CALLOUT) + +#define PUBLIC_EXEC_OPTIONS \ + (PCRE_ANCHORED|PCRE_NOTBOL|PCRE_NOTEOL|PCRE_NOTEMPTY|PCRE_NO_UTF8_CHECK| \ + PCRE_PARTIAL) + +#define PUBLIC_STUDY_OPTIONS 0 /* None defined */ + +/* Magic number to provide a small check against being handed junk. */ + +#define MAGIC_NUMBER 0x50435245UL /* 'PCRE' */ + +/* Negative values for the firstchar and reqchar variables */ + +#define REQ_UNSET (-2) +#define REQ_NONE (-1) + +/* Flags added to firstbyte or reqbyte; a "non-literal" item is either a +variable-length repeat, or a anything other than literal characters. */ + +#define REQ_CASELESS 0x0100 /* indicates caselessness */ +#define REQ_VARY 0x0200 /* reqbyte followed non-literal item */ + +/* Miscellaneous definitions */ + +typedef int BOOL; + +#define FALSE 0 +#define TRUE 1 + +/* Escape items that are just an encoding of a particular data value. Note that +ESC_n is defined as yet another macro, which is set in config.h to either \n +(the default) or \r (which some people want). */ + +#ifndef ESC_e +#define ESC_e 27 +#endif + +#ifndef ESC_f +#define ESC_f '\f' +#endif + +#ifndef ESC_n +#define ESC_n NEWLINE +#endif + +#ifndef ESC_r +#define ESC_r '\r' +#endif + +/* We can't officially use ESC_t because it is a POSIX reserved identifier +(presumably because of all the others like size_t). */ + +#ifndef ESC_tee +#define ESC_tee '\t' +#endif + +/* These are escaped items that aren't just an encoding of a particular data +value such as \n. They must have non-zero values, as check_escape() returns +their negation. Also, they must appear in the same order as in the opcode +definitions below, up to ESC_z. There's a dummy for OP_ANY because it +corresponds to "." rather than an escape sequence. The final one must be +ESC_REF as subsequent values are used for \1, \2, \3, etc. There is are two +tests in the code for an escape greater than ESC_b and less than ESC_Z to +detect the types that may be repeated. These are the types that consume +characters. If any new escapes are put in between that don't consume a +character, that code will have to change. */ + +enum { ESC_A = 1, ESC_G, ESC_B, ESC_b, ESC_D, ESC_d, ESC_S, ESC_s, ESC_W, + ESC_w, ESC_dum1, ESC_C, ESC_P, ESC_p, ESC_X, ESC_Z, ESC_z, ESC_E, + ESC_Q, ESC_REF }; + +/* Flag bits and data types for the extended class (OP_XCLASS) for classes that +contain UTF-8 characters with values greater than 255. */ + +#define XCL_NOT 0x01 /* Flag: this is a negative class */ +#define XCL_MAP 0x02 /* Flag: a 32-byte map is present */ + +#define XCL_END 0 /* Marks end of individual items */ +#define XCL_SINGLE 1 /* Single item (one multibyte char) follows */ +#define XCL_RANGE 2 /* A range (two multibyte chars) follows */ +#define XCL_PROP 3 /* Unicode property (one property code) follows */ +#define XCL_NOTPROP 4 /* Unicode inverted property (ditto) */ + + +/* Opcode table: OP_BRA must be last, as all values >= it are used for brackets +that extract substrings. Starting from 1 (i.e. after OP_END), the values up to +OP_EOD must correspond in order to the list of escapes immediately above. +Note that whenever this list is updated, the two macro definitions that follow +must also be updated to match. */ + +enum { + OP_END, /* 0 End of pattern */ + + /* Values corresponding to backslashed metacharacters */ + + OP_SOD, /* 1 Start of data: \A */ + OP_SOM, /* 2 Start of match (subject + offset): \G */ + OP_NOT_WORD_BOUNDARY, /* 3 \B */ + OP_WORD_BOUNDARY, /* 4 \b */ + OP_NOT_DIGIT, /* 5 \D */ + OP_DIGIT, /* 6 \d */ + OP_NOT_WHITESPACE, /* 7 \S */ + OP_WHITESPACE, /* 8 \s */ + OP_NOT_WORDCHAR, /* 9 \W */ + OP_WORDCHAR, /* 10 \w */ + OP_ANY, /* 11 Match any character */ + OP_ANYBYTE, /* 12 Match any byte (\C); different to OP_ANY for UTF-8 */ + OP_NOTPROP, /* 13 \P (not Unicode property) */ + OP_PROP, /* 14 \p (Unicode property) */ + OP_EXTUNI, /* 15 \X (extended Unicode sequence */ + OP_EODN, /* 16 End of data or \n at end of data: \Z. */ + OP_EOD, /* 17 End of data: \z */ + + OP_OPT, /* 18 Set runtime options */ + OP_CIRC, /* 19 Start of line - varies with multiline switch */ + OP_DOLL, /* 20 End of line - varies with multiline switch */ + OP_CHAR, /* 21 Match one character, casefully */ + OP_CHARNC, /* 22 Match one character, caselessly */ + OP_NOT, /* 23 Match anything but the following char */ + + OP_STAR, /* 24 The maximizing and minimizing versions of */ + OP_MINSTAR, /* 25 all these opcodes must come in pairs, with */ + OP_PLUS, /* 26 the minimizing one second. */ + OP_MINPLUS, /* 27 This first set applies to single characters */ + OP_QUERY, /* 28 */ + OP_MINQUERY, /* 29 */ + OP_UPTO, /* 30 From 0 to n matches */ + OP_MINUPTO, /* 31 */ + OP_EXACT, /* 32 Exactly n matches */ + + OP_NOTSTAR, /* 33 The maximizing and minimizing versions of */ + OP_NOTMINSTAR, /* 34 all these opcodes must come in pairs, with */ + OP_NOTPLUS, /* 35 the minimizing one second. */ + OP_NOTMINPLUS, /* 36 This set applies to "not" single characters */ + OP_NOTQUERY, /* 37 */ + OP_NOTMINQUERY, /* 38 */ + OP_NOTUPTO, /* 39 From 0 to n matches */ + OP_NOTMINUPTO, /* 40 */ + OP_NOTEXACT, /* 41 Exactly n matches */ + + OP_TYPESTAR, /* 42 The maximizing and minimizing versions of */ + OP_TYPEMINSTAR, /* 43 all these opcodes must come in pairs, with */ + OP_TYPEPLUS, /* 44 the minimizing one second. These codes must */ + OP_TYPEMINPLUS, /* 45 be in exactly the same order as those above. */ + OP_TYPEQUERY, /* 46 This set applies to character types such as \d */ + OP_TYPEMINQUERY, /* 47 */ + OP_TYPEUPTO, /* 48 From 0 to n matches */ + OP_TYPEMINUPTO, /* 49 */ + OP_TYPEEXACT, /* 50 Exactly n matches */ + + OP_CRSTAR, /* 51 The maximizing and minimizing versions of */ + OP_CRMINSTAR, /* 52 all these opcodes must come in pairs, with */ + OP_CRPLUS, /* 53 the minimizing one second. These codes must */ + OP_CRMINPLUS, /* 54 be in exactly the same order as those above. */ + OP_CRQUERY, /* 55 These are for character classes and back refs */ + OP_CRMINQUERY, /* 56 */ + OP_CRRANGE, /* 57 These are different to the three sets above. */ + OP_CRMINRANGE, /* 58 */ + + OP_CLASS, /* 59 Match a character class, chars < 256 only */ + OP_NCLASS, /* 60 Same, but the bitmap was created from a negative + class - the difference is relevant only when a UTF-8 + character > 255 is encountered. */ + + OP_XCLASS, /* 61 Extended class for handling UTF-8 chars within the + class. This does both positive and negative. */ + + OP_REF, /* 62 Match a back reference */ + OP_RECURSE, /* 63 Match a numbered subpattern (possibly recursive) */ + OP_CALLOUT, /* 64 Call out to external function if provided */ + + OP_ALT, /* 65 Start of alternation */ + OP_KET, /* 66 End of group that doesn't have an unbounded repeat */ + OP_KETRMAX, /* 67 These two must remain together and in this */ + OP_KETRMIN, /* 68 order. They are for groups the repeat for ever. */ + + /* The assertions must come before ONCE and COND */ + + OP_ASSERT, /* 69 Positive lookahead */ + OP_ASSERT_NOT, /* 70 Negative lookahead */ + OP_ASSERTBACK, /* 71 Positive lookbehind */ + OP_ASSERTBACK_NOT, /* 72 Negative lookbehind */ + OP_REVERSE, /* 73 Move pointer back - used in lookbehind assertions */ + + /* ONCE and COND must come after the assertions, with ONCE first, as there's + a test for >= ONCE for a subpattern that isn't an assertion. */ + + OP_ONCE, /* 74 Once matched, don't back up into the subpattern */ + OP_COND, /* 75 Conditional group */ + OP_CREF, /* 76 Used to hold an extraction string number (cond ref) */ + + OP_BRAZERO, /* 77 These two must remain together and in this */ + OP_BRAMINZERO, /* 78 order. */ + + OP_BRANUMBER, /* 79 Used for extracting brackets whose number is greater + than can fit into an opcode. */ + + OP_BRA /* 80 This and greater values are used for brackets that + extract substrings up to EXTRACT_BASIC_MAX. After + that, use is made of OP_BRANUMBER. */ +}; + +/* WARNING WARNING WARNING: There is an implicit assumption in pcre.c and +study.c that all opcodes are less than 128 in value. This makes handling UTF-8 +character sequences easier. */ + +/* The highest extraction number before we have to start using additional +bytes. (Originally PCRE didn't have support for extraction counts highter than +this number.) The value is limited by the number of opcodes left after OP_BRA, +i.e. 255 - OP_BRA. We actually set it a bit lower to leave room for additional +opcodes. */ + +#define EXTRACT_BASIC_MAX 100 + + +/* This macro defines textual names for all the opcodes. There are used only +for debugging, in pcre.c when DEBUG is defined, and also in pcretest.c. The +macro is referenced only in printint.c. */ + +#define OP_NAME_LIST \ + "End", "\\A", "\\G", "\\B", "\\b", "\\D", "\\d", \ + "\\S", "\\s", "\\W", "\\w", "Any", "Anybyte", \ + "notprop", "prop", "extuni", \ + "\\Z", "\\z", \ + "Opt", "^", "$", "char", "charnc", "not", \ + "*", "*?", "+", "+?", "?", "??", "{", "{", "{", \ + "*", "*?", "+", "+?", "?", "??", "{", "{", "{", \ + "*", "*?", "+", "+?", "?", "??", "{", "{", "{", \ + "*", "*?", "+", "+?", "?", "??", "{", "{", \ + "class", "nclass", "xclass", "Ref", "Recurse", "Callout", \ + "Alt", "Ket", "KetRmax", "KetRmin", "Assert", "Assert not", \ + "AssertB", "AssertB not", "Reverse", "Once", "Cond", "Cond ref",\ + "Brazero", "Braminzero", "Branumber", "Bra" + + +/* This macro defines the length of fixed length operations in the compiled +regex. The lengths are used when searching for specific things, and also in the +debugging printing of a compiled regex. We use a macro so that it can be +incorporated both into pcre.c and pcretest.c without being publicly exposed. + +As things have been extended, some of these are no longer fixed lenths, but are +minima instead. For example, the length of a single-character repeat may vary +in UTF-8 mode. The code that uses this table must know about such things. */ + +#define OP_LENGTHS \ + 1, /* End */ \ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* \A, \G, \B, \B, \D, \d, \S, \s, \W, \w */ \ + 1, 1, /* Any, Anybyte */ \ + 2, 2, 1, /* NOTPROP, PROP, EXTUNI */ \ + 1, 1, 2, 1, 1, /* \Z, \z, Opt, ^, $ */ \ + 2, /* Char - the minimum length */ \ + 2, /* Charnc - the minimum length */ \ + 2, /* not */ \ + /* Positive single-char repeats ** These are */ \ + 2, 2, 2, 2, 2, 2, /* *, *?, +, +?, ?, ?? ** minima in */ \ + 4, 4, 4, /* upto, minupto, exact ** UTF-8 mode */ \ + /* Negative single-char repeats - only for chars < 256 */ \ + 2, 2, 2, 2, 2, 2, /* NOT *, *?, +, +?, ?, ?? */ \ + 4, 4, 4, /* NOT upto, minupto, exact */ \ + /* Positive type repeats */ \ + 2, 2, 2, 2, 2, 2, /* Type *, *?, +, +?, ?, ?? */ \ + 4, 4, 4, /* Type upto, minupto, exact */ \ + /* Character class & ref repeats */ \ + 1, 1, 1, 1, 1, 1, /* *, *?, +, +?, ?, ?? */ \ + 5, 5, /* CRRANGE, CRMINRANGE */ \ + 33, /* CLASS */ \ + 33, /* NCLASS */ \ + 0, /* XCLASS - variable length */ \ + 3, /* REF */ \ + 1+LINK_SIZE, /* RECURSE */ \ + 2+2*LINK_SIZE, /* CALLOUT */ \ + 1+LINK_SIZE, /* Alt */ \ + 1+LINK_SIZE, /* Ket */ \ + 1+LINK_SIZE, /* KetRmax */ \ + 1+LINK_SIZE, /* KetRmin */ \ + 1+LINK_SIZE, /* Assert */ \ + 1+LINK_SIZE, /* Assert not */ \ + 1+LINK_SIZE, /* Assert behind */ \ + 1+LINK_SIZE, /* Assert behind not */ \ + 1+LINK_SIZE, /* Reverse */ \ + 1+LINK_SIZE, /* Once */ \ + 1+LINK_SIZE, /* COND */ \ + 3, /* CREF */ \ + 1, 1, /* BRAZERO, BRAMINZERO */ \ + 3, /* BRANUMBER */ \ + 1+LINK_SIZE /* BRA */ \ + + +/* A magic value for OP_CREF to indicate the "in recursion" condition. */ + +#define CREF_RECURSE 0xffff + +/* The texts of compile-time error messages are defined as macros here so that +they can be accessed by the POSIX wrapper and converted into error codes. Yes, +I could have used error codes in the first place, but didn't feel like changing +just to accommodate the POSIX wrapper. */ + +#define ERR1 "\\ at end of pattern" +#define ERR2 "\\c at end of pattern" +#define ERR3 "unrecognized character follows \\" +#define ERR4 "numbers out of order in {} quantifier" +#define ERR5 "number too big in {} quantifier" +#define ERR6 "missing terminating ] for character class" +#define ERR7 "invalid escape sequence in character class" +#define ERR8 "range out of order in character class" +#define ERR9 "nothing to repeat" +#define ERR10 "operand of unlimited repeat could match the empty string" +#define ERR11 "internal error: unexpected repeat" +#define ERR12 "unrecognized character after (?" +#define ERR13 "POSIX named classes are supported only within a class" +#define ERR14 "missing )" +#define ERR15 "reference to non-existent subpattern" +#define ERR16 "erroffset passed as NULL" +#define ERR17 "unknown option bit(s) set" +#define ERR18 "missing ) after comment" +#define ERR19 "parentheses nested too deeply" +#define ERR20 "regular expression too large" +#define ERR21 "failed to get memory" +#define ERR22 "unmatched parentheses" +#define ERR23 "internal error: code overflow" +#define ERR24 "unrecognized character after (?<" +#define ERR25 "lookbehind assertion is not fixed length" +#define ERR26 "malformed number after (?(" +#define ERR27 "conditional group contains more than two branches" +#define ERR28 "assertion expected after (?(" +#define ERR29 "(?R or (?digits must be followed by )" +#define ERR30 "unknown POSIX class name" +#define ERR31 "POSIX collating elements are not supported" +#define ERR32 "this version of PCRE is not compiled with PCRE_UTF8 support" +#define ERR33 "spare error" +#define ERR34 "character value in \\x{...} sequence is too large" +#define ERR35 "invalid condition (?(0)" +#define ERR36 "\\C not allowed in lookbehind assertion" +#define ERR37 "PCRE does not support \\L, \\l, \\N, \\U, or \\u" +#define ERR38 "number after (?C is > 255" +#define ERR39 "closing ) for (?C expected" +#define ERR40 "recursive call could loop indefinitely" +#define ERR41 "unrecognized character after (?P" +#define ERR42 "syntax error after (?P" +#define ERR43 "two named groups have the same name" +#define ERR44 "invalid UTF-8 string" +#define ERR45 "support for \\P, \\p, and \\X has not been compiled" +#define ERR46 "malformed \\P or \\p sequence" +#define ERR47 "unknown property name after \\P or \\p" + +/* The real format of the start of the pcre block; the index of names and the +code vector run on as long as necessary after the end. We store an explicit +offset to the name table so that if a regex is compiled on one host, saved, and +then run on another where the size of pointers is different, all might still +be well. For the case of compiled-on-4 and run-on-8, we include an extra +pointer that is always NULL. For future-proofing, we also include a few dummy +fields - even though you can never get this planning right! + +NOTE NOTE NOTE: +Because people can now save and re-use compiled patterns, any additions to this +structure should be made at the end, and something earlier (e.g. a new +flag in the options or one of the dummy fields) should indicate that the new +fields are present. Currently PCRE always sets the dummy fields to zero. +NOTE NOTE NOTE: +*/ + +typedef struct real_pcre { + pcre_uint32 magic_number; + pcre_uint32 size; /* Total that was malloced */ + pcre_uint32 options; + pcre_uint32 dummy1; /* For future use, maybe */ + + pcre_uint16 top_bracket; + pcre_uint16 top_backref; + pcre_uint16 first_byte; + pcre_uint16 req_byte; + pcre_uint16 name_table_offset; /* Offset to name table that follows */ + pcre_uint16 name_entry_size; /* Size of any name items */ + pcre_uint16 name_count; /* Number of name items */ + pcre_uint16 dummy2; /* For future use, maybe */ + + const unsigned char *tables; /* Pointer to tables or NULL for std */ + const unsigned char *nullpad; /* NULL padding */ +} real_pcre; + +/* The format of the block used to store data from pcre_study(). The same +remark (see NOTE above) about extending this structure applies. */ + +typedef struct pcre_study_data { + pcre_uint32 size; /* Total that was malloced */ + pcre_uint32 options; + uschar start_bits[32]; +} pcre_study_data; + +/* Structure for passing "static" information around between the functions +doing the compiling, so that they are thread-safe. */ + +typedef struct compile_data { + const uschar *lcc; /* Points to lower casing table */ + const uschar *fcc; /* Points to case-flipping table */ + const uschar *cbits; /* Points to character type table */ + const uschar *ctypes; /* Points to table of type maps */ + const uschar *start_code; /* The start of the compiled code */ + const uschar *start_pattern; /* The start of the pattern */ + uschar *name_table; /* The name/number table */ + int names_found; /* Number of entries so far */ + int name_entry_size; /* Size of each entry */ + int top_backref; /* Maximum back reference */ + unsigned int backref_map; /* Bitmap of low back refs */ + int req_varyopt; /* "After variable item" flag for reqbyte */ + BOOL nopartial; /* Set TRUE if partial won't work */ +} compile_data; + +/* Structure for maintaining a chain of pointers to the currently incomplete +branches, for testing for left recursion. */ + +typedef struct branch_chain { + struct branch_chain *outer; + uschar *current; +} branch_chain; + +/* Structure for items in a linked list that represents an explicit recursive +call within the pattern. */ + +typedef struct recursion_info { + struct recursion_info *prevrec; /* Previous recursion record (or NULL) */ + int group_num; /* Number of group that was called */ + const uschar *after_call; /* "Return value": points after the call in the expr */ + const uschar *save_start; /* Old value of md->start_match */ + int *offset_save; /* Pointer to start of saved offsets */ + int saved_max; /* Number of saved offsets */ +} recursion_info; + +/* When compiling in a mode that doesn't use recursive calls to match(), +a structure is used to remember local variables on the heap. It is defined in +pcre.c, close to the match() function, so that it is easy to keep it in step +with any changes of local variable. However, the pointer to the current frame +must be saved in some "static" place over a longjmp(). We declare the +structure here so that we can put a pointer in the match_data structure. +NOTE: This isn't used for a "normal" compilation of pcre. */ + +struct heapframe; + +/* Structure for passing "static" information around between the functions +doing the matching, so that they are thread-safe. */ + +typedef struct match_data { + unsigned long int match_call_count; /* As it says */ + unsigned long int match_limit;/* As it says */ + int *offset_vector; /* Offset vector */ + int offset_end; /* One past the end */ + int offset_max; /* The maximum usable for return data */ + const uschar *lcc; /* Points to lower casing table */ + const uschar *ctypes; /* Points to table of type maps */ + BOOL offset_overflow; /* Set if too many extractions */ + BOOL notbol; /* NOTBOL flag */ + BOOL noteol; /* NOTEOL flag */ + BOOL utf8; /* UTF8 flag */ + BOOL endonly; /* Dollar not before final \n */ + BOOL notempty; /* Empty string match not wanted */ + BOOL partial; /* PARTIAL flag */ + BOOL hitend; /* Hit the end of the subject at some point */ + const uschar *start_code; /* For use when recursing */ + const uschar *start_subject; /* Start of the subject string */ + const uschar *end_subject; /* End of the subject string */ + const uschar *start_match; /* Start of this match attempt */ + const uschar *end_match_ptr; /* Subject position at end match */ + int end_offset_top; /* Highwater mark at end of match */ + int capture_last; /* Most recent capture number */ + int start_offset; /* The start offset value */ + recursion_info *recursive; /* Linked list of recursion data */ + void *callout_data; /* To pass back to callouts */ + struct heapframe *thisframe; /* Used only when compiling for no recursion */ +} match_data; + +/* Bit definitions for entries in the pcre_ctypes table. */ + +#define ctype_space 0x01 +#define ctype_letter 0x02 +#define ctype_digit 0x04 +#define ctype_xdigit 0x08 +#define ctype_word 0x10 /* alphameric or '_' */ +#define ctype_meta 0x80 /* regexp meta char or zero (end pattern) */ + +/* Offsets for the bitmap tables in pcre_cbits. Each table contains a set +of bits for a class map. Some classes are built by combining these tables. */ + +#define cbit_space 0 /* [:space:] or \s */ +#define cbit_xdigit 32 /* [:xdigit:] */ +#define cbit_digit 64 /* [:digit:] or \d */ +#define cbit_upper 96 /* [:upper:] */ +#define cbit_lower 128 /* [:lower:] */ +#define cbit_word 160 /* [:word:] or \w */ +#define cbit_graph 192 /* [:graph:] */ +#define cbit_print 224 /* [:print:] */ +#define cbit_punct 256 /* [:punct:] */ +#define cbit_cntrl 288 /* [:cntrl:] */ +#define cbit_length 320 /* Length of the cbits table */ + +/* Offsets of the various tables from the base tables pointer, and +total length. */ + +#define lcc_offset 0 +#define fcc_offset 256 +#define cbits_offset 512 +#define ctypes_offset (cbits_offset + cbit_length) +#define tables_length (ctypes_offset + 256) + +/* End of internal.h */ diff --git a/Foundation/src/pocomsg.h b/Foundation/src/pocomsg.h index f23b0a59f..ee44973c4 100644 --- a/Foundation/src/pocomsg.h +++ b/Foundation/src/pocomsg.h @@ -1,158 +1,158 @@ -// -// pocomsg.mc[.h] -// -// $Id: //poco/1.2/Foundation/src/pocomsg.mc#1 $ -// -// The Poco message source/header file. -// -// NOTE: pocomsg.h is automatically generated from pocomsg.mc. -// Never edit pocomsg.h directly! -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// -// -// Categories -// -// -// Values are 32 bit values layed out as follows: -// -// 3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1 -// 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 -// +---+-+-+-----------------------+-------------------------------+ -// |Sev|C|R| Facility | Code | -// +---+-+-+-----------------------+-------------------------------+ -// -// where -// -// Sev - is the severity code -// -// 00 - Success -// 01 - Informational -// 10 - Warning -// 11 - Error -// -// C - is the Customer code flag -// -// R - is a reserved bit -// -// Facility - is the facility code -// -// Code - is the facility's status code -// -// -// Define the facility codes -// - - -// -// Define the severity codes -// - - -// -// MessageId: POCO_CTG_FATAL -// -// MessageText: -// -// Fatal -// -#define POCO_CTG_FATAL 0x00000001L - -// -// MessageId: POCO_CTG_CRITICAL -// -// MessageText: -// -// Critical -// -#define POCO_CTG_CRITICAL 0x00000002L - -// -// MessageId: POCO_CTG_ERROR -// -// MessageText: -// -// Error -// -#define POCO_CTG_ERROR 0x00000003L - -// -// MessageId: POCO_CTG_WARNING -// -// MessageText: -// -// Warning -// -#define POCO_CTG_WARNING 0x00000004L - -// -// MessageId: POCO_CTG_NOTICE -// -// MessageText: -// -// Notice -// -#define POCO_CTG_NOTICE 0x00000005L - -// -// MessageId: POCO_CTG_INFORMATION -// -// MessageText: -// -// Information -// -#define POCO_CTG_INFORMATION 0x00000006L - -// -// MessageId: POCO_CTG_DEBUG -// -// MessageText: -// -// Debug -// -#define POCO_CTG_DEBUG 0x00000007L - -// -// MessageId: POCO_CTG_TRACE -// -// MessageText: -// -// Trace -// -#define POCO_CTG_TRACE 0x00000008L - -// -// Event Identifiers -// -// -// MessageId: POCO_MSG_LOG -// -// MessageText: -// -// %1 -// -#define POCO_MSG_LOG 0x00001000L - +// +// pocomsg.mc[.h] +// +// $Id: //poco/1.2/Foundation/src/pocomsg.mc#1 $ +// +// The Poco message source/header file. +// +// NOTE: pocomsg.h is automatically generated from pocomsg.mc. +// Never edit pocomsg.h directly! +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// +// +// Categories +// +// +// Values are 32 bit values layed out as follows: +// +// 3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1 +// 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 +// +---+-+-+-----------------------+-------------------------------+ +// |Sev|C|R| Facility | Code | +// +---+-+-+-----------------------+-------------------------------+ +// +// where +// +// Sev - is the severity code +// +// 00 - Success +// 01 - Informational +// 10 - Warning +// 11 - Error +// +// C - is the Customer code flag +// +// R - is a reserved bit +// +// Facility - is the facility code +// +// Code - is the facility's status code +// +// +// Define the facility codes +// + + +// +// Define the severity codes +// + + +// +// MessageId: POCO_CTG_FATAL +// +// MessageText: +// +// Fatal +// +#define POCO_CTG_FATAL 0x00000001L + +// +// MessageId: POCO_CTG_CRITICAL +// +// MessageText: +// +// Critical +// +#define POCO_CTG_CRITICAL 0x00000002L + +// +// MessageId: POCO_CTG_ERROR +// +// MessageText: +// +// Error +// +#define POCO_CTG_ERROR 0x00000003L + +// +// MessageId: POCO_CTG_WARNING +// +// MessageText: +// +// Warning +// +#define POCO_CTG_WARNING 0x00000004L + +// +// MessageId: POCO_CTG_NOTICE +// +// MessageText: +// +// Notice +// +#define POCO_CTG_NOTICE 0x00000005L + +// +// MessageId: POCO_CTG_INFORMATION +// +// MessageText: +// +// Information +// +#define POCO_CTG_INFORMATION 0x00000006L + +// +// MessageId: POCO_CTG_DEBUG +// +// MessageText: +// +// Debug +// +#define POCO_CTG_DEBUG 0x00000007L + +// +// MessageId: POCO_CTG_TRACE +// +// MessageText: +// +// Trace +// +#define POCO_CTG_TRACE 0x00000008L + +// +// Event Identifiers +// +// +// MessageId: POCO_MSG_LOG +// +// MessageText: +// +// %1 +// +#define POCO_MSG_LOG 0x00001000L + diff --git a/Foundation/src/pocomsg.mc b/Foundation/src/pocomsg.mc index a7483bb9a..c7c679746 100644 --- a/Foundation/src/pocomsg.mc +++ b/Foundation/src/pocomsg.mc @@ -1,89 +1,89 @@ -;// -;// pocomsg.mc[.h] -;// -;// $Id: //poco/1.2/Foundation/src/pocomsg.mc#1 $ -;// -;// The Poco message source/header file. -;// -;// NOTE: pocomsg.h is automatically generated from pocomsg.mc. -;// Never edit pocomsg.h directly! -;// -;// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -;// and Contributors. -;// -;// 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. -;// - - -;// -;// Categories -;// -MessageId=0x1 -SymbolicName=POCO_CTG_FATAL -Language=English -Fatal -. -MessageId=0x2 -SymbolicName=POCO_CTG_CRITICAL -Language=English -Critical -. -MessageId=0x3 -SymbolicName=POCO_CTG_ERROR -Language=English -Error -. -MessageId=0x4 -SymbolicName=POCO_CTG_WARNING -Language=English -Warning -. -MessageId=0x5 -SymbolicName=POCO_CTG_NOTICE -Language=English -Notice -. -MessageId=0x6 -SymbolicName=POCO_CTG_INFORMATION -Language=English -Information -. -MessageId=0x7 -SymbolicName=POCO_CTG_DEBUG -Language=English -Debug -. -MessageId=0x8 -SymbolicName=POCO_CTG_TRACE -Language=English -Trace -. - -;// -;// Event Identifiers -;// -MessageId=0x1000 -SymbolicName=POCO_MSG_LOG -Language=English -%1 -. +;// +;// pocomsg.mc[.h] +;// +;// $Id: //poco/1.2/Foundation/src/pocomsg.mc#1 $ +;// +;// The Poco message source/header file. +;// +;// NOTE: pocomsg.h is automatically generated from pocomsg.mc. +;// Never edit pocomsg.h directly! +;// +;// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +;// and Contributors. +;// +;// 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. +;// + + +;// +;// Categories +;// +MessageId=0x1 +SymbolicName=POCO_CTG_FATAL +Language=English +Fatal +. +MessageId=0x2 +SymbolicName=POCO_CTG_CRITICAL +Language=English +Critical +. +MessageId=0x3 +SymbolicName=POCO_CTG_ERROR +Language=English +Error +. +MessageId=0x4 +SymbolicName=POCO_CTG_WARNING +Language=English +Warning +. +MessageId=0x5 +SymbolicName=POCO_CTG_NOTICE +Language=English +Notice +. +MessageId=0x6 +SymbolicName=POCO_CTG_INFORMATION +Language=English +Information +. +MessageId=0x7 +SymbolicName=POCO_CTG_DEBUG +Language=English +Debug +. +MessageId=0x8 +SymbolicName=POCO_CTG_TRACE +Language=English +Trace +. + +;// +;// Event Identifiers +;// +MessageId=0x1000 +SymbolicName=POCO_MSG_LOG +Language=English +%1 +. diff --git a/Foundation/src/pocomsg.rc b/Foundation/src/pocomsg.rc index 116522b7d..0885a897e 100644 --- a/Foundation/src/pocomsg.rc +++ b/Foundation/src/pocomsg.rc @@ -1,2 +1,2 @@ -LANGUAGE 0x9,0x1 -1 11 MSG00001.bin +LANGUAGE 0x9,0x1 +1 11 MSG00001.bin diff --git a/Foundation/src/study.c b/Foundation/src/study.c index 7ffb14285..bdd1fcb1b 100644 --- a/Foundation/src/study.c +++ b/Foundation/src/study.c @@ -1,484 +1,484 @@ -/************************************************* -* Perl-Compatible Regular Expressions * -*************************************************/ - -/* -This is a library of functions to support regular expressions whose syntax -and semantics are as close as possible to those of the Perl 5 language. See -the file Tech.Notes for some information on the internals. - -Written by: Philip Hazel - - Copyright (c) 1997-2004 University of Cambridge - ------------------------------------------------------------------------------ -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - * 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. - - * Neither the name of the University of Cambridge nor the names of its - contributors may be used to endorse or promote products derived from - this software without specific prior written permission. - -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. ------------------------------------------------------------------------------ -*/ - - -/* Include the internals header, which itself includes Standard C headers plus -the external pcre header. */ - -#include "pcreinternal.h" - - - -/************************************************* -* Set a bit and maybe its alternate case * -*************************************************/ - -/* Given a character, set its bit in the table, and also the bit for the other -version of a letter if we are caseless. - -Arguments: - start_bits points to the bit map - c is the character - caseless the caseless flag - cd the block with char table pointers - -Returns: nothing -*/ - -static void -set_bit(uschar *start_bits, unsigned int c, BOOL caseless, compile_data *cd) -{ -start_bits[c/8] |= (1 << (c&7)); -if (caseless && (cd->ctypes[c] & ctype_letter) != 0) - start_bits[cd->fcc[c]/8] |= (1 << (cd->fcc[c]&7)); -} - - - -/************************************************* -* Create bitmap of starting chars * -*************************************************/ - -/* This function scans a compiled unanchored expression and attempts to build a -bitmap of the set of initial characters. If it can't, it returns FALSE. As time -goes by, we may be able to get more clever at doing this. - -Arguments: - code points to an expression - start_bits points to a 32-byte table, initialized to 0 - caseless the current state of the caseless flag - utf8 TRUE if in UTF-8 mode - cd the block with char table pointers - -Returns: TRUE if table built, FALSE otherwise -*/ - -static BOOL -set_start_bits(const uschar *code, uschar *start_bits, BOOL caseless, - BOOL utf8, compile_data *cd) -{ -register int c; - -/* This next statement and the later reference to dummy are here in order to -trick the optimizer of the IBM C compiler for OS/2 into generating correct -code. Apparently IBM isn't going to fix the problem, and we would rather not -disable optimization (in this module it actually makes a big difference, and -the pcre module can use all the optimization it can get). */ - -volatile int dummy; - -do - { - const uschar *tcode = code + 1 + LINK_SIZE; - BOOL try_next = TRUE; - - while (try_next) - { - /* If a branch starts with a bracket or a positive lookahead assertion, - recurse to set bits from within them. That's all for this branch. */ - - if ((int)*tcode >= OP_BRA || *tcode == OP_ASSERT) - { - if (!set_start_bits(tcode, start_bits, caseless, utf8, cd)) - return FALSE; - try_next = FALSE; - } - - else switch(*tcode) - { - default: - return FALSE; - - /* Skip over callout */ - - case OP_CALLOUT: - tcode += 2 + 2*LINK_SIZE; - break; - - /* Skip over extended extraction bracket number */ - - case OP_BRANUMBER: - tcode += 3; - break; - - /* Skip over lookbehind and negative lookahead assertions */ - - case OP_ASSERT_NOT: - case OP_ASSERTBACK: - case OP_ASSERTBACK_NOT: - do tcode += GET(tcode, 1); while (*tcode == OP_ALT); - tcode += 1+LINK_SIZE; - break; - - /* Skip over an option setting, changing the caseless flag */ - - case OP_OPT: - caseless = (tcode[1] & PCRE_CASELESS) != 0; - tcode += 2; - break; - - /* BRAZERO does the bracket, but carries on. */ - - case OP_BRAZERO: - case OP_BRAMINZERO: - if (!set_start_bits(++tcode, start_bits, caseless, utf8, cd)) - return FALSE; - dummy = 1; - do tcode += GET(tcode,1); while (*tcode == OP_ALT); - tcode += 1+LINK_SIZE; - break; - - /* Single-char * or ? sets the bit and tries the next item */ - - case OP_STAR: - case OP_MINSTAR: - case OP_QUERY: - case OP_MINQUERY: - set_bit(start_bits, tcode[1], caseless, cd); - tcode += 2; -#ifdef SUPPORT_UTF8 - if (utf8) while ((*tcode & 0xc0) == 0x80) tcode++; -#endif - break; - - /* Single-char upto sets the bit and tries the next */ - - case OP_UPTO: - case OP_MINUPTO: - set_bit(start_bits, tcode[3], caseless, cd); - tcode += 4; -#ifdef SUPPORT_UTF8 - if (utf8) while ((*tcode & 0xc0) == 0x80) tcode++; -#endif - break; - - /* At least one single char sets the bit and stops */ - - case OP_EXACT: /* Fall through */ - tcode += 2; - - case OP_CHAR: - case OP_CHARNC: - case OP_PLUS: - case OP_MINPLUS: - set_bit(start_bits, tcode[1], caseless, cd); - try_next = FALSE; - break; - - /* Single character type sets the bits and stops */ - - case OP_NOT_DIGIT: - for (c = 0; c < 32; c++) - start_bits[c] |= ~cd->cbits[c+cbit_digit]; - try_next = FALSE; - break; - - case OP_DIGIT: - for (c = 0; c < 32; c++) - start_bits[c] |= cd->cbits[c+cbit_digit]; - try_next = FALSE; - break; - - case OP_NOT_WHITESPACE: - for (c = 0; c < 32; c++) - start_bits[c] |= ~cd->cbits[c+cbit_space]; - try_next = FALSE; - break; - - case OP_WHITESPACE: - for (c = 0; c < 32; c++) - start_bits[c] |= cd->cbits[c+cbit_space]; - try_next = FALSE; - break; - - case OP_NOT_WORDCHAR: - for (c = 0; c < 32; c++) - start_bits[c] |= ~cd->cbits[c+cbit_word]; - try_next = FALSE; - break; - - case OP_WORDCHAR: - for (c = 0; c < 32; c++) - start_bits[c] |= cd->cbits[c+cbit_word]; - try_next = FALSE; - break; - - /* One or more character type fudges the pointer and restarts, knowing - it will hit a single character type and stop there. */ - - case OP_TYPEPLUS: - case OP_TYPEMINPLUS: - tcode++; - break; - - case OP_TYPEEXACT: - tcode += 3; - break; - - /* Zero or more repeats of character types set the bits and then - try again. */ - - case OP_TYPEUPTO: - case OP_TYPEMINUPTO: - tcode += 2; /* Fall through */ - - case OP_TYPESTAR: - case OP_TYPEMINSTAR: - case OP_TYPEQUERY: - case OP_TYPEMINQUERY: - switch(tcode[1]) - { - case OP_ANY: - return FALSE; - - case OP_NOT_DIGIT: - for (c = 0; c < 32; c++) - start_bits[c] |= ~cd->cbits[c+cbit_digit]; - break; - - case OP_DIGIT: - for (c = 0; c < 32; c++) - start_bits[c] |= cd->cbits[c+cbit_digit]; - break; - - case OP_NOT_WHITESPACE: - for (c = 0; c < 32; c++) - start_bits[c] |= ~cd->cbits[c+cbit_space]; - break; - - case OP_WHITESPACE: - for (c = 0; c < 32; c++) - start_bits[c] |= cd->cbits[c+cbit_space]; - break; - - case OP_NOT_WORDCHAR: - for (c = 0; c < 32; c++) - start_bits[c] |= ~cd->cbits[c+cbit_word]; - break; - - case OP_WORDCHAR: - for (c = 0; c < 32; c++) - start_bits[c] |= cd->cbits[c+cbit_word]; - break; - } - - tcode += 2; - break; - - /* Character class where all the information is in a bit map: set the - bits and either carry on or not, according to the repeat count. If it was - a negative class, and we are operating with UTF-8 characters, any byte - with a value >= 0xc4 is a potentially valid starter because it starts a - character with a value > 255. */ - - case OP_NCLASS: - if (utf8) - { - start_bits[24] |= 0xf0; /* Bits for 0xc4 - 0xc8 */ - memset(start_bits+25, 0xff, 7); /* Bits for 0xc9 - 0xff */ - } - /* Fall through */ - - case OP_CLASS: - { - tcode++; - - /* In UTF-8 mode, the bits in a bit map correspond to character - values, not to byte values. However, the bit map we are constructing is - for byte values. So we have to do a conversion for characters whose - value is > 127. In fact, there are only two possible starting bytes for - characters in the range 128 - 255. */ - - if (utf8) - { - for (c = 0; c < 16; c++) start_bits[c] |= tcode[c]; - for (c = 128; c < 256; c++) - { - if ((tcode[c/8] && (1 << (c&7))) != 0) - { - int d = (c >> 6) | 0xc0; /* Set bit for this starter */ - start_bits[d/8] |= (1 << (d&7)); /* and then skip on to the */ - c = (c & 0xc0) + 0x40 - 1; /* next relevant character. */ - } - } - } - - /* In non-UTF-8 mode, the two bit maps are completely compatible. */ - - else - { - for (c = 0; c < 32; c++) start_bits[c] |= tcode[c]; - } - - /* Advance past the bit map, and act on what follows */ - - tcode += 32; - switch (*tcode) - { - case OP_CRSTAR: - case OP_CRMINSTAR: - case OP_CRQUERY: - case OP_CRMINQUERY: - tcode++; - break; - - case OP_CRRANGE: - case OP_CRMINRANGE: - if (((tcode[1] << 8) + tcode[2]) == 0) tcode += 5; - else try_next = FALSE; - break; - - default: - try_next = FALSE; - break; - } - } - break; /* End of bitmap class handling */ - - } /* End of switch */ - } /* End of try_next loop */ - - code += GET(code, 1); /* Advance to next branch */ - } -while (*code == OP_ALT); -return TRUE; -} - - - -/************************************************* -* Study a compiled expression * -*************************************************/ - -/* This function is handed a compiled expression that it must study to produce -information that will speed up the matching. It returns a pcre_extra block -which then gets handed back to pcre_exec(). - -Arguments: - re points to the compiled expression - options contains option bits - errorptr points to where to place error messages; - set NULL unless error - -Returns: pointer to a pcre_extra block, with study_data filled in and the - appropriate flag set; - NULL on error or if no optimization possible -*/ - -EXPORT pcre_extra * -pcre_study(const pcre *external_re, int options, const char **errorptr) -{ -uschar start_bits[32]; -pcre_extra *extra; -pcre_study_data *study; -const uschar *tables; -const real_pcre *re = (const real_pcre *)external_re; -uschar *code = (uschar *)re + re->name_table_offset + - (re->name_count * re->name_entry_size); -compile_data compile_block; - -*errorptr = NULL; - -if (re == NULL || re->magic_number != MAGIC_NUMBER) - { - *errorptr = "argument is not a compiled regular expression"; - return NULL; - } - -if ((options & ~PUBLIC_STUDY_OPTIONS) != 0) - { - *errorptr = "unknown or incorrect option bit(s) set"; - return NULL; - } - -/* For an anchored pattern, or an unanchored pattern that has a first char, or -a multiline pattern that matches only at "line starts", no further processing -at present. */ - -if ((re->options & (PCRE_ANCHORED|PCRE_FIRSTSET|PCRE_STARTLINE)) != 0) - return NULL; - -/* Set the character tables in the block that is passed around */ - -tables = re->tables; -if (tables == NULL) - (void)pcre_fullinfo(external_re, NULL, PCRE_INFO_DEFAULT_TABLES, &tables); - -compile_block.lcc = tables + lcc_offset; -compile_block.fcc = tables + fcc_offset; -compile_block.cbits = tables + cbits_offset; -compile_block.ctypes = tables + ctypes_offset; - -/* See if we can find a fixed set of initial characters for the pattern. */ - -memset(start_bits, 0, 32 * sizeof(uschar)); -if (!set_start_bits(code, start_bits, (re->options & PCRE_CASELESS) != 0, - (re->options & PCRE_UTF8) != 0, &compile_block)) return NULL; - -/* Get a pcre_extra block and a pcre_study_data block. The study data is put in -the latter, which is pointed to by the former, which may also get additional -data set later by the calling program. At the moment, the size of -pcre_study_data is fixed. We nevertheless save it in a field for returning via -the pcre_fullinfo() function so that if it becomes variable in the future, we -don't have to change that code. */ - -extra = (pcre_extra *)(pcre_malloc) - (sizeof(pcre_extra) + sizeof(pcre_study_data)); - -if (extra == NULL) - { - *errorptr = "failed to get memory"; - return NULL; - } - -study = (pcre_study_data *)((char *)extra + sizeof(pcre_extra)); -extra->flags = PCRE_EXTRA_STUDY_DATA; -extra->study_data = study; - -study->size = sizeof(pcre_study_data); -study->options = PCRE_STUDY_MAPPED; -memcpy(study->start_bits, start_bits, sizeof(start_bits)); - -return extra; -} - -/* End of study.c */ +/************************************************* +* Perl-Compatible Regular Expressions * +*************************************************/ + +/* +This is a library of functions to support regular expressions whose syntax +and semantics are as close as possible to those of the Perl 5 language. See +the file Tech.Notes for some information on the internals. + +Written by: Philip Hazel + + Copyright (c) 1997-2004 University of Cambridge + +----------------------------------------------------------------------------- +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + * 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. + + * Neither the name of the University of Cambridge nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +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. +----------------------------------------------------------------------------- +*/ + + +/* Include the internals header, which itself includes Standard C headers plus +the external pcre header. */ + +#include "pcreinternal.h" + + + +/************************************************* +* Set a bit and maybe its alternate case * +*************************************************/ + +/* Given a character, set its bit in the table, and also the bit for the other +version of a letter if we are caseless. + +Arguments: + start_bits points to the bit map + c is the character + caseless the caseless flag + cd the block with char table pointers + +Returns: nothing +*/ + +static void +set_bit(uschar *start_bits, unsigned int c, BOOL caseless, compile_data *cd) +{ +start_bits[c/8] |= (1 << (c&7)); +if (caseless && (cd->ctypes[c] & ctype_letter) != 0) + start_bits[cd->fcc[c]/8] |= (1 << (cd->fcc[c]&7)); +} + + + +/************************************************* +* Create bitmap of starting chars * +*************************************************/ + +/* This function scans a compiled unanchored expression and attempts to build a +bitmap of the set of initial characters. If it can't, it returns FALSE. As time +goes by, we may be able to get more clever at doing this. + +Arguments: + code points to an expression + start_bits points to a 32-byte table, initialized to 0 + caseless the current state of the caseless flag + utf8 TRUE if in UTF-8 mode + cd the block with char table pointers + +Returns: TRUE if table built, FALSE otherwise +*/ + +static BOOL +set_start_bits(const uschar *code, uschar *start_bits, BOOL caseless, + BOOL utf8, compile_data *cd) +{ +register int c; + +/* This next statement and the later reference to dummy are here in order to +trick the optimizer of the IBM C compiler for OS/2 into generating correct +code. Apparently IBM isn't going to fix the problem, and we would rather not +disable optimization (in this module it actually makes a big difference, and +the pcre module can use all the optimization it can get). */ + +volatile int dummy; + +do + { + const uschar *tcode = code + 1 + LINK_SIZE; + BOOL try_next = TRUE; + + while (try_next) + { + /* If a branch starts with a bracket or a positive lookahead assertion, + recurse to set bits from within them. That's all for this branch. */ + + if ((int)*tcode >= OP_BRA || *tcode == OP_ASSERT) + { + if (!set_start_bits(tcode, start_bits, caseless, utf8, cd)) + return FALSE; + try_next = FALSE; + } + + else switch(*tcode) + { + default: + return FALSE; + + /* Skip over callout */ + + case OP_CALLOUT: + tcode += 2 + 2*LINK_SIZE; + break; + + /* Skip over extended extraction bracket number */ + + case OP_BRANUMBER: + tcode += 3; + break; + + /* Skip over lookbehind and negative lookahead assertions */ + + case OP_ASSERT_NOT: + case OP_ASSERTBACK: + case OP_ASSERTBACK_NOT: + do tcode += GET(tcode, 1); while (*tcode == OP_ALT); + tcode += 1+LINK_SIZE; + break; + + /* Skip over an option setting, changing the caseless flag */ + + case OP_OPT: + caseless = (tcode[1] & PCRE_CASELESS) != 0; + tcode += 2; + break; + + /* BRAZERO does the bracket, but carries on. */ + + case OP_BRAZERO: + case OP_BRAMINZERO: + if (!set_start_bits(++tcode, start_bits, caseless, utf8, cd)) + return FALSE; + dummy = 1; + do tcode += GET(tcode,1); while (*tcode == OP_ALT); + tcode += 1+LINK_SIZE; + break; + + /* Single-char * or ? sets the bit and tries the next item */ + + case OP_STAR: + case OP_MINSTAR: + case OP_QUERY: + case OP_MINQUERY: + set_bit(start_bits, tcode[1], caseless, cd); + tcode += 2; +#ifdef SUPPORT_UTF8 + if (utf8) while ((*tcode & 0xc0) == 0x80) tcode++; +#endif + break; + + /* Single-char upto sets the bit and tries the next */ + + case OP_UPTO: + case OP_MINUPTO: + set_bit(start_bits, tcode[3], caseless, cd); + tcode += 4; +#ifdef SUPPORT_UTF8 + if (utf8) while ((*tcode & 0xc0) == 0x80) tcode++; +#endif + break; + + /* At least one single char sets the bit and stops */ + + case OP_EXACT: /* Fall through */ + tcode += 2; + + case OP_CHAR: + case OP_CHARNC: + case OP_PLUS: + case OP_MINPLUS: + set_bit(start_bits, tcode[1], caseless, cd); + try_next = FALSE; + break; + + /* Single character type sets the bits and stops */ + + case OP_NOT_DIGIT: + for (c = 0; c < 32; c++) + start_bits[c] |= ~cd->cbits[c+cbit_digit]; + try_next = FALSE; + break; + + case OP_DIGIT: + for (c = 0; c < 32; c++) + start_bits[c] |= cd->cbits[c+cbit_digit]; + try_next = FALSE; + break; + + case OP_NOT_WHITESPACE: + for (c = 0; c < 32; c++) + start_bits[c] |= ~cd->cbits[c+cbit_space]; + try_next = FALSE; + break; + + case OP_WHITESPACE: + for (c = 0; c < 32; c++) + start_bits[c] |= cd->cbits[c+cbit_space]; + try_next = FALSE; + break; + + case OP_NOT_WORDCHAR: + for (c = 0; c < 32; c++) + start_bits[c] |= ~cd->cbits[c+cbit_word]; + try_next = FALSE; + break; + + case OP_WORDCHAR: + for (c = 0; c < 32; c++) + start_bits[c] |= cd->cbits[c+cbit_word]; + try_next = FALSE; + break; + + /* One or more character type fudges the pointer and restarts, knowing + it will hit a single character type and stop there. */ + + case OP_TYPEPLUS: + case OP_TYPEMINPLUS: + tcode++; + break; + + case OP_TYPEEXACT: + tcode += 3; + break; + + /* Zero or more repeats of character types set the bits and then + try again. */ + + case OP_TYPEUPTO: + case OP_TYPEMINUPTO: + tcode += 2; /* Fall through */ + + case OP_TYPESTAR: + case OP_TYPEMINSTAR: + case OP_TYPEQUERY: + case OP_TYPEMINQUERY: + switch(tcode[1]) + { + case OP_ANY: + return FALSE; + + case OP_NOT_DIGIT: + for (c = 0; c < 32; c++) + start_bits[c] |= ~cd->cbits[c+cbit_digit]; + break; + + case OP_DIGIT: + for (c = 0; c < 32; c++) + start_bits[c] |= cd->cbits[c+cbit_digit]; + break; + + case OP_NOT_WHITESPACE: + for (c = 0; c < 32; c++) + start_bits[c] |= ~cd->cbits[c+cbit_space]; + break; + + case OP_WHITESPACE: + for (c = 0; c < 32; c++) + start_bits[c] |= cd->cbits[c+cbit_space]; + break; + + case OP_NOT_WORDCHAR: + for (c = 0; c < 32; c++) + start_bits[c] |= ~cd->cbits[c+cbit_word]; + break; + + case OP_WORDCHAR: + for (c = 0; c < 32; c++) + start_bits[c] |= cd->cbits[c+cbit_word]; + break; + } + + tcode += 2; + break; + + /* Character class where all the information is in a bit map: set the + bits and either carry on or not, according to the repeat count. If it was + a negative class, and we are operating with UTF-8 characters, any byte + with a value >= 0xc4 is a potentially valid starter because it starts a + character with a value > 255. */ + + case OP_NCLASS: + if (utf8) + { + start_bits[24] |= 0xf0; /* Bits for 0xc4 - 0xc8 */ + memset(start_bits+25, 0xff, 7); /* Bits for 0xc9 - 0xff */ + } + /* Fall through */ + + case OP_CLASS: + { + tcode++; + + /* In UTF-8 mode, the bits in a bit map correspond to character + values, not to byte values. However, the bit map we are constructing is + for byte values. So we have to do a conversion for characters whose + value is > 127. In fact, there are only two possible starting bytes for + characters in the range 128 - 255. */ + + if (utf8) + { + for (c = 0; c < 16; c++) start_bits[c] |= tcode[c]; + for (c = 128; c < 256; c++) + { + if ((tcode[c/8] && (1 << (c&7))) != 0) + { + int d = (c >> 6) | 0xc0; /* Set bit for this starter */ + start_bits[d/8] |= (1 << (d&7)); /* and then skip on to the */ + c = (c & 0xc0) + 0x40 - 1; /* next relevant character. */ + } + } + } + + /* In non-UTF-8 mode, the two bit maps are completely compatible. */ + + else + { + for (c = 0; c < 32; c++) start_bits[c] |= tcode[c]; + } + + /* Advance past the bit map, and act on what follows */ + + tcode += 32; + switch (*tcode) + { + case OP_CRSTAR: + case OP_CRMINSTAR: + case OP_CRQUERY: + case OP_CRMINQUERY: + tcode++; + break; + + case OP_CRRANGE: + case OP_CRMINRANGE: + if (((tcode[1] << 8) + tcode[2]) == 0) tcode += 5; + else try_next = FALSE; + break; + + default: + try_next = FALSE; + break; + } + } + break; /* End of bitmap class handling */ + + } /* End of switch */ + } /* End of try_next loop */ + + code += GET(code, 1); /* Advance to next branch */ + } +while (*code == OP_ALT); +return TRUE; +} + + + +/************************************************* +* Study a compiled expression * +*************************************************/ + +/* This function is handed a compiled expression that it must study to produce +information that will speed up the matching. It returns a pcre_extra block +which then gets handed back to pcre_exec(). + +Arguments: + re points to the compiled expression + options contains option bits + errorptr points to where to place error messages; + set NULL unless error + +Returns: pointer to a pcre_extra block, with study_data filled in and the + appropriate flag set; + NULL on error or if no optimization possible +*/ + +EXPORT pcre_extra * +pcre_study(const pcre *external_re, int options, const char **errorptr) +{ +uschar start_bits[32]; +pcre_extra *extra; +pcre_study_data *study; +const uschar *tables; +const real_pcre *re = (const real_pcre *)external_re; +uschar *code = (uschar *)re + re->name_table_offset + + (re->name_count * re->name_entry_size); +compile_data compile_block; + +*errorptr = NULL; + +if (re == NULL || re->magic_number != MAGIC_NUMBER) + { + *errorptr = "argument is not a compiled regular expression"; + return NULL; + } + +if ((options & ~PUBLIC_STUDY_OPTIONS) != 0) + { + *errorptr = "unknown or incorrect option bit(s) set"; + return NULL; + } + +/* For an anchored pattern, or an unanchored pattern that has a first char, or +a multiline pattern that matches only at "line starts", no further processing +at present. */ + +if ((re->options & (PCRE_ANCHORED|PCRE_FIRSTSET|PCRE_STARTLINE)) != 0) + return NULL; + +/* Set the character tables in the block that is passed around */ + +tables = re->tables; +if (tables == NULL) + (void)pcre_fullinfo(external_re, NULL, PCRE_INFO_DEFAULT_TABLES, &tables); + +compile_block.lcc = tables + lcc_offset; +compile_block.fcc = tables + fcc_offset; +compile_block.cbits = tables + cbits_offset; +compile_block.ctypes = tables + ctypes_offset; + +/* See if we can find a fixed set of initial characters for the pattern. */ + +memset(start_bits, 0, 32 * sizeof(uschar)); +if (!set_start_bits(code, start_bits, (re->options & PCRE_CASELESS) != 0, + (re->options & PCRE_UTF8) != 0, &compile_block)) return NULL; + +/* Get a pcre_extra block and a pcre_study_data block. The study data is put in +the latter, which is pointed to by the former, which may also get additional +data set later by the calling program. At the moment, the size of +pcre_study_data is fixed. We nevertheless save it in a field for returning via +the pcre_fullinfo() function so that if it becomes variable in the future, we +don't have to change that code. */ + +extra = (pcre_extra *)(pcre_malloc) + (sizeof(pcre_extra) + sizeof(pcre_study_data)); + +if (extra == NULL) + { + *errorptr = "failed to get memory"; + return NULL; + } + +study = (pcre_study_data *)((char *)extra + sizeof(pcre_extra)); +extra->flags = PCRE_EXTRA_STUDY_DATA; +extra->study_data = study; + +study->size = sizeof(pcre_study_data); +study->options = PCRE_STUDY_MAPPED; +memcpy(study->start_bits, start_bits, sizeof(start_bits)); + +return extra; +} + +/* End of study.c */ diff --git a/Foundation/src/trees.c b/Foundation/src/trees.c index 84f71dda9..698dc3f33 100644 --- a/Foundation/src/trees.c +++ b/Foundation/src/trees.c @@ -1,1223 +1,1223 @@ -/* trees.c -- output deflated data using Huffman coding - * Copyright (C) 1995-2005 Jean-loup Gailly - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -/* - * ALGORITHM - * - * The "deflation" process uses several Huffman trees. The more - * common source values are represented by shorter bit sequences. - * - * Each code tree is stored in a compressed form which is itself - * a Huffman encoding of the lengths of all the code strings (in - * ascending order by source values). The actual code strings are - * reconstructed from the lengths in the inflate process, as described - * in the deflate specification. - * - * REFERENCES - * - * Deutsch, L.P.,"'Deflate' Compressed Data Format Specification". - * Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc - * - * Storer, James A. - * Data Compression: Methods and Theory, pp. 49-50. - * Computer Science Press, 1988. ISBN 0-7167-8156-5. - * - * Sedgewick, R. - * Algorithms, p290. - * Addison-Wesley, 1983. ISBN 0-201-06672-6. - */ - -/* @(#) $Id: //poco/1.2/Foundation/src/trees.c#1 $ */ - -/* #define GEN_TREES_H */ - -#if defined(_MSC_VER) - #pragma warning(disable:4267) // conversion from ... possble loss of data -#endif - -#include "deflate.h" - -#ifdef DEBUG -# include -#endif - -/* =========================================================================== - * Constants - */ - -#define MAX_BL_BITS 7 -/* Bit length codes must not exceed MAX_BL_BITS bits */ - -#define END_BLOCK 256 -/* end of block literal code */ - -#define REP_3_6 16 -/* repeat previous bit length 3-6 times (2 bits of repeat count) */ - -#define REPZ_3_10 17 -/* repeat a zero length 3-10 times (3 bits of repeat count) */ - -#define REPZ_11_138 18 -/* repeat a zero length 11-138 times (7 bits of repeat count) */ - -local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */ - = {0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0}; - -local const int extra_dbits[D_CODES] /* extra bits for each distance code */ - = {0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13}; - -local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */ - = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7}; - -local const uch bl_order[BL_CODES] - = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15}; -/* The lengths of the bit length codes are sent in order of decreasing - * probability, to avoid transmitting the lengths for unused bit length codes. - */ - -#define Buf_size (8 * 2*sizeof(char)) -/* Number of bits used within bi_buf. (bi_buf might be implemented on - * more than 16 bits on some systems.) - */ - -/* =========================================================================== - * Local data. These are initialized only once. - */ - -#define DIST_CODE_LEN 512 /* see definition of array dist_code below */ - -#if defined(GEN_TREES_H) || !defined(STDC) -/* non ANSI compilers may not accept trees.h */ - -local ct_data static_ltree[L_CODES+2]; -/* The static literal tree. Since the bit lengths are imposed, there is no - * need for the L_CODES extra codes used during heap construction. However - * The codes 286 and 287 are needed to build a canonical tree (see _tr_init - * below). - */ - -local ct_data static_dtree[D_CODES]; -/* The static distance tree. (Actually a trivial tree since all codes use - * 5 bits.) - */ - -uch _dist_code[DIST_CODE_LEN]; -/* Distance codes. The first 256 values correspond to the distances - * 3 .. 258, the last 256 values correspond to the top 8 bits of - * the 15 bit distances. - */ - -uch _length_code[MAX_MATCH-MIN_MATCH+1]; -/* length code for each normalized match length (0 == MIN_MATCH) */ - -local int base_length[LENGTH_CODES]; -/* First normalized length for each code (0 = MIN_MATCH) */ - -local int base_dist[D_CODES]; -/* First normalized distance for each code (0 = distance of 1) */ - -#else -# include "trees.h" -#endif /* GEN_TREES_H */ - -struct static_tree_desc_s { - const ct_data *static_tree; /* static tree or NULL */ - const intf *extra_bits; /* extra bits for each code or NULL */ - int extra_base; /* base index for extra_bits */ - int elems; /* max number of elements in the tree */ - int max_length; /* max bit length for the codes */ -}; - -local static_tree_desc static_l_desc = -{static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS}; - -local static_tree_desc static_d_desc = -{static_dtree, extra_dbits, 0, D_CODES, MAX_BITS}; - -local static_tree_desc static_bl_desc = -{(const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS}; - -/* =========================================================================== - * Local (static) routines in this file. - */ - -local void tr_static_init OF((void)); -local void init_block OF((deflate_state *s)); -local void pqdownheap OF((deflate_state *s, ct_data *tree, int k)); -local void gen_bitlen OF((deflate_state *s, tree_desc *desc)); -local void gen_codes OF((ct_data *tree, int max_code, ushf *bl_count)); -local void build_tree OF((deflate_state *s, tree_desc *desc)); -local void scan_tree OF((deflate_state *s, ct_data *tree, int max_code)); -local void send_tree OF((deflate_state *s, ct_data *tree, int max_code)); -local int build_bl_tree OF((deflate_state *s)); -local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes, - int blcodes)); -local void compress_block OF((deflate_state *s, ct_data *ltree, - ct_data *dtree)); -local void set_data_type OF((deflate_state *s)); -local unsigned bi_reverse OF((unsigned value, int length)); -local void bi_windup OF((deflate_state *s)); -local void bi_flush OF((deflate_state *s)); -local void copy_block OF((deflate_state *s, charf *buf, unsigned len, - int header)); - -#ifdef GEN_TREES_H -local void gen_trees_header OF((void)); -#endif - -#ifndef DEBUG -# define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len) - /* Send a code of the given tree. c and tree must not have side effects */ - -#else /* DEBUG */ -# define send_code(s, c, tree) \ - { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \ - send_bits(s, tree[c].Code, tree[c].Len); } -#endif - -/* =========================================================================== - * Output a short LSB first on the stream. - * IN assertion: there is enough room in pendingBuf. - */ -#define put_short(s, w) { \ - put_byte(s, (uch)((w) & 0xff)); \ - put_byte(s, (uch)((ush)(w) >> 8)); \ -} - -/* =========================================================================== - * Send a value on a given number of bits. - * IN assertion: length <= 16 and value fits in length bits. - */ -#ifdef DEBUG -local void send_bits OF((deflate_state *s, int value, int length)); - -local void send_bits(s, value, length) - deflate_state *s; - int value; /* value to send */ - int length; /* number of bits */ -{ - Tracevv((stderr," l %2d v %4x ", length, value)); - Assert(length > 0 && length <= 15, "invalid length"); - s->bits_sent += (ulg)length; - - /* If not enough room in bi_buf, use (valid) bits from bi_buf and - * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid)) - * unused bits in value. - */ - if (s->bi_valid > (int)Buf_size - length) { - s->bi_buf |= (value << s->bi_valid); - put_short(s, s->bi_buf); - s->bi_buf = (ush)value >> (Buf_size - s->bi_valid); - s->bi_valid += length - Buf_size; - } else { - s->bi_buf |= value << s->bi_valid; - s->bi_valid += length; - } -} -#else /* !DEBUG */ - -#define send_bits(s, value, length) \ -{ int len = length;\ - if (s->bi_valid > (int)Buf_size - len) {\ - int val = value;\ - s->bi_buf |= (val << s->bi_valid);\ - put_short(s, s->bi_buf);\ - s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\ - s->bi_valid += len - Buf_size;\ - } else {\ - s->bi_buf |= (value) << s->bi_valid;\ - s->bi_valid += len;\ - }\ -} -#endif /* DEBUG */ - - -/* the arguments must not have side effects */ - -/* =========================================================================== - * Initialize the various 'constant' tables. - */ -local void tr_static_init() -{ -#if defined(GEN_TREES_H) || !defined(STDC) - static int static_init_done = 0; - int n; /* iterates over tree elements */ - int bits; /* bit counter */ - int length; /* length value */ - int code; /* code value */ - int dist; /* distance index */ - ush bl_count[MAX_BITS+1]; - /* number of codes at each bit length for an optimal tree */ - - if (static_init_done) return; - - /* For some embedded targets, global variables are not initialized: */ - static_l_desc.static_tree = static_ltree; - static_l_desc.extra_bits = extra_lbits; - static_d_desc.static_tree = static_dtree; - static_d_desc.extra_bits = extra_dbits; - static_bl_desc.extra_bits = extra_blbits; - - /* Initialize the mapping length (0..255) -> length code (0..28) */ - length = 0; - for (code = 0; code < LENGTH_CODES-1; code++) { - base_length[code] = length; - for (n = 0; n < (1< dist code (0..29) */ - dist = 0; - for (code = 0 ; code < 16; code++) { - base_dist[code] = dist; - for (n = 0; n < (1<>= 7; /* from now on, all distances are divided by 128 */ - for ( ; code < D_CODES; code++) { - base_dist[code] = dist << 7; - for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) { - _dist_code[256 + dist++] = (uch)code; - } - } - Assert (dist == 256, "tr_static_init: 256+dist != 512"); - - /* Construct the codes of the static literal tree */ - for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0; - n = 0; - while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++; - while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++; - while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++; - while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++; - /* Codes 286 and 287 do not exist, but we must include them in the - * tree construction to get a canonical Huffman tree (longest code - * all ones) - */ - gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count); - - /* The static distance tree is trivial: */ - for (n = 0; n < D_CODES; n++) { - static_dtree[n].Len = 5; - static_dtree[n].Code = bi_reverse((unsigned)n, 5); - } - static_init_done = 1; - -# ifdef GEN_TREES_H - gen_trees_header(); -# endif -#endif /* defined(GEN_TREES_H) || !defined(STDC) */ -} - -/* =========================================================================== - * Genererate the file trees.h describing the static trees. - */ -#ifdef GEN_TREES_H -# ifndef DEBUG -# include -# endif - -# define SEPARATOR(i, last, width) \ - ((i) == (last)? "\n};\n\n" : \ - ((i) % (width) == (width)-1 ? ",\n" : ", ")) - -void gen_trees_header() -{ - FILE *header = fopen("trees.h", "w"); - int i; - - Assert (header != NULL, "Can't open trees.h"); - fprintf(header, - "/* header created automatically with -DGEN_TREES_H */\n\n"); - - fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n"); - for (i = 0; i < L_CODES+2; i++) { - fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code, - static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5)); - } - - fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n"); - for (i = 0; i < D_CODES; i++) { - fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code, - static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5)); - } - - fprintf(header, "const uch _dist_code[DIST_CODE_LEN] = {\n"); - for (i = 0; i < DIST_CODE_LEN; i++) { - fprintf(header, "%2u%s", _dist_code[i], - SEPARATOR(i, DIST_CODE_LEN-1, 20)); - } - - fprintf(header, "const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {\n"); - for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) { - fprintf(header, "%2u%s", _length_code[i], - SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20)); - } - - fprintf(header, "local const int base_length[LENGTH_CODES] = {\n"); - for (i = 0; i < LENGTH_CODES; i++) { - fprintf(header, "%1u%s", base_length[i], - SEPARATOR(i, LENGTH_CODES-1, 20)); - } - - fprintf(header, "local const int base_dist[D_CODES] = {\n"); - for (i = 0; i < D_CODES; i++) { - fprintf(header, "%5u%s", base_dist[i], - SEPARATOR(i, D_CODES-1, 10)); - } - - fclose(header); -} -#endif /* GEN_TREES_H */ - -/* =========================================================================== - * Initialize the tree data structures for a new zlib stream. - */ -void _tr_init(s) - deflate_state *s; -{ - tr_static_init(); - - s->l_desc.dyn_tree = s->dyn_ltree; - s->l_desc.stat_desc = &static_l_desc; - - s->d_desc.dyn_tree = s->dyn_dtree; - s->d_desc.stat_desc = &static_d_desc; - - s->bl_desc.dyn_tree = s->bl_tree; - s->bl_desc.stat_desc = &static_bl_desc; - - s->bi_buf = 0; - s->bi_valid = 0; - s->last_eob_len = 8; /* enough lookahead for inflate */ -#ifdef DEBUG - s->compressed_len = 0L; - s->bits_sent = 0L; -#endif - - /* Initialize the first block of the first file: */ - init_block(s); -} - -/* =========================================================================== - * Initialize a new block. - */ -local void init_block(s) - deflate_state *s; -{ - int n; /* iterates over tree elements */ - - /* Initialize the trees. */ - for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0; - for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0; - for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0; - - s->dyn_ltree[END_BLOCK].Freq = 1; - s->opt_len = s->static_len = 0L; - s->last_lit = s->matches = 0; -} - -#define SMALLEST 1 -/* Index within the heap array of least frequent node in the Huffman tree */ - - -/* =========================================================================== - * Remove the smallest element from the heap and recreate the heap with - * one less element. Updates heap and heap_len. - */ -#define pqremove(s, tree, top) \ -{\ - top = s->heap[SMALLEST]; \ - s->heap[SMALLEST] = s->heap[s->heap_len--]; \ - pqdownheap(s, tree, SMALLEST); \ -} - -/* =========================================================================== - * Compares to subtrees, using the tree depth as tie breaker when - * the subtrees have equal frequency. This minimizes the worst case length. - */ -#define smaller(tree, n, m, depth) \ - (tree[n].Freq < tree[m].Freq || \ - (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m])) - -/* =========================================================================== - * Restore the heap property by moving down the tree starting at node k, - * exchanging a node with the smallest of its two sons if necessary, stopping - * when the heap property is re-established (each father smaller than its - * two sons). - */ -local void pqdownheap(s, tree, k) - deflate_state *s; - ct_data *tree; /* the tree to restore */ - int k; /* node to move down */ -{ - int v = s->heap[k]; - int j = k << 1; /* left son of k */ - while (j <= s->heap_len) { - /* Set j to the smallest of the two sons: */ - if (j < s->heap_len && - smaller(tree, s->heap[j+1], s->heap[j], s->depth)) { - j++; - } - /* Exit if v is smaller than both sons */ - if (smaller(tree, v, s->heap[j], s->depth)) break; - - /* Exchange v with the smallest son */ - s->heap[k] = s->heap[j]; k = j; - - /* And continue down the tree, setting j to the left son of k */ - j <<= 1; - } - s->heap[k] = v; -} - -/* =========================================================================== - * Compute the optimal bit lengths for a tree and update the total bit length - * for the current block. - * IN assertion: the fields freq and dad are set, heap[heap_max] and - * above are the tree nodes sorted by increasing frequency. - * OUT assertions: the field len is set to the optimal bit length, the - * array bl_count contains the frequencies for each bit length. - * The length opt_len is updated; static_len is also updated if stree is - * not null. - */ -local void gen_bitlen(s, desc) - deflate_state *s; - tree_desc *desc; /* the tree descriptor */ -{ - ct_data *tree = desc->dyn_tree; - int max_code = desc->max_code; - const ct_data *stree = desc->stat_desc->static_tree; - const intf *extra = desc->stat_desc->extra_bits; - int base = desc->stat_desc->extra_base; - int max_length = desc->stat_desc->max_length; - int h; /* heap index */ - int n, m; /* iterate over the tree elements */ - int bits; /* bit length */ - int xbits; /* extra bits */ - ush f; /* frequency */ - int overflow = 0; /* number of elements with bit length too large */ - - for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0; - - /* In a first pass, compute the optimal bit lengths (which may - * overflow in the case of the bit length tree). - */ - tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */ - - for (h = s->heap_max+1; h < HEAP_SIZE; h++) { - n = s->heap[h]; - bits = tree[tree[n].Dad].Len + 1; - if (bits > max_length) bits = max_length, overflow++; - tree[n].Len = (ush)bits; - /* We overwrite tree[n].Dad which is no longer needed */ - - if (n > max_code) continue; /* not a leaf node */ - - s->bl_count[bits]++; - xbits = 0; - if (n >= base) xbits = extra[n-base]; - f = tree[n].Freq; - s->opt_len += (ulg)f * (bits + xbits); - if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits); - } - if (overflow == 0) return; - - Trace((stderr,"\nbit length overflow\n")); - /* This happens for example on obj2 and pic of the Calgary corpus */ - - /* Find the first bit length which could increase: */ - do { - bits = max_length-1; - while (s->bl_count[bits] == 0) bits--; - s->bl_count[bits]--; /* move one leaf down the tree */ - s->bl_count[bits+1] += 2; /* move one overflow item as its brother */ - s->bl_count[max_length]--; - /* The brother of the overflow item also moves one step up, - * but this does not affect bl_count[max_length] - */ - overflow -= 2; - } while (overflow > 0); - - /* Now recompute all bit lengths, scanning in increasing frequency. - * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all - * lengths instead of fixing only the wrong ones. This idea is taken - * from 'ar' written by Haruhiko Okumura.) - */ - for (bits = max_length; bits != 0; bits--) { - n = s->bl_count[bits]; - while (n != 0) { - m = s->heap[--h]; - if (m > max_code) continue; - if ((unsigned) tree[m].Len != (unsigned) bits) { - Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits)); - s->opt_len += ((long)bits - (long)tree[m].Len) - *(long)tree[m].Freq; - tree[m].Len = (ush)bits; - } - n--; - } - } -} - -/* =========================================================================== - * Generate the codes for a given tree and bit counts (which need not be - * optimal). - * IN assertion: the array bl_count contains the bit length statistics for - * the given tree and the field len is set for all tree elements. - * OUT assertion: the field code is set for all tree elements of non - * zero code length. - */ -local void gen_codes (tree, max_code, bl_count) - ct_data *tree; /* the tree to decorate */ - int max_code; /* largest code with non zero frequency */ - ushf *bl_count; /* number of codes at each bit length */ -{ - ush next_code[MAX_BITS+1]; /* next code value for each bit length */ - ush code = 0; /* running code value */ - int bits; /* bit index */ - int n; /* code index */ - - /* The distribution counts are first used to generate the code values - * without bit reversal. - */ - for (bits = 1; bits <= MAX_BITS; bits++) { - next_code[bits] = code = (code + bl_count[bits-1]) << 1; - } - /* Check that the bit counts in bl_count are consistent. The last code - * must be all ones. - */ - Assert (code + bl_count[MAX_BITS]-1 == (1<dyn_tree; - const ct_data *stree = desc->stat_desc->static_tree; - int elems = desc->stat_desc->elems; - int n, m; /* iterate over heap elements */ - int max_code = -1; /* largest code with non zero frequency */ - int node; /* new node being created */ - - /* Construct the initial heap, with least frequent element in - * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. - * heap[0] is not used. - */ - s->heap_len = 0, s->heap_max = HEAP_SIZE; - - for (n = 0; n < elems; n++) { - if (tree[n].Freq != 0) { - s->heap[++(s->heap_len)] = max_code = n; - s->depth[n] = 0; - } else { - tree[n].Len = 0; - } - } - - /* The pkzip format requires that at least one distance code exists, - * and that at least one bit should be sent even if there is only one - * possible code. So to avoid special checks later on we force at least - * two codes of non zero frequency. - */ - while (s->heap_len < 2) { - node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0); - tree[node].Freq = 1; - s->depth[node] = 0; - s->opt_len--; if (stree) s->static_len -= stree[node].Len; - /* node is 0 or 1 so it does not have extra bits */ - } - desc->max_code = max_code; - - /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, - * establish sub-heaps of increasing lengths: - */ - for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n); - - /* Construct the Huffman tree by repeatedly combining the least two - * frequent nodes. - */ - node = elems; /* next internal node of the tree */ - do { - pqremove(s, tree, n); /* n = node of least frequency */ - m = s->heap[SMALLEST]; /* m = node of next least frequency */ - - s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */ - s->heap[--(s->heap_max)] = m; - - /* Create a new node father of n and m */ - tree[node].Freq = tree[n].Freq + tree[m].Freq; - s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ? - s->depth[n] : s->depth[m]) + 1); - tree[n].Dad = tree[m].Dad = (ush)node; -#ifdef DUMP_BL_TREE - if (tree == s->bl_tree) { - fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)", - node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq); - } -#endif - /* and insert the new node in the heap */ - s->heap[SMALLEST] = node++; - pqdownheap(s, tree, SMALLEST); - - } while (s->heap_len >= 2); - - s->heap[--(s->heap_max)] = s->heap[SMALLEST]; - - /* At this point, the fields freq and dad are set. We can now - * generate the bit lengths. - */ - gen_bitlen(s, (tree_desc *)desc); - - /* The field len is now set, we can generate the bit codes */ - gen_codes ((ct_data *)tree, max_code, s->bl_count); -} - -/* =========================================================================== - * Scan a literal or distance tree to determine the frequencies of the codes - * in the bit length tree. - */ -local void scan_tree (s, tree, max_code) - deflate_state *s; - ct_data *tree; /* the tree to be scanned */ - int max_code; /* and its largest code of non zero frequency */ -{ - int n; /* iterates over all tree elements */ - int prevlen = -1; /* last emitted length */ - int curlen; /* length of current code */ - int nextlen = tree[0].Len; /* length of next code */ - int count = 0; /* repeat count of the current code */ - int max_count = 7; /* max repeat count */ - int min_count = 4; /* min repeat count */ - - if (nextlen == 0) max_count = 138, min_count = 3; - tree[max_code+1].Len = (ush)0xffff; /* guard */ - - for (n = 0; n <= max_code; n++) { - curlen = nextlen; nextlen = tree[n+1].Len; - if (++count < max_count && curlen == nextlen) { - continue; - } else if (count < min_count) { - s->bl_tree[curlen].Freq += count; - } else if (curlen != 0) { - if (curlen != prevlen) s->bl_tree[curlen].Freq++; - s->bl_tree[REP_3_6].Freq++; - } else if (count <= 10) { - s->bl_tree[REPZ_3_10].Freq++; - } else { - s->bl_tree[REPZ_11_138].Freq++; - } - count = 0; prevlen = curlen; - if (nextlen == 0) { - max_count = 138, min_count = 3; - } else if (curlen == nextlen) { - max_count = 6, min_count = 3; - } else { - max_count = 7, min_count = 4; - } - } -} - -/* =========================================================================== - * Send a literal or distance tree in compressed form, using the codes in - * bl_tree. - */ -local void send_tree (s, tree, max_code) - deflate_state *s; - ct_data *tree; /* the tree to be scanned */ - int max_code; /* and its largest code of non zero frequency */ -{ - int n; /* iterates over all tree elements */ - int prevlen = -1; /* last emitted length */ - int curlen; /* length of current code */ - int nextlen = tree[0].Len; /* length of next code */ - int count = 0; /* repeat count of the current code */ - int max_count = 7; /* max repeat count */ - int min_count = 4; /* min repeat count */ - - /* tree[max_code+1].Len = -1; */ /* guard already set */ - if (nextlen == 0) max_count = 138, min_count = 3; - - for (n = 0; n <= max_code; n++) { - curlen = nextlen; nextlen = tree[n+1].Len; - if (++count < max_count && curlen == nextlen) { - continue; - } else if (count < min_count) { - do { send_code(s, curlen, s->bl_tree); } while (--count != 0); - - } else if (curlen != 0) { - if (curlen != prevlen) { - send_code(s, curlen, s->bl_tree); count--; - } - Assert(count >= 3 && count <= 6, " 3_6?"); - send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2); - - } else if (count <= 10) { - send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3); - - } else { - send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7); - } - count = 0; prevlen = curlen; - if (nextlen == 0) { - max_count = 138, min_count = 3; - } else if (curlen == nextlen) { - max_count = 6, min_count = 3; - } else { - max_count = 7, min_count = 4; - } - } -} - -/* =========================================================================== - * Construct the Huffman tree for the bit lengths and return the index in - * bl_order of the last bit length code to send. - */ -local int build_bl_tree(s) - deflate_state *s; -{ - int max_blindex; /* index of last bit length code of non zero freq */ - - /* Determine the bit length frequencies for literal and distance trees */ - scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code); - scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code); - - /* Build the bit length tree: */ - build_tree(s, (tree_desc *)(&(s->bl_desc))); - /* opt_len now includes the length of the tree representations, except - * the lengths of the bit lengths codes and the 5+5+4 bits for the counts. - */ - - /* Determine the number of bit length codes to send. The pkzip format - * requires that at least 4 bit length codes be sent. (appnote.txt says - * 3 but the actual value used is 4.) - */ - for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) { - if (s->bl_tree[bl_order[max_blindex]].Len != 0) break; - } - /* Update opt_len to include the bit length tree and counts */ - s->opt_len += 3*(max_blindex+1) + 5+5+4; - Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld", - s->opt_len, s->static_len)); - - return max_blindex; -} - -/* =========================================================================== - * Send the header for a block using dynamic Huffman trees: the counts, the - * lengths of the bit length codes, the literal tree and the distance tree. - * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. - */ -local void send_all_trees(s, lcodes, dcodes, blcodes) - deflate_state *s; - int lcodes, dcodes, blcodes; /* number of codes for each tree */ -{ - int rank; /* index in bl_order */ - - Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes"); - Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES, - "too many codes"); - Tracev((stderr, "\nbl counts: ")); - send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */ - send_bits(s, dcodes-1, 5); - send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */ - for (rank = 0; rank < blcodes; rank++) { - Tracev((stderr, "\nbl code %2d ", bl_order[rank])); - send_bits(s, s->bl_tree[bl_order[rank]].Len, 3); - } - Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent)); - - send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */ - Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent)); - - send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */ - Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent)); -} - -/* =========================================================================== - * Send a stored block - */ -void _tr_stored_block(s, buf, stored_len, eof) - deflate_state *s; - charf *buf; /* input block */ - ulg stored_len; /* length of input block */ - int eof; /* true if this is the last block for a file */ -{ - send_bits(s, (STORED_BLOCK<<1)+eof, 3); /* send block type */ -#ifdef DEBUG - s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L; - s->compressed_len += (stored_len + 4) << 3; -#endif - copy_block(s, buf, (unsigned)stored_len, 1); /* with header */ -} - -/* =========================================================================== - * Send one empty static block to give enough lookahead for inflate. - * This takes 10 bits, of which 7 may remain in the bit buffer. - * The current inflate code requires 9 bits of lookahead. If the - * last two codes for the previous block (real code plus EOB) were coded - * on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode - * the last real code. In this case we send two empty static blocks instead - * of one. (There are no problems if the previous block is stored or fixed.) - * To simplify the code, we assume the worst case of last real code encoded - * on one bit only. - */ -void _tr_align(s) - deflate_state *s; -{ - send_bits(s, STATIC_TREES<<1, 3); - send_code(s, END_BLOCK, static_ltree); -#ifdef DEBUG - s->compressed_len += 10L; /* 3 for block type, 7 for EOB */ -#endif - bi_flush(s); - /* Of the 10 bits for the empty block, we have already sent - * (10 - bi_valid) bits. The lookahead for the last real code (before - * the EOB of the previous block) was thus at least one plus the length - * of the EOB plus what we have just sent of the empty static block. - */ - if (1 + s->last_eob_len + 10 - s->bi_valid < 9) { - send_bits(s, STATIC_TREES<<1, 3); - send_code(s, END_BLOCK, static_ltree); -#ifdef DEBUG - s->compressed_len += 10L; -#endif - bi_flush(s); - } - s->last_eob_len = 7; -} - -/* =========================================================================== - * Determine the best encoding for the current block: dynamic trees, static - * trees or store, and output the encoded block to the zip file. - */ -void _tr_flush_block(s, buf, stored_len, eof) - deflate_state *s; - charf *buf; /* input block, or NULL if too old */ - ulg stored_len; /* length of input block */ - int eof; /* true if this is the last block for a file */ -{ - ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */ - int max_blindex = 0; /* index of last bit length code of non zero freq */ - - /* Build the Huffman trees unless a stored block is forced */ - if (s->level > 0) { - - /* Check if the file is binary or text */ - if (stored_len > 0 && s->strm->data_type == Z_UNKNOWN) - set_data_type(s); - - /* Construct the literal and distance trees */ - build_tree(s, (tree_desc *)(&(s->l_desc))); - Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len, - s->static_len)); - - build_tree(s, (tree_desc *)(&(s->d_desc))); - Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len, - s->static_len)); - /* At this point, opt_len and static_len are the total bit lengths of - * the compressed block data, excluding the tree representations. - */ - - /* Build the bit length tree for the above two trees, and get the index - * in bl_order of the last bit length code to send. - */ - max_blindex = build_bl_tree(s); - - /* Determine the best encoding. Compute the block lengths in bytes. */ - opt_lenb = (s->opt_len+3+7)>>3; - static_lenb = (s->static_len+3+7)>>3; - - Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ", - opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len, - s->last_lit)); - - if (static_lenb <= opt_lenb) opt_lenb = static_lenb; - - } else { - Assert(buf != (char*)0, "lost buf"); - opt_lenb = static_lenb = stored_len + 5; /* force a stored block */ - } - -#ifdef FORCE_STORED - if (buf != (char*)0) { /* force stored block */ -#else - if (stored_len+4 <= opt_lenb && buf != (char*)0) { - /* 4: two words for the lengths */ -#endif - /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE. - * Otherwise we can't have processed more than WSIZE input bytes since - * the last block flush, because compression would have been - * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to - * transform a block into a stored block. - */ - _tr_stored_block(s, buf, stored_len, eof); - -#ifdef FORCE_STATIC - } else if (static_lenb >= 0) { /* force static trees */ -#else - } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) { -#endif - send_bits(s, (STATIC_TREES<<1)+eof, 3); - compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree); -#ifdef DEBUG - s->compressed_len += 3 + s->static_len; -#endif - } else { - send_bits(s, (DYN_TREES<<1)+eof, 3); - send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1, - max_blindex+1); - compress_block(s, (ct_data *)s->dyn_ltree, (ct_data *)s->dyn_dtree); -#ifdef DEBUG - s->compressed_len += 3 + s->opt_len; -#endif - } - Assert (s->compressed_len == s->bits_sent, "bad compressed size"); - /* The above check is made mod 2^32, for files larger than 512 MB - * and uLong implemented on 32 bits. - */ - init_block(s); - - if (eof) { - bi_windup(s); -#ifdef DEBUG - s->compressed_len += 7; /* align on byte boundary */ -#endif - } - Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3, - s->compressed_len-7*eof)); -} - -/* =========================================================================== - * Save the match info and tally the frequency counts. Return true if - * the current block must be flushed. - */ -int _tr_tally (s, dist, lc) - deflate_state *s; - unsigned dist; /* distance of matched string */ - unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */ -{ - s->d_buf[s->last_lit] = (ush)dist; - s->l_buf[s->last_lit++] = (uch)lc; - if (dist == 0) { - /* lc is the unmatched char */ - s->dyn_ltree[lc].Freq++; - } else { - s->matches++; - /* Here, lc is the match length - MIN_MATCH */ - dist--; /* dist = match distance - 1 */ - Assert((ush)dist < (ush)MAX_DIST(s) && - (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) && - (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match"); - - s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++; - s->dyn_dtree[d_code(dist)].Freq++; - } - -#ifdef TRUNCATE_BLOCK - /* Try to guess if it is profitable to stop the current block here */ - if ((s->last_lit & 0x1fff) == 0 && s->level > 2) { - /* Compute an upper bound for the compressed length */ - ulg out_length = (ulg)s->last_lit*8L; - ulg in_length = (ulg)((long)s->strstart - s->block_start); - int dcode; - for (dcode = 0; dcode < D_CODES; dcode++) { - out_length += (ulg)s->dyn_dtree[dcode].Freq * - (5L+extra_dbits[dcode]); - } - out_length >>= 3; - Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ", - s->last_lit, in_length, out_length, - 100L - out_length*100L/in_length)); - if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1; - } -#endif - return (s->last_lit == s->lit_bufsize-1); - /* We avoid equality with lit_bufsize because of wraparound at 64K - * on 16 bit machines and because stored blocks are restricted to - * 64K-1 bytes. - */ -} - -/* =========================================================================== - * Send the block data compressed using the given Huffman trees - */ -local void compress_block(s, ltree, dtree) - deflate_state *s; - ct_data *ltree; /* literal tree */ - ct_data *dtree; /* distance tree */ -{ - unsigned dist; /* distance of matched string */ - int lc; /* match length or unmatched char (if dist == 0) */ - unsigned lx = 0; /* running index in l_buf */ - unsigned code; /* the code to send */ - int extra; /* number of extra bits to send */ - - if (s->last_lit != 0) do { - dist = s->d_buf[lx]; - lc = s->l_buf[lx++]; - if (dist == 0) { - send_code(s, lc, ltree); /* send a literal byte */ - Tracecv(isgraph(lc), (stderr," '%c' ", lc)); - } else { - /* Here, lc is the match length - MIN_MATCH */ - code = _length_code[lc]; - send_code(s, code+LITERALS+1, ltree); /* send the length code */ - extra = extra_lbits[code]; - if (extra != 0) { - lc -= base_length[code]; - send_bits(s, lc, extra); /* send the extra length bits */ - } - dist--; /* dist is now the match distance - 1 */ - code = d_code(dist); - Assert (code < D_CODES, "bad d_code"); - - send_code(s, code, dtree); /* send the distance code */ - extra = extra_dbits[code]; - if (extra != 0) { - dist -= base_dist[code]; - send_bits(s, dist, extra); /* send the extra distance bits */ - } - } /* literal or match pair ? */ - - /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */ - Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx, - "pendingBuf overflow"); - - } while (lx < s->last_lit); - - send_code(s, END_BLOCK, ltree); - s->last_eob_len = ltree[END_BLOCK].Len; -} - -/* =========================================================================== - * Set the data type to BINARY or TEXT, using a crude approximation: - * set it to Z_TEXT if all symbols are either printable characters (33 to 255) - * or white spaces (9 to 13, or 32); or set it to Z_BINARY otherwise. - * IN assertion: the fields Freq of dyn_ltree are set. - */ -local void set_data_type(s) - deflate_state *s; -{ - int n; - - for (n = 0; n < 9; n++) - if (s->dyn_ltree[n].Freq != 0) - break; - if (n == 9) - for (n = 14; n < 32; n++) - if (s->dyn_ltree[n].Freq != 0) - break; - s->strm->data_type = (n == 32) ? Z_TEXT : Z_BINARY; -} - -/* =========================================================================== - * Reverse the first len bits of a code, using straightforward code (a faster - * method would use a table) - * IN assertion: 1 <= len <= 15 - */ -local unsigned bi_reverse(code, len) - unsigned code; /* the value to invert */ - int len; /* its bit length */ -{ - register unsigned res = 0; - do { - res |= code & 1; - code >>= 1, res <<= 1; - } while (--len > 0); - return res >> 1; -} - -/* =========================================================================== - * Flush the bit buffer, keeping at most 7 bits in it. - */ -local void bi_flush(s) - deflate_state *s; -{ - if (s->bi_valid == 16) { - put_short(s, s->bi_buf); - s->bi_buf = 0; - s->bi_valid = 0; - } else if (s->bi_valid >= 8) { - put_byte(s, (Byte)s->bi_buf); - s->bi_buf >>= 8; - s->bi_valid -= 8; - } -} - -/* =========================================================================== - * Flush the bit buffer and align the output on a byte boundary - */ -local void bi_windup(s) - deflate_state *s; -{ - if (s->bi_valid > 8) { - put_short(s, s->bi_buf); - } else if (s->bi_valid > 0) { - put_byte(s, (Byte)s->bi_buf); - } - s->bi_buf = 0; - s->bi_valid = 0; -#ifdef DEBUG - s->bits_sent = (s->bits_sent+7) & ~7; -#endif -} - -/* =========================================================================== - * Copy a stored block, storing first the length and its - * one's complement if requested. - */ -local void copy_block(s, buf, len, header) - deflate_state *s; - charf *buf; /* the input data */ - unsigned len; /* its length */ - int header; /* true if block header must be written */ -{ - bi_windup(s); /* align on byte boundary */ - s->last_eob_len = 8; /* enough lookahead for inflate */ - - if (header) { - put_short(s, (ush)len); - put_short(s, (ush)~len); -#ifdef DEBUG - s->bits_sent += 2*16; -#endif - } -#ifdef DEBUG - s->bits_sent += (ulg)len<<3; -#endif - while (len--) { - put_byte(s, *buf++); - } -} +/* trees.c -- output deflated data using Huffman coding + * Copyright (C) 1995-2005 Jean-loup Gailly + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* + * ALGORITHM + * + * The "deflation" process uses several Huffman trees. The more + * common source values are represented by shorter bit sequences. + * + * Each code tree is stored in a compressed form which is itself + * a Huffman encoding of the lengths of all the code strings (in + * ascending order by source values). The actual code strings are + * reconstructed from the lengths in the inflate process, as described + * in the deflate specification. + * + * REFERENCES + * + * Deutsch, L.P.,"'Deflate' Compressed Data Format Specification". + * Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc + * + * Storer, James A. + * Data Compression: Methods and Theory, pp. 49-50. + * Computer Science Press, 1988. ISBN 0-7167-8156-5. + * + * Sedgewick, R. + * Algorithms, p290. + * Addison-Wesley, 1983. ISBN 0-201-06672-6. + */ + +/* @(#) $Id: //poco/1.2/Foundation/src/trees.c#1 $ */ + +/* #define GEN_TREES_H */ + +#if defined(_MSC_VER) + #pragma warning(disable:4267) // conversion from ... possble loss of data +#endif + +#include "deflate.h" + +#ifdef DEBUG +# include +#endif + +/* =========================================================================== + * Constants + */ + +#define MAX_BL_BITS 7 +/* Bit length codes must not exceed MAX_BL_BITS bits */ + +#define END_BLOCK 256 +/* end of block literal code */ + +#define REP_3_6 16 +/* repeat previous bit length 3-6 times (2 bits of repeat count) */ + +#define REPZ_3_10 17 +/* repeat a zero length 3-10 times (3 bits of repeat count) */ + +#define REPZ_11_138 18 +/* repeat a zero length 11-138 times (7 bits of repeat count) */ + +local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */ + = {0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0}; + +local const int extra_dbits[D_CODES] /* extra bits for each distance code */ + = {0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13}; + +local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */ + = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7}; + +local const uch bl_order[BL_CODES] + = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15}; +/* The lengths of the bit length codes are sent in order of decreasing + * probability, to avoid transmitting the lengths for unused bit length codes. + */ + +#define Buf_size (8 * 2*sizeof(char)) +/* Number of bits used within bi_buf. (bi_buf might be implemented on + * more than 16 bits on some systems.) + */ + +/* =========================================================================== + * Local data. These are initialized only once. + */ + +#define DIST_CODE_LEN 512 /* see definition of array dist_code below */ + +#if defined(GEN_TREES_H) || !defined(STDC) +/* non ANSI compilers may not accept trees.h */ + +local ct_data static_ltree[L_CODES+2]; +/* The static literal tree. Since the bit lengths are imposed, there is no + * need for the L_CODES extra codes used during heap construction. However + * The codes 286 and 287 are needed to build a canonical tree (see _tr_init + * below). + */ + +local ct_data static_dtree[D_CODES]; +/* The static distance tree. (Actually a trivial tree since all codes use + * 5 bits.) + */ + +uch _dist_code[DIST_CODE_LEN]; +/* Distance codes. The first 256 values correspond to the distances + * 3 .. 258, the last 256 values correspond to the top 8 bits of + * the 15 bit distances. + */ + +uch _length_code[MAX_MATCH-MIN_MATCH+1]; +/* length code for each normalized match length (0 == MIN_MATCH) */ + +local int base_length[LENGTH_CODES]; +/* First normalized length for each code (0 = MIN_MATCH) */ + +local int base_dist[D_CODES]; +/* First normalized distance for each code (0 = distance of 1) */ + +#else +# include "trees.h" +#endif /* GEN_TREES_H */ + +struct static_tree_desc_s { + const ct_data *static_tree; /* static tree or NULL */ + const intf *extra_bits; /* extra bits for each code or NULL */ + int extra_base; /* base index for extra_bits */ + int elems; /* max number of elements in the tree */ + int max_length; /* max bit length for the codes */ +}; + +local static_tree_desc static_l_desc = +{static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS}; + +local static_tree_desc static_d_desc = +{static_dtree, extra_dbits, 0, D_CODES, MAX_BITS}; + +local static_tree_desc static_bl_desc = +{(const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS}; + +/* =========================================================================== + * Local (static) routines in this file. + */ + +local void tr_static_init OF((void)); +local void init_block OF((deflate_state *s)); +local void pqdownheap OF((deflate_state *s, ct_data *tree, int k)); +local void gen_bitlen OF((deflate_state *s, tree_desc *desc)); +local void gen_codes OF((ct_data *tree, int max_code, ushf *bl_count)); +local void build_tree OF((deflate_state *s, tree_desc *desc)); +local void scan_tree OF((deflate_state *s, ct_data *tree, int max_code)); +local void send_tree OF((deflate_state *s, ct_data *tree, int max_code)); +local int build_bl_tree OF((deflate_state *s)); +local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes, + int blcodes)); +local void compress_block OF((deflate_state *s, ct_data *ltree, + ct_data *dtree)); +local void set_data_type OF((deflate_state *s)); +local unsigned bi_reverse OF((unsigned value, int length)); +local void bi_windup OF((deflate_state *s)); +local void bi_flush OF((deflate_state *s)); +local void copy_block OF((deflate_state *s, charf *buf, unsigned len, + int header)); + +#ifdef GEN_TREES_H +local void gen_trees_header OF((void)); +#endif + +#ifndef DEBUG +# define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len) + /* Send a code of the given tree. c and tree must not have side effects */ + +#else /* DEBUG */ +# define send_code(s, c, tree) \ + { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \ + send_bits(s, tree[c].Code, tree[c].Len); } +#endif + +/* =========================================================================== + * Output a short LSB first on the stream. + * IN assertion: there is enough room in pendingBuf. + */ +#define put_short(s, w) { \ + put_byte(s, (uch)((w) & 0xff)); \ + put_byte(s, (uch)((ush)(w) >> 8)); \ +} + +/* =========================================================================== + * Send a value on a given number of bits. + * IN assertion: length <= 16 and value fits in length bits. + */ +#ifdef DEBUG +local void send_bits OF((deflate_state *s, int value, int length)); + +local void send_bits(s, value, length) + deflate_state *s; + int value; /* value to send */ + int length; /* number of bits */ +{ + Tracevv((stderr," l %2d v %4x ", length, value)); + Assert(length > 0 && length <= 15, "invalid length"); + s->bits_sent += (ulg)length; + + /* If not enough room in bi_buf, use (valid) bits from bi_buf and + * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid)) + * unused bits in value. + */ + if (s->bi_valid > (int)Buf_size - length) { + s->bi_buf |= (value << s->bi_valid); + put_short(s, s->bi_buf); + s->bi_buf = (ush)value >> (Buf_size - s->bi_valid); + s->bi_valid += length - Buf_size; + } else { + s->bi_buf |= value << s->bi_valid; + s->bi_valid += length; + } +} +#else /* !DEBUG */ + +#define send_bits(s, value, length) \ +{ int len = length;\ + if (s->bi_valid > (int)Buf_size - len) {\ + int val = value;\ + s->bi_buf |= (val << s->bi_valid);\ + put_short(s, s->bi_buf);\ + s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\ + s->bi_valid += len - Buf_size;\ + } else {\ + s->bi_buf |= (value) << s->bi_valid;\ + s->bi_valid += len;\ + }\ +} +#endif /* DEBUG */ + + +/* the arguments must not have side effects */ + +/* =========================================================================== + * Initialize the various 'constant' tables. + */ +local void tr_static_init() +{ +#if defined(GEN_TREES_H) || !defined(STDC) + static int static_init_done = 0; + int n; /* iterates over tree elements */ + int bits; /* bit counter */ + int length; /* length value */ + int code; /* code value */ + int dist; /* distance index */ + ush bl_count[MAX_BITS+1]; + /* number of codes at each bit length for an optimal tree */ + + if (static_init_done) return; + + /* For some embedded targets, global variables are not initialized: */ + static_l_desc.static_tree = static_ltree; + static_l_desc.extra_bits = extra_lbits; + static_d_desc.static_tree = static_dtree; + static_d_desc.extra_bits = extra_dbits; + static_bl_desc.extra_bits = extra_blbits; + + /* Initialize the mapping length (0..255) -> length code (0..28) */ + length = 0; + for (code = 0; code < LENGTH_CODES-1; code++) { + base_length[code] = length; + for (n = 0; n < (1< dist code (0..29) */ + dist = 0; + for (code = 0 ; code < 16; code++) { + base_dist[code] = dist; + for (n = 0; n < (1<>= 7; /* from now on, all distances are divided by 128 */ + for ( ; code < D_CODES; code++) { + base_dist[code] = dist << 7; + for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) { + _dist_code[256 + dist++] = (uch)code; + } + } + Assert (dist == 256, "tr_static_init: 256+dist != 512"); + + /* Construct the codes of the static literal tree */ + for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0; + n = 0; + while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++; + while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++; + while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++; + while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++; + /* Codes 286 and 287 do not exist, but we must include them in the + * tree construction to get a canonical Huffman tree (longest code + * all ones) + */ + gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count); + + /* The static distance tree is trivial: */ + for (n = 0; n < D_CODES; n++) { + static_dtree[n].Len = 5; + static_dtree[n].Code = bi_reverse((unsigned)n, 5); + } + static_init_done = 1; + +# ifdef GEN_TREES_H + gen_trees_header(); +# endif +#endif /* defined(GEN_TREES_H) || !defined(STDC) */ +} + +/* =========================================================================== + * Genererate the file trees.h describing the static trees. + */ +#ifdef GEN_TREES_H +# ifndef DEBUG +# include +# endif + +# define SEPARATOR(i, last, width) \ + ((i) == (last)? "\n};\n\n" : \ + ((i) % (width) == (width)-1 ? ",\n" : ", ")) + +void gen_trees_header() +{ + FILE *header = fopen("trees.h", "w"); + int i; + + Assert (header != NULL, "Can't open trees.h"); + fprintf(header, + "/* header created automatically with -DGEN_TREES_H */\n\n"); + + fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n"); + for (i = 0; i < L_CODES+2; i++) { + fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code, + static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5)); + } + + fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n"); + for (i = 0; i < D_CODES; i++) { + fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code, + static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5)); + } + + fprintf(header, "const uch _dist_code[DIST_CODE_LEN] = {\n"); + for (i = 0; i < DIST_CODE_LEN; i++) { + fprintf(header, "%2u%s", _dist_code[i], + SEPARATOR(i, DIST_CODE_LEN-1, 20)); + } + + fprintf(header, "const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {\n"); + for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) { + fprintf(header, "%2u%s", _length_code[i], + SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20)); + } + + fprintf(header, "local const int base_length[LENGTH_CODES] = {\n"); + for (i = 0; i < LENGTH_CODES; i++) { + fprintf(header, "%1u%s", base_length[i], + SEPARATOR(i, LENGTH_CODES-1, 20)); + } + + fprintf(header, "local const int base_dist[D_CODES] = {\n"); + for (i = 0; i < D_CODES; i++) { + fprintf(header, "%5u%s", base_dist[i], + SEPARATOR(i, D_CODES-1, 10)); + } + + fclose(header); +} +#endif /* GEN_TREES_H */ + +/* =========================================================================== + * Initialize the tree data structures for a new zlib stream. + */ +void _tr_init(s) + deflate_state *s; +{ + tr_static_init(); + + s->l_desc.dyn_tree = s->dyn_ltree; + s->l_desc.stat_desc = &static_l_desc; + + s->d_desc.dyn_tree = s->dyn_dtree; + s->d_desc.stat_desc = &static_d_desc; + + s->bl_desc.dyn_tree = s->bl_tree; + s->bl_desc.stat_desc = &static_bl_desc; + + s->bi_buf = 0; + s->bi_valid = 0; + s->last_eob_len = 8; /* enough lookahead for inflate */ +#ifdef DEBUG + s->compressed_len = 0L; + s->bits_sent = 0L; +#endif + + /* Initialize the first block of the first file: */ + init_block(s); +} + +/* =========================================================================== + * Initialize a new block. + */ +local void init_block(s) + deflate_state *s; +{ + int n; /* iterates over tree elements */ + + /* Initialize the trees. */ + for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0; + for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0; + for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0; + + s->dyn_ltree[END_BLOCK].Freq = 1; + s->opt_len = s->static_len = 0L; + s->last_lit = s->matches = 0; +} + +#define SMALLEST 1 +/* Index within the heap array of least frequent node in the Huffman tree */ + + +/* =========================================================================== + * Remove the smallest element from the heap and recreate the heap with + * one less element. Updates heap and heap_len. + */ +#define pqremove(s, tree, top) \ +{\ + top = s->heap[SMALLEST]; \ + s->heap[SMALLEST] = s->heap[s->heap_len--]; \ + pqdownheap(s, tree, SMALLEST); \ +} + +/* =========================================================================== + * Compares to subtrees, using the tree depth as tie breaker when + * the subtrees have equal frequency. This minimizes the worst case length. + */ +#define smaller(tree, n, m, depth) \ + (tree[n].Freq < tree[m].Freq || \ + (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m])) + +/* =========================================================================== + * Restore the heap property by moving down the tree starting at node k, + * exchanging a node with the smallest of its two sons if necessary, stopping + * when the heap property is re-established (each father smaller than its + * two sons). + */ +local void pqdownheap(s, tree, k) + deflate_state *s; + ct_data *tree; /* the tree to restore */ + int k; /* node to move down */ +{ + int v = s->heap[k]; + int j = k << 1; /* left son of k */ + while (j <= s->heap_len) { + /* Set j to the smallest of the two sons: */ + if (j < s->heap_len && + smaller(tree, s->heap[j+1], s->heap[j], s->depth)) { + j++; + } + /* Exit if v is smaller than both sons */ + if (smaller(tree, v, s->heap[j], s->depth)) break; + + /* Exchange v with the smallest son */ + s->heap[k] = s->heap[j]; k = j; + + /* And continue down the tree, setting j to the left son of k */ + j <<= 1; + } + s->heap[k] = v; +} + +/* =========================================================================== + * Compute the optimal bit lengths for a tree and update the total bit length + * for the current block. + * IN assertion: the fields freq and dad are set, heap[heap_max] and + * above are the tree nodes sorted by increasing frequency. + * OUT assertions: the field len is set to the optimal bit length, the + * array bl_count contains the frequencies for each bit length. + * The length opt_len is updated; static_len is also updated if stree is + * not null. + */ +local void gen_bitlen(s, desc) + deflate_state *s; + tree_desc *desc; /* the tree descriptor */ +{ + ct_data *tree = desc->dyn_tree; + int max_code = desc->max_code; + const ct_data *stree = desc->stat_desc->static_tree; + const intf *extra = desc->stat_desc->extra_bits; + int base = desc->stat_desc->extra_base; + int max_length = desc->stat_desc->max_length; + int h; /* heap index */ + int n, m; /* iterate over the tree elements */ + int bits; /* bit length */ + int xbits; /* extra bits */ + ush f; /* frequency */ + int overflow = 0; /* number of elements with bit length too large */ + + for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0; + + /* In a first pass, compute the optimal bit lengths (which may + * overflow in the case of the bit length tree). + */ + tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */ + + for (h = s->heap_max+1; h < HEAP_SIZE; h++) { + n = s->heap[h]; + bits = tree[tree[n].Dad].Len + 1; + if (bits > max_length) bits = max_length, overflow++; + tree[n].Len = (ush)bits; + /* We overwrite tree[n].Dad which is no longer needed */ + + if (n > max_code) continue; /* not a leaf node */ + + s->bl_count[bits]++; + xbits = 0; + if (n >= base) xbits = extra[n-base]; + f = tree[n].Freq; + s->opt_len += (ulg)f * (bits + xbits); + if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits); + } + if (overflow == 0) return; + + Trace((stderr,"\nbit length overflow\n")); + /* This happens for example on obj2 and pic of the Calgary corpus */ + + /* Find the first bit length which could increase: */ + do { + bits = max_length-1; + while (s->bl_count[bits] == 0) bits--; + s->bl_count[bits]--; /* move one leaf down the tree */ + s->bl_count[bits+1] += 2; /* move one overflow item as its brother */ + s->bl_count[max_length]--; + /* The brother of the overflow item also moves one step up, + * but this does not affect bl_count[max_length] + */ + overflow -= 2; + } while (overflow > 0); + + /* Now recompute all bit lengths, scanning in increasing frequency. + * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all + * lengths instead of fixing only the wrong ones. This idea is taken + * from 'ar' written by Haruhiko Okumura.) + */ + for (bits = max_length; bits != 0; bits--) { + n = s->bl_count[bits]; + while (n != 0) { + m = s->heap[--h]; + if (m > max_code) continue; + if ((unsigned) tree[m].Len != (unsigned) bits) { + Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits)); + s->opt_len += ((long)bits - (long)tree[m].Len) + *(long)tree[m].Freq; + tree[m].Len = (ush)bits; + } + n--; + } + } +} + +/* =========================================================================== + * Generate the codes for a given tree and bit counts (which need not be + * optimal). + * IN assertion: the array bl_count contains the bit length statistics for + * the given tree and the field len is set for all tree elements. + * OUT assertion: the field code is set for all tree elements of non + * zero code length. + */ +local void gen_codes (tree, max_code, bl_count) + ct_data *tree; /* the tree to decorate */ + int max_code; /* largest code with non zero frequency */ + ushf *bl_count; /* number of codes at each bit length */ +{ + ush next_code[MAX_BITS+1]; /* next code value for each bit length */ + ush code = 0; /* running code value */ + int bits; /* bit index */ + int n; /* code index */ + + /* The distribution counts are first used to generate the code values + * without bit reversal. + */ + for (bits = 1; bits <= MAX_BITS; bits++) { + next_code[bits] = code = (code + bl_count[bits-1]) << 1; + } + /* Check that the bit counts in bl_count are consistent. The last code + * must be all ones. + */ + Assert (code + bl_count[MAX_BITS]-1 == (1<dyn_tree; + const ct_data *stree = desc->stat_desc->static_tree; + int elems = desc->stat_desc->elems; + int n, m; /* iterate over heap elements */ + int max_code = -1; /* largest code with non zero frequency */ + int node; /* new node being created */ + + /* Construct the initial heap, with least frequent element in + * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. + * heap[0] is not used. + */ + s->heap_len = 0, s->heap_max = HEAP_SIZE; + + for (n = 0; n < elems; n++) { + if (tree[n].Freq != 0) { + s->heap[++(s->heap_len)] = max_code = n; + s->depth[n] = 0; + } else { + tree[n].Len = 0; + } + } + + /* The pkzip format requires that at least one distance code exists, + * and that at least one bit should be sent even if there is only one + * possible code. So to avoid special checks later on we force at least + * two codes of non zero frequency. + */ + while (s->heap_len < 2) { + node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0); + tree[node].Freq = 1; + s->depth[node] = 0; + s->opt_len--; if (stree) s->static_len -= stree[node].Len; + /* node is 0 or 1 so it does not have extra bits */ + } + desc->max_code = max_code; + + /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, + * establish sub-heaps of increasing lengths: + */ + for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n); + + /* Construct the Huffman tree by repeatedly combining the least two + * frequent nodes. + */ + node = elems; /* next internal node of the tree */ + do { + pqremove(s, tree, n); /* n = node of least frequency */ + m = s->heap[SMALLEST]; /* m = node of next least frequency */ + + s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */ + s->heap[--(s->heap_max)] = m; + + /* Create a new node father of n and m */ + tree[node].Freq = tree[n].Freq + tree[m].Freq; + s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ? + s->depth[n] : s->depth[m]) + 1); + tree[n].Dad = tree[m].Dad = (ush)node; +#ifdef DUMP_BL_TREE + if (tree == s->bl_tree) { + fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)", + node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq); + } +#endif + /* and insert the new node in the heap */ + s->heap[SMALLEST] = node++; + pqdownheap(s, tree, SMALLEST); + + } while (s->heap_len >= 2); + + s->heap[--(s->heap_max)] = s->heap[SMALLEST]; + + /* At this point, the fields freq and dad are set. We can now + * generate the bit lengths. + */ + gen_bitlen(s, (tree_desc *)desc); + + /* The field len is now set, we can generate the bit codes */ + gen_codes ((ct_data *)tree, max_code, s->bl_count); +} + +/* =========================================================================== + * Scan a literal or distance tree to determine the frequencies of the codes + * in the bit length tree. + */ +local void scan_tree (s, tree, max_code) + deflate_state *s; + ct_data *tree; /* the tree to be scanned */ + int max_code; /* and its largest code of non zero frequency */ +{ + int n; /* iterates over all tree elements */ + int prevlen = -1; /* last emitted length */ + int curlen; /* length of current code */ + int nextlen = tree[0].Len; /* length of next code */ + int count = 0; /* repeat count of the current code */ + int max_count = 7; /* max repeat count */ + int min_count = 4; /* min repeat count */ + + if (nextlen == 0) max_count = 138, min_count = 3; + tree[max_code+1].Len = (ush)0xffff; /* guard */ + + for (n = 0; n <= max_code; n++) { + curlen = nextlen; nextlen = tree[n+1].Len; + if (++count < max_count && curlen == nextlen) { + continue; + } else if (count < min_count) { + s->bl_tree[curlen].Freq += count; + } else if (curlen != 0) { + if (curlen != prevlen) s->bl_tree[curlen].Freq++; + s->bl_tree[REP_3_6].Freq++; + } else if (count <= 10) { + s->bl_tree[REPZ_3_10].Freq++; + } else { + s->bl_tree[REPZ_11_138].Freq++; + } + count = 0; prevlen = curlen; + if (nextlen == 0) { + max_count = 138, min_count = 3; + } else if (curlen == nextlen) { + max_count = 6, min_count = 3; + } else { + max_count = 7, min_count = 4; + } + } +} + +/* =========================================================================== + * Send a literal or distance tree in compressed form, using the codes in + * bl_tree. + */ +local void send_tree (s, tree, max_code) + deflate_state *s; + ct_data *tree; /* the tree to be scanned */ + int max_code; /* and its largest code of non zero frequency */ +{ + int n; /* iterates over all tree elements */ + int prevlen = -1; /* last emitted length */ + int curlen; /* length of current code */ + int nextlen = tree[0].Len; /* length of next code */ + int count = 0; /* repeat count of the current code */ + int max_count = 7; /* max repeat count */ + int min_count = 4; /* min repeat count */ + + /* tree[max_code+1].Len = -1; */ /* guard already set */ + if (nextlen == 0) max_count = 138, min_count = 3; + + for (n = 0; n <= max_code; n++) { + curlen = nextlen; nextlen = tree[n+1].Len; + if (++count < max_count && curlen == nextlen) { + continue; + } else if (count < min_count) { + do { send_code(s, curlen, s->bl_tree); } while (--count != 0); + + } else if (curlen != 0) { + if (curlen != prevlen) { + send_code(s, curlen, s->bl_tree); count--; + } + Assert(count >= 3 && count <= 6, " 3_6?"); + send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2); + + } else if (count <= 10) { + send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3); + + } else { + send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7); + } + count = 0; prevlen = curlen; + if (nextlen == 0) { + max_count = 138, min_count = 3; + } else if (curlen == nextlen) { + max_count = 6, min_count = 3; + } else { + max_count = 7, min_count = 4; + } + } +} + +/* =========================================================================== + * Construct the Huffman tree for the bit lengths and return the index in + * bl_order of the last bit length code to send. + */ +local int build_bl_tree(s) + deflate_state *s; +{ + int max_blindex; /* index of last bit length code of non zero freq */ + + /* Determine the bit length frequencies for literal and distance trees */ + scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code); + scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code); + + /* Build the bit length tree: */ + build_tree(s, (tree_desc *)(&(s->bl_desc))); + /* opt_len now includes the length of the tree representations, except + * the lengths of the bit lengths codes and the 5+5+4 bits for the counts. + */ + + /* Determine the number of bit length codes to send. The pkzip format + * requires that at least 4 bit length codes be sent. (appnote.txt says + * 3 but the actual value used is 4.) + */ + for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) { + if (s->bl_tree[bl_order[max_blindex]].Len != 0) break; + } + /* Update opt_len to include the bit length tree and counts */ + s->opt_len += 3*(max_blindex+1) + 5+5+4; + Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld", + s->opt_len, s->static_len)); + + return max_blindex; +} + +/* =========================================================================== + * Send the header for a block using dynamic Huffman trees: the counts, the + * lengths of the bit length codes, the literal tree and the distance tree. + * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. + */ +local void send_all_trees(s, lcodes, dcodes, blcodes) + deflate_state *s; + int lcodes, dcodes, blcodes; /* number of codes for each tree */ +{ + int rank; /* index in bl_order */ + + Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes"); + Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES, + "too many codes"); + Tracev((stderr, "\nbl counts: ")); + send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */ + send_bits(s, dcodes-1, 5); + send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */ + for (rank = 0; rank < blcodes; rank++) { + Tracev((stderr, "\nbl code %2d ", bl_order[rank])); + send_bits(s, s->bl_tree[bl_order[rank]].Len, 3); + } + Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent)); + + send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */ + Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent)); + + send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */ + Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent)); +} + +/* =========================================================================== + * Send a stored block + */ +void _tr_stored_block(s, buf, stored_len, eof) + deflate_state *s; + charf *buf; /* input block */ + ulg stored_len; /* length of input block */ + int eof; /* true if this is the last block for a file */ +{ + send_bits(s, (STORED_BLOCK<<1)+eof, 3); /* send block type */ +#ifdef DEBUG + s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L; + s->compressed_len += (stored_len + 4) << 3; +#endif + copy_block(s, buf, (unsigned)stored_len, 1); /* with header */ +} + +/* =========================================================================== + * Send one empty static block to give enough lookahead for inflate. + * This takes 10 bits, of which 7 may remain in the bit buffer. + * The current inflate code requires 9 bits of lookahead. If the + * last two codes for the previous block (real code plus EOB) were coded + * on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode + * the last real code. In this case we send two empty static blocks instead + * of one. (There are no problems if the previous block is stored or fixed.) + * To simplify the code, we assume the worst case of last real code encoded + * on one bit only. + */ +void _tr_align(s) + deflate_state *s; +{ + send_bits(s, STATIC_TREES<<1, 3); + send_code(s, END_BLOCK, static_ltree); +#ifdef DEBUG + s->compressed_len += 10L; /* 3 for block type, 7 for EOB */ +#endif + bi_flush(s); + /* Of the 10 bits for the empty block, we have already sent + * (10 - bi_valid) bits. The lookahead for the last real code (before + * the EOB of the previous block) was thus at least one plus the length + * of the EOB plus what we have just sent of the empty static block. + */ + if (1 + s->last_eob_len + 10 - s->bi_valid < 9) { + send_bits(s, STATIC_TREES<<1, 3); + send_code(s, END_BLOCK, static_ltree); +#ifdef DEBUG + s->compressed_len += 10L; +#endif + bi_flush(s); + } + s->last_eob_len = 7; +} + +/* =========================================================================== + * Determine the best encoding for the current block: dynamic trees, static + * trees or store, and output the encoded block to the zip file. + */ +void _tr_flush_block(s, buf, stored_len, eof) + deflate_state *s; + charf *buf; /* input block, or NULL if too old */ + ulg stored_len; /* length of input block */ + int eof; /* true if this is the last block for a file */ +{ + ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */ + int max_blindex = 0; /* index of last bit length code of non zero freq */ + + /* Build the Huffman trees unless a stored block is forced */ + if (s->level > 0) { + + /* Check if the file is binary or text */ + if (stored_len > 0 && s->strm->data_type == Z_UNKNOWN) + set_data_type(s); + + /* Construct the literal and distance trees */ + build_tree(s, (tree_desc *)(&(s->l_desc))); + Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len, + s->static_len)); + + build_tree(s, (tree_desc *)(&(s->d_desc))); + Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len, + s->static_len)); + /* At this point, opt_len and static_len are the total bit lengths of + * the compressed block data, excluding the tree representations. + */ + + /* Build the bit length tree for the above two trees, and get the index + * in bl_order of the last bit length code to send. + */ + max_blindex = build_bl_tree(s); + + /* Determine the best encoding. Compute the block lengths in bytes. */ + opt_lenb = (s->opt_len+3+7)>>3; + static_lenb = (s->static_len+3+7)>>3; + + Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ", + opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len, + s->last_lit)); + + if (static_lenb <= opt_lenb) opt_lenb = static_lenb; + + } else { + Assert(buf != (char*)0, "lost buf"); + opt_lenb = static_lenb = stored_len + 5; /* force a stored block */ + } + +#ifdef FORCE_STORED + if (buf != (char*)0) { /* force stored block */ +#else + if (stored_len+4 <= opt_lenb && buf != (char*)0) { + /* 4: two words for the lengths */ +#endif + /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE. + * Otherwise we can't have processed more than WSIZE input bytes since + * the last block flush, because compression would have been + * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to + * transform a block into a stored block. + */ + _tr_stored_block(s, buf, stored_len, eof); + +#ifdef FORCE_STATIC + } else if (static_lenb >= 0) { /* force static trees */ +#else + } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) { +#endif + send_bits(s, (STATIC_TREES<<1)+eof, 3); + compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree); +#ifdef DEBUG + s->compressed_len += 3 + s->static_len; +#endif + } else { + send_bits(s, (DYN_TREES<<1)+eof, 3); + send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1, + max_blindex+1); + compress_block(s, (ct_data *)s->dyn_ltree, (ct_data *)s->dyn_dtree); +#ifdef DEBUG + s->compressed_len += 3 + s->opt_len; +#endif + } + Assert (s->compressed_len == s->bits_sent, "bad compressed size"); + /* The above check is made mod 2^32, for files larger than 512 MB + * and uLong implemented on 32 bits. + */ + init_block(s); + + if (eof) { + bi_windup(s); +#ifdef DEBUG + s->compressed_len += 7; /* align on byte boundary */ +#endif + } + Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3, + s->compressed_len-7*eof)); +} + +/* =========================================================================== + * Save the match info and tally the frequency counts. Return true if + * the current block must be flushed. + */ +int _tr_tally (s, dist, lc) + deflate_state *s; + unsigned dist; /* distance of matched string */ + unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */ +{ + s->d_buf[s->last_lit] = (ush)dist; + s->l_buf[s->last_lit++] = (uch)lc; + if (dist == 0) { + /* lc is the unmatched char */ + s->dyn_ltree[lc].Freq++; + } else { + s->matches++; + /* Here, lc is the match length - MIN_MATCH */ + dist--; /* dist = match distance - 1 */ + Assert((ush)dist < (ush)MAX_DIST(s) && + (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) && + (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match"); + + s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++; + s->dyn_dtree[d_code(dist)].Freq++; + } + +#ifdef TRUNCATE_BLOCK + /* Try to guess if it is profitable to stop the current block here */ + if ((s->last_lit & 0x1fff) == 0 && s->level > 2) { + /* Compute an upper bound for the compressed length */ + ulg out_length = (ulg)s->last_lit*8L; + ulg in_length = (ulg)((long)s->strstart - s->block_start); + int dcode; + for (dcode = 0; dcode < D_CODES; dcode++) { + out_length += (ulg)s->dyn_dtree[dcode].Freq * + (5L+extra_dbits[dcode]); + } + out_length >>= 3; + Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ", + s->last_lit, in_length, out_length, + 100L - out_length*100L/in_length)); + if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1; + } +#endif + return (s->last_lit == s->lit_bufsize-1); + /* We avoid equality with lit_bufsize because of wraparound at 64K + * on 16 bit machines and because stored blocks are restricted to + * 64K-1 bytes. + */ +} + +/* =========================================================================== + * Send the block data compressed using the given Huffman trees + */ +local void compress_block(s, ltree, dtree) + deflate_state *s; + ct_data *ltree; /* literal tree */ + ct_data *dtree; /* distance tree */ +{ + unsigned dist; /* distance of matched string */ + int lc; /* match length or unmatched char (if dist == 0) */ + unsigned lx = 0; /* running index in l_buf */ + unsigned code; /* the code to send */ + int extra; /* number of extra bits to send */ + + if (s->last_lit != 0) do { + dist = s->d_buf[lx]; + lc = s->l_buf[lx++]; + if (dist == 0) { + send_code(s, lc, ltree); /* send a literal byte */ + Tracecv(isgraph(lc), (stderr," '%c' ", lc)); + } else { + /* Here, lc is the match length - MIN_MATCH */ + code = _length_code[lc]; + send_code(s, code+LITERALS+1, ltree); /* send the length code */ + extra = extra_lbits[code]; + if (extra != 0) { + lc -= base_length[code]; + send_bits(s, lc, extra); /* send the extra length bits */ + } + dist--; /* dist is now the match distance - 1 */ + code = d_code(dist); + Assert (code < D_CODES, "bad d_code"); + + send_code(s, code, dtree); /* send the distance code */ + extra = extra_dbits[code]; + if (extra != 0) { + dist -= base_dist[code]; + send_bits(s, dist, extra); /* send the extra distance bits */ + } + } /* literal or match pair ? */ + + /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */ + Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx, + "pendingBuf overflow"); + + } while (lx < s->last_lit); + + send_code(s, END_BLOCK, ltree); + s->last_eob_len = ltree[END_BLOCK].Len; +} + +/* =========================================================================== + * Set the data type to BINARY or TEXT, using a crude approximation: + * set it to Z_TEXT if all symbols are either printable characters (33 to 255) + * or white spaces (9 to 13, or 32); or set it to Z_BINARY otherwise. + * IN assertion: the fields Freq of dyn_ltree are set. + */ +local void set_data_type(s) + deflate_state *s; +{ + int n; + + for (n = 0; n < 9; n++) + if (s->dyn_ltree[n].Freq != 0) + break; + if (n == 9) + for (n = 14; n < 32; n++) + if (s->dyn_ltree[n].Freq != 0) + break; + s->strm->data_type = (n == 32) ? Z_TEXT : Z_BINARY; +} + +/* =========================================================================== + * Reverse the first len bits of a code, using straightforward code (a faster + * method would use a table) + * IN assertion: 1 <= len <= 15 + */ +local unsigned bi_reverse(code, len) + unsigned code; /* the value to invert */ + int len; /* its bit length */ +{ + register unsigned res = 0; + do { + res |= code & 1; + code >>= 1, res <<= 1; + } while (--len > 0); + return res >> 1; +} + +/* =========================================================================== + * Flush the bit buffer, keeping at most 7 bits in it. + */ +local void bi_flush(s) + deflate_state *s; +{ + if (s->bi_valid == 16) { + put_short(s, s->bi_buf); + s->bi_buf = 0; + s->bi_valid = 0; + } else if (s->bi_valid >= 8) { + put_byte(s, (Byte)s->bi_buf); + s->bi_buf >>= 8; + s->bi_valid -= 8; + } +} + +/* =========================================================================== + * Flush the bit buffer and align the output on a byte boundary + */ +local void bi_windup(s) + deflate_state *s; +{ + if (s->bi_valid > 8) { + put_short(s, s->bi_buf); + } else if (s->bi_valid > 0) { + put_byte(s, (Byte)s->bi_buf); + } + s->bi_buf = 0; + s->bi_valid = 0; +#ifdef DEBUG + s->bits_sent = (s->bits_sent+7) & ~7; +#endif +} + +/* =========================================================================== + * Copy a stored block, storing first the length and its + * one's complement if requested. + */ +local void copy_block(s, buf, len, header) + deflate_state *s; + charf *buf; /* the input data */ + unsigned len; /* its length */ + int header; /* true if block header must be written */ +{ + bi_windup(s); /* align on byte boundary */ + s->last_eob_len = 8; /* enough lookahead for inflate */ + + if (header) { + put_short(s, (ush)len); + put_short(s, (ush)~len); +#ifdef DEBUG + s->bits_sent += 2*16; +#endif + } +#ifdef DEBUG + s->bits_sent += (ulg)len<<3; +#endif + while (len--) { + put_byte(s, *buf++); + } +} diff --git a/Foundation/src/trees.h b/Foundation/src/trees.h index 1ca868b84..72facf900 100644 --- a/Foundation/src/trees.h +++ b/Foundation/src/trees.h @@ -1,128 +1,128 @@ -/* header created automatically with -DGEN_TREES_H */ - -local const ct_data static_ltree[L_CODES+2] = { -{{ 12},{ 8}}, {{140},{ 8}}, {{ 76},{ 8}}, {{204},{ 8}}, {{ 44},{ 8}}, -{{172},{ 8}}, {{108},{ 8}}, {{236},{ 8}}, {{ 28},{ 8}}, {{156},{ 8}}, -{{ 92},{ 8}}, {{220},{ 8}}, {{ 60},{ 8}}, {{188},{ 8}}, {{124},{ 8}}, -{{252},{ 8}}, {{ 2},{ 8}}, {{130},{ 8}}, {{ 66},{ 8}}, {{194},{ 8}}, -{{ 34},{ 8}}, {{162},{ 8}}, {{ 98},{ 8}}, {{226},{ 8}}, {{ 18},{ 8}}, -{{146},{ 8}}, {{ 82},{ 8}}, {{210},{ 8}}, {{ 50},{ 8}}, {{178},{ 8}}, -{{114},{ 8}}, {{242},{ 8}}, {{ 10},{ 8}}, {{138},{ 8}}, {{ 74},{ 8}}, -{{202},{ 8}}, {{ 42},{ 8}}, {{170},{ 8}}, {{106},{ 8}}, {{234},{ 8}}, -{{ 26},{ 8}}, {{154},{ 8}}, {{ 90},{ 8}}, {{218},{ 8}}, {{ 58},{ 8}}, -{{186},{ 8}}, {{122},{ 8}}, {{250},{ 8}}, {{ 6},{ 8}}, {{134},{ 8}}, -{{ 70},{ 8}}, {{198},{ 8}}, {{ 38},{ 8}}, {{166},{ 8}}, {{102},{ 8}}, -{{230},{ 8}}, {{ 22},{ 8}}, {{150},{ 8}}, {{ 86},{ 8}}, {{214},{ 8}}, -{{ 54},{ 8}}, {{182},{ 8}}, {{118},{ 8}}, {{246},{ 8}}, {{ 14},{ 8}}, -{{142},{ 8}}, {{ 78},{ 8}}, {{206},{ 8}}, {{ 46},{ 8}}, {{174},{ 8}}, -{{110},{ 8}}, {{238},{ 8}}, {{ 30},{ 8}}, {{158},{ 8}}, {{ 94},{ 8}}, -{{222},{ 8}}, {{ 62},{ 8}}, {{190},{ 8}}, {{126},{ 8}}, {{254},{ 8}}, -{{ 1},{ 8}}, {{129},{ 8}}, {{ 65},{ 8}}, {{193},{ 8}}, {{ 33},{ 8}}, -{{161},{ 8}}, {{ 97},{ 8}}, {{225},{ 8}}, {{ 17},{ 8}}, {{145},{ 8}}, -{{ 81},{ 8}}, {{209},{ 8}}, {{ 49},{ 8}}, {{177},{ 8}}, {{113},{ 8}}, -{{241},{ 8}}, {{ 9},{ 8}}, {{137},{ 8}}, {{ 73},{ 8}}, {{201},{ 8}}, -{{ 41},{ 8}}, {{169},{ 8}}, {{105},{ 8}}, {{233},{ 8}}, {{ 25},{ 8}}, -{{153},{ 8}}, {{ 89},{ 8}}, {{217},{ 8}}, {{ 57},{ 8}}, {{185},{ 8}}, -{{121},{ 8}}, {{249},{ 8}}, {{ 5},{ 8}}, {{133},{ 8}}, {{ 69},{ 8}}, -{{197},{ 8}}, {{ 37},{ 8}}, {{165},{ 8}}, {{101},{ 8}}, {{229},{ 8}}, -{{ 21},{ 8}}, {{149},{ 8}}, {{ 85},{ 8}}, {{213},{ 8}}, {{ 53},{ 8}}, -{{181},{ 8}}, {{117},{ 8}}, {{245},{ 8}}, {{ 13},{ 8}}, {{141},{ 8}}, -{{ 77},{ 8}}, {{205},{ 8}}, {{ 45},{ 8}}, {{173},{ 8}}, {{109},{ 8}}, -{{237},{ 8}}, {{ 29},{ 8}}, {{157},{ 8}}, {{ 93},{ 8}}, {{221},{ 8}}, -{{ 61},{ 8}}, {{189},{ 8}}, {{125},{ 8}}, {{253},{ 8}}, {{ 19},{ 9}}, -{{275},{ 9}}, {{147},{ 9}}, {{403},{ 9}}, {{ 83},{ 9}}, {{339},{ 9}}, -{{211},{ 9}}, {{467},{ 9}}, {{ 51},{ 9}}, {{307},{ 9}}, {{179},{ 9}}, -{{435},{ 9}}, {{115},{ 9}}, {{371},{ 9}}, {{243},{ 9}}, {{499},{ 9}}, -{{ 11},{ 9}}, {{267},{ 9}}, {{139},{ 9}}, {{395},{ 9}}, {{ 75},{ 9}}, -{{331},{ 9}}, {{203},{ 9}}, {{459},{ 9}}, {{ 43},{ 9}}, {{299},{ 9}}, -{{171},{ 9}}, {{427},{ 9}}, {{107},{ 9}}, {{363},{ 9}}, {{235},{ 9}}, -{{491},{ 9}}, {{ 27},{ 9}}, {{283},{ 9}}, {{155},{ 9}}, {{411},{ 9}}, -{{ 91},{ 9}}, {{347},{ 9}}, {{219},{ 9}}, {{475},{ 9}}, {{ 59},{ 9}}, -{{315},{ 9}}, {{187},{ 9}}, {{443},{ 9}}, {{123},{ 9}}, {{379},{ 9}}, -{{251},{ 9}}, {{507},{ 9}}, {{ 7},{ 9}}, {{263},{ 9}}, {{135},{ 9}}, -{{391},{ 9}}, {{ 71},{ 9}}, {{327},{ 9}}, {{199},{ 9}}, {{455},{ 9}}, -{{ 39},{ 9}}, {{295},{ 9}}, {{167},{ 9}}, {{423},{ 9}}, {{103},{ 9}}, -{{359},{ 9}}, {{231},{ 9}}, {{487},{ 9}}, {{ 23},{ 9}}, {{279},{ 9}}, -{{151},{ 9}}, {{407},{ 9}}, {{ 87},{ 9}}, {{343},{ 9}}, {{215},{ 9}}, -{{471},{ 9}}, {{ 55},{ 9}}, {{311},{ 9}}, {{183},{ 9}}, {{439},{ 9}}, -{{119},{ 9}}, {{375},{ 9}}, {{247},{ 9}}, {{503},{ 9}}, {{ 15},{ 9}}, -{{271},{ 9}}, {{143},{ 9}}, {{399},{ 9}}, {{ 79},{ 9}}, {{335},{ 9}}, -{{207},{ 9}}, {{463},{ 9}}, {{ 47},{ 9}}, {{303},{ 9}}, {{175},{ 9}}, -{{431},{ 9}}, {{111},{ 9}}, {{367},{ 9}}, {{239},{ 9}}, {{495},{ 9}}, -{{ 31},{ 9}}, {{287},{ 9}}, {{159},{ 9}}, {{415},{ 9}}, {{ 95},{ 9}}, -{{351},{ 9}}, {{223},{ 9}}, {{479},{ 9}}, {{ 63},{ 9}}, {{319},{ 9}}, -{{191},{ 9}}, {{447},{ 9}}, {{127},{ 9}}, {{383},{ 9}}, {{255},{ 9}}, -{{511},{ 9}}, {{ 0},{ 7}}, {{ 64},{ 7}}, {{ 32},{ 7}}, {{ 96},{ 7}}, -{{ 16},{ 7}}, {{ 80},{ 7}}, {{ 48},{ 7}}, {{112},{ 7}}, {{ 8},{ 7}}, -{{ 72},{ 7}}, {{ 40},{ 7}}, {{104},{ 7}}, {{ 24},{ 7}}, {{ 88},{ 7}}, -{{ 56},{ 7}}, {{120},{ 7}}, {{ 4},{ 7}}, {{ 68},{ 7}}, {{ 36},{ 7}}, -{{100},{ 7}}, {{ 20},{ 7}}, {{ 84},{ 7}}, {{ 52},{ 7}}, {{116},{ 7}}, -{{ 3},{ 8}}, {{131},{ 8}}, {{ 67},{ 8}}, {{195},{ 8}}, {{ 35},{ 8}}, -{{163},{ 8}}, {{ 99},{ 8}}, {{227},{ 8}} -}; - -local const ct_data static_dtree[D_CODES] = { -{{ 0},{ 5}}, {{16},{ 5}}, {{ 8},{ 5}}, {{24},{ 5}}, {{ 4},{ 5}}, -{{20},{ 5}}, {{12},{ 5}}, {{28},{ 5}}, {{ 2},{ 5}}, {{18},{ 5}}, -{{10},{ 5}}, {{26},{ 5}}, {{ 6},{ 5}}, {{22},{ 5}}, {{14},{ 5}}, -{{30},{ 5}}, {{ 1},{ 5}}, {{17},{ 5}}, {{ 9},{ 5}}, {{25},{ 5}}, -{{ 5},{ 5}}, {{21},{ 5}}, {{13},{ 5}}, {{29},{ 5}}, {{ 3},{ 5}}, -{{19},{ 5}}, {{11},{ 5}}, {{27},{ 5}}, {{ 7},{ 5}}, {{23},{ 5}} -}; - -const uch _dist_code[DIST_CODE_LEN] = { - 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, - 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, -10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, -11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, -12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, -13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, -13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, -14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, -14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, -14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15, -15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, -15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, -15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17, -18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22, -23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, -24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, -26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, -26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, -27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, -27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, -28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, -28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, -28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, -29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, -29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, -29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29 -}; - -const uch _length_code[MAX_MATCH-MIN_MATCH+1]= { - 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12, -13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, -17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19, -19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, -21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22, -22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23, -23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, -24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, -25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, -25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26, -26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, -26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, -27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28 -}; - -local const int base_length[LENGTH_CODES] = { -0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56, -64, 80, 96, 112, 128, 160, 192, 224, 0 -}; - -local const int base_dist[D_CODES] = { - 0, 1, 2, 3, 4, 6, 8, 12, 16, 24, - 32, 48, 64, 96, 128, 192, 256, 384, 512, 768, - 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576 -}; - +/* header created automatically with -DGEN_TREES_H */ + +local const ct_data static_ltree[L_CODES+2] = { +{{ 12},{ 8}}, {{140},{ 8}}, {{ 76},{ 8}}, {{204},{ 8}}, {{ 44},{ 8}}, +{{172},{ 8}}, {{108},{ 8}}, {{236},{ 8}}, {{ 28},{ 8}}, {{156},{ 8}}, +{{ 92},{ 8}}, {{220},{ 8}}, {{ 60},{ 8}}, {{188},{ 8}}, {{124},{ 8}}, +{{252},{ 8}}, {{ 2},{ 8}}, {{130},{ 8}}, {{ 66},{ 8}}, {{194},{ 8}}, +{{ 34},{ 8}}, {{162},{ 8}}, {{ 98},{ 8}}, {{226},{ 8}}, {{ 18},{ 8}}, +{{146},{ 8}}, {{ 82},{ 8}}, {{210},{ 8}}, {{ 50},{ 8}}, {{178},{ 8}}, +{{114},{ 8}}, {{242},{ 8}}, {{ 10},{ 8}}, {{138},{ 8}}, {{ 74},{ 8}}, +{{202},{ 8}}, {{ 42},{ 8}}, {{170},{ 8}}, {{106},{ 8}}, {{234},{ 8}}, +{{ 26},{ 8}}, {{154},{ 8}}, {{ 90},{ 8}}, {{218},{ 8}}, {{ 58},{ 8}}, +{{186},{ 8}}, {{122},{ 8}}, {{250},{ 8}}, {{ 6},{ 8}}, {{134},{ 8}}, +{{ 70},{ 8}}, {{198},{ 8}}, {{ 38},{ 8}}, {{166},{ 8}}, {{102},{ 8}}, +{{230},{ 8}}, {{ 22},{ 8}}, {{150},{ 8}}, {{ 86},{ 8}}, {{214},{ 8}}, +{{ 54},{ 8}}, {{182},{ 8}}, {{118},{ 8}}, {{246},{ 8}}, {{ 14},{ 8}}, +{{142},{ 8}}, {{ 78},{ 8}}, {{206},{ 8}}, {{ 46},{ 8}}, {{174},{ 8}}, +{{110},{ 8}}, {{238},{ 8}}, {{ 30},{ 8}}, {{158},{ 8}}, {{ 94},{ 8}}, +{{222},{ 8}}, {{ 62},{ 8}}, {{190},{ 8}}, {{126},{ 8}}, {{254},{ 8}}, +{{ 1},{ 8}}, {{129},{ 8}}, {{ 65},{ 8}}, {{193},{ 8}}, {{ 33},{ 8}}, +{{161},{ 8}}, {{ 97},{ 8}}, {{225},{ 8}}, {{ 17},{ 8}}, {{145},{ 8}}, +{{ 81},{ 8}}, {{209},{ 8}}, {{ 49},{ 8}}, {{177},{ 8}}, {{113},{ 8}}, +{{241},{ 8}}, {{ 9},{ 8}}, {{137},{ 8}}, {{ 73},{ 8}}, {{201},{ 8}}, +{{ 41},{ 8}}, {{169},{ 8}}, {{105},{ 8}}, {{233},{ 8}}, {{ 25},{ 8}}, +{{153},{ 8}}, {{ 89},{ 8}}, {{217},{ 8}}, {{ 57},{ 8}}, {{185},{ 8}}, +{{121},{ 8}}, {{249},{ 8}}, {{ 5},{ 8}}, {{133},{ 8}}, {{ 69},{ 8}}, +{{197},{ 8}}, {{ 37},{ 8}}, {{165},{ 8}}, {{101},{ 8}}, {{229},{ 8}}, +{{ 21},{ 8}}, {{149},{ 8}}, {{ 85},{ 8}}, {{213},{ 8}}, {{ 53},{ 8}}, +{{181},{ 8}}, {{117},{ 8}}, {{245},{ 8}}, {{ 13},{ 8}}, {{141},{ 8}}, +{{ 77},{ 8}}, {{205},{ 8}}, {{ 45},{ 8}}, {{173},{ 8}}, {{109},{ 8}}, +{{237},{ 8}}, {{ 29},{ 8}}, {{157},{ 8}}, {{ 93},{ 8}}, {{221},{ 8}}, +{{ 61},{ 8}}, {{189},{ 8}}, {{125},{ 8}}, {{253},{ 8}}, {{ 19},{ 9}}, +{{275},{ 9}}, {{147},{ 9}}, {{403},{ 9}}, {{ 83},{ 9}}, {{339},{ 9}}, +{{211},{ 9}}, {{467},{ 9}}, {{ 51},{ 9}}, {{307},{ 9}}, {{179},{ 9}}, +{{435},{ 9}}, {{115},{ 9}}, {{371},{ 9}}, {{243},{ 9}}, {{499},{ 9}}, +{{ 11},{ 9}}, {{267},{ 9}}, {{139},{ 9}}, {{395},{ 9}}, {{ 75},{ 9}}, +{{331},{ 9}}, {{203},{ 9}}, {{459},{ 9}}, {{ 43},{ 9}}, {{299},{ 9}}, +{{171},{ 9}}, {{427},{ 9}}, {{107},{ 9}}, {{363},{ 9}}, {{235},{ 9}}, +{{491},{ 9}}, {{ 27},{ 9}}, {{283},{ 9}}, {{155},{ 9}}, {{411},{ 9}}, +{{ 91},{ 9}}, {{347},{ 9}}, {{219},{ 9}}, {{475},{ 9}}, {{ 59},{ 9}}, +{{315},{ 9}}, {{187},{ 9}}, {{443},{ 9}}, {{123},{ 9}}, {{379},{ 9}}, +{{251},{ 9}}, {{507},{ 9}}, {{ 7},{ 9}}, {{263},{ 9}}, {{135},{ 9}}, +{{391},{ 9}}, {{ 71},{ 9}}, {{327},{ 9}}, {{199},{ 9}}, {{455},{ 9}}, +{{ 39},{ 9}}, {{295},{ 9}}, {{167},{ 9}}, {{423},{ 9}}, {{103},{ 9}}, +{{359},{ 9}}, {{231},{ 9}}, {{487},{ 9}}, {{ 23},{ 9}}, {{279},{ 9}}, +{{151},{ 9}}, {{407},{ 9}}, {{ 87},{ 9}}, {{343},{ 9}}, {{215},{ 9}}, +{{471},{ 9}}, {{ 55},{ 9}}, {{311},{ 9}}, {{183},{ 9}}, {{439},{ 9}}, +{{119},{ 9}}, {{375},{ 9}}, {{247},{ 9}}, {{503},{ 9}}, {{ 15},{ 9}}, +{{271},{ 9}}, {{143},{ 9}}, {{399},{ 9}}, {{ 79},{ 9}}, {{335},{ 9}}, +{{207},{ 9}}, {{463},{ 9}}, {{ 47},{ 9}}, {{303},{ 9}}, {{175},{ 9}}, +{{431},{ 9}}, {{111},{ 9}}, {{367},{ 9}}, {{239},{ 9}}, {{495},{ 9}}, +{{ 31},{ 9}}, {{287},{ 9}}, {{159},{ 9}}, {{415},{ 9}}, {{ 95},{ 9}}, +{{351},{ 9}}, {{223},{ 9}}, {{479},{ 9}}, {{ 63},{ 9}}, {{319},{ 9}}, +{{191},{ 9}}, {{447},{ 9}}, {{127},{ 9}}, {{383},{ 9}}, {{255},{ 9}}, +{{511},{ 9}}, {{ 0},{ 7}}, {{ 64},{ 7}}, {{ 32},{ 7}}, {{ 96},{ 7}}, +{{ 16},{ 7}}, {{ 80},{ 7}}, {{ 48},{ 7}}, {{112},{ 7}}, {{ 8},{ 7}}, +{{ 72},{ 7}}, {{ 40},{ 7}}, {{104},{ 7}}, {{ 24},{ 7}}, {{ 88},{ 7}}, +{{ 56},{ 7}}, {{120},{ 7}}, {{ 4},{ 7}}, {{ 68},{ 7}}, {{ 36},{ 7}}, +{{100},{ 7}}, {{ 20},{ 7}}, {{ 84},{ 7}}, {{ 52},{ 7}}, {{116},{ 7}}, +{{ 3},{ 8}}, {{131},{ 8}}, {{ 67},{ 8}}, {{195},{ 8}}, {{ 35},{ 8}}, +{{163},{ 8}}, {{ 99},{ 8}}, {{227},{ 8}} +}; + +local const ct_data static_dtree[D_CODES] = { +{{ 0},{ 5}}, {{16},{ 5}}, {{ 8},{ 5}}, {{24},{ 5}}, {{ 4},{ 5}}, +{{20},{ 5}}, {{12},{ 5}}, {{28},{ 5}}, {{ 2},{ 5}}, {{18},{ 5}}, +{{10},{ 5}}, {{26},{ 5}}, {{ 6},{ 5}}, {{22},{ 5}}, {{14},{ 5}}, +{{30},{ 5}}, {{ 1},{ 5}}, {{17},{ 5}}, {{ 9},{ 5}}, {{25},{ 5}}, +{{ 5},{ 5}}, {{21},{ 5}}, {{13},{ 5}}, {{29},{ 5}}, {{ 3},{ 5}}, +{{19},{ 5}}, {{11},{ 5}}, {{27},{ 5}}, {{ 7},{ 5}}, {{23},{ 5}} +}; + +const uch _dist_code[DIST_CODE_LEN] = { + 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, + 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, +10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, +11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, +12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, +13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, +13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, +14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, +14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, +14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15, +15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, +15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, +15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17, +18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22, +23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, +24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, +26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, +26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, +27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, +27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, +28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, +28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, +28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, +29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, +29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, +29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29 +}; + +const uch _length_code[MAX_MATCH-MIN_MATCH+1]= { + 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12, +13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, +17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19, +19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, +21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22, +22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23, +23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, +24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, +25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, +25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26, +26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, +26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, +27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28 +}; + +local const int base_length[LENGTH_CODES] = { +0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56, +64, 80, 96, 112, 128, 160, 192, 224, 0 +}; + +local const int base_dist[D_CODES] = { + 0, 1, 2, 3, 4, 6, 8, 12, 16, 24, + 32, 48, 64, 96, 128, 192, 256, 384, 512, 768, + 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576 +}; + diff --git a/Foundation/src/zconf.h b/Foundation/src/zconf.h index 0a98d644d..313a5070d 100644 --- a/Foundation/src/zconf.h +++ b/Foundation/src/zconf.h @@ -1,332 +1,332 @@ -/* zconf.h -- configuration of the zlib compression library - * Copyright (C) 1995-2005 Jean-loup Gailly. - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -/* @(#) $Id: //poco/1.2/Foundation/src/zconf.h#1 $ */ - -#ifndef ZCONF_H -#define ZCONF_H - -/* - * If you *really* need a unique prefix for all types and library functions, - * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it. - */ -#ifdef Z_PREFIX -# define deflateInit_ z_deflateInit_ -# define deflate z_deflate -# define deflateEnd z_deflateEnd -# define inflateInit_ z_inflateInit_ -# define inflate z_inflate -# define inflateEnd z_inflateEnd -# define deflateInit2_ z_deflateInit2_ -# define deflateSetDictionary z_deflateSetDictionary -# define deflateCopy z_deflateCopy -# define deflateReset z_deflateReset -# define deflateParams z_deflateParams -# define deflateBound z_deflateBound -# define deflatePrime z_deflatePrime -# define inflateInit2_ z_inflateInit2_ -# define inflateSetDictionary z_inflateSetDictionary -# define inflateSync z_inflateSync -# define inflateSyncPoint z_inflateSyncPoint -# define inflateCopy z_inflateCopy -# define inflateReset z_inflateReset -# define inflateBack z_inflateBack -# define inflateBackEnd z_inflateBackEnd -# define compress z_compress -# define compress2 z_compress2 -# define compressBound z_compressBound -# define uncompress z_uncompress -# define adler32 z_adler32 -# define crc32 z_crc32 -# define get_crc_table z_get_crc_table -# define zError z_zError - -# define alloc_func z_alloc_func -# define free_func z_free_func -# define in_func z_in_func -# define out_func z_out_func -# define Byte z_Byte -# define uInt z_uInt -# define uLong z_uLong -# define Bytef z_Bytef -# define charf z_charf -# define intf z_intf -# define uIntf z_uIntf -# define uLongf z_uLongf -# define voidpf z_voidpf -# define voidp z_voidp -#endif - -#if defined(__MSDOS__) && !defined(MSDOS) -# define MSDOS -#endif -#if (defined(OS_2) || defined(__OS2__)) && !defined(OS2) -# define OS2 -#endif -#if defined(_WINDOWS) && !defined(WINDOWS) -# define WINDOWS -#endif -#if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__) -# ifndef WIN32 -# define WIN32 -# endif -#endif -#if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32) -# if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__) -# ifndef SYS16BIT -# define SYS16BIT -# endif -# endif -#endif - -/* - * Compile with -DMAXSEG_64K if the alloc function cannot allocate more - * than 64k bytes at a time (needed on systems with 16-bit int). - */ -#ifdef SYS16BIT -# define MAXSEG_64K -#endif -#ifdef MSDOS -# define UNALIGNED_OK -#endif - -#ifdef __STDC_VERSION__ -# ifndef STDC -# define STDC -# endif -# if __STDC_VERSION__ >= 199901L -# ifndef STDC99 -# define STDC99 -# endif -# endif -#endif -#if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus)) -# define STDC -#endif -#if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__)) -# define STDC -#endif -#if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32)) -# define STDC -#endif -#if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__)) -# define STDC -#endif - -#if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */ -# define STDC -#endif - -#ifndef STDC -# ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */ -# define const /* note: need a more gentle solution here */ -# endif -#endif - -/* Some Mac compilers merge all .h files incorrectly: */ -#if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__) -# define NO_DUMMY_DECL -#endif - -/* Maximum value for memLevel in deflateInit2 */ -#ifndef MAX_MEM_LEVEL -# ifdef MAXSEG_64K -# define MAX_MEM_LEVEL 8 -# else -# define MAX_MEM_LEVEL 9 -# endif -#endif - -/* Maximum value for windowBits in deflateInit2 and inflateInit2. - * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files - * created by gzip. (Files created by minigzip can still be extracted by - * gzip.) - */ -#ifndef MAX_WBITS -# define MAX_WBITS 15 /* 32K LZ77 window */ -#endif - -/* The memory requirements for deflate are (in bytes): - (1 << (windowBits+2)) + (1 << (memLevel+9)) - that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values) - plus a few kilobytes for small objects. For example, if you want to reduce - the default memory requirements from 256K to 128K, compile with - make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7" - Of course this will generally degrade compression (there's no free lunch). - - The memory requirements for inflate are (in bytes) 1 << windowBits - that is, 32K for windowBits=15 (default value) plus a few kilobytes - for small objects. -*/ - - /* Type declarations */ - -#ifndef OF /* function prototypes */ -# ifdef STDC -# define OF(args) args -# else -# define OF(args) () -# endif -#endif - -/* The following definitions for FAR are needed only for MSDOS mixed - * model programming (small or medium model with some far allocations). - * This was tested only with MSC; for other MSDOS compilers you may have - * to define NO_MEMCPY in zutil.h. If you don't need the mixed model, - * just define FAR to be empty. - */ -#ifdef SYS16BIT -# if defined(M_I86SM) || defined(M_I86MM) - /* MSC small or medium model */ -# define SMALL_MEDIUM -# ifdef _MSC_VER -# define FAR _far -# else -# define FAR far -# endif -# endif -# if (defined(__SMALL__) || defined(__MEDIUM__)) - /* Turbo C small or medium model */ -# define SMALL_MEDIUM -# ifdef __BORLANDC__ -# define FAR _far -# else -# define FAR far -# endif -# endif -#endif - -#if defined(WINDOWS) || defined(WIN32) - /* If building or using zlib as a DLL, define ZLIB_DLL. - * This is not mandatory, but it offers a little performance increase. - */ -# ifdef ZLIB_DLL -# if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500)) -# ifdef ZLIB_INTERNAL -# define ZEXTERN extern __declspec(dllexport) -# else -# define ZEXTERN extern __declspec(dllimport) -# endif -# endif -# endif /* ZLIB_DLL */ - /* If building or using zlib with the WINAPI/WINAPIV calling convention, - * define ZLIB_WINAPI. - * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI. - */ -# ifdef ZLIB_WINAPI -# ifdef FAR -# undef FAR -# endif -# include - /* No need for _export, use ZLIB.DEF instead. */ - /* For complete Windows compatibility, use WINAPI, not __stdcall. */ -# define ZEXPORT WINAPI -# ifdef WIN32 -# define ZEXPORTVA WINAPIV -# else -# define ZEXPORTVA FAR CDECL -# endif -# endif -#endif - -#if defined (__BEOS__) -# ifdef ZLIB_DLL -# ifdef ZLIB_INTERNAL -# define ZEXPORT __declspec(dllexport) -# define ZEXPORTVA __declspec(dllexport) -# else -# define ZEXPORT __declspec(dllimport) -# define ZEXPORTVA __declspec(dllimport) -# endif -# endif -#endif - -#ifndef ZEXTERN -# define ZEXTERN extern -#endif -#ifndef ZEXPORT -# define ZEXPORT -#endif -#ifndef ZEXPORTVA -# define ZEXPORTVA -#endif - -#ifndef FAR -# define FAR -#endif - -#if !defined(__MACTYPES__) -typedef unsigned char Byte; /* 8 bits */ -#endif -typedef unsigned int uInt; /* 16 bits or more */ -typedef unsigned long uLong; /* 32 bits or more */ - -#ifdef SMALL_MEDIUM - /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */ -# define Bytef Byte FAR -#else - typedef Byte FAR Bytef; -#endif -typedef char FAR charf; -typedef int FAR intf; -typedef uInt FAR uIntf; -typedef uLong FAR uLongf; - -#ifdef STDC - typedef void const *voidpc; - typedef void FAR *voidpf; - typedef void *voidp; -#else - typedef Byte const *voidpc; - typedef Byte FAR *voidpf; - typedef Byte *voidp; -#endif - -#if 0 /* HAVE_UNISTD_H -- this line is updated by ./configure */ -# include /* for off_t */ -# include /* for SEEK_* and off_t */ -# ifdef VMS -# include /* for off_t */ -# endif -# define z_off_t off_t -#endif -#ifndef SEEK_SET -# define SEEK_SET 0 /* Seek from beginning of file. */ -# define SEEK_CUR 1 /* Seek from current position. */ -# define SEEK_END 2 /* Set file pointer to EOF plus "offset" */ -#endif -#ifndef z_off_t -# define z_off_t long -#endif - -#if defined(__OS400__) -# define NO_vsnprintf -#endif - -#if defined(__MVS__) -# define NO_vsnprintf -# ifdef FAR -# undef FAR -# endif -#endif - -/* MVS linker does not support external names larger than 8 bytes */ -#if defined(__MVS__) -# pragma map(deflateInit_,"DEIN") -# pragma map(deflateInit2_,"DEIN2") -# pragma map(deflateEnd,"DEEND") -# pragma map(deflateBound,"DEBND") -# pragma map(inflateInit_,"ININ") -# pragma map(inflateInit2_,"ININ2") -# pragma map(inflateEnd,"INEND") -# pragma map(inflateSync,"INSY") -# pragma map(inflateSetDictionary,"INSEDI") -# pragma map(compressBound,"CMBND") -# pragma map(inflate_table,"INTABL") -# pragma map(inflate_fast,"INFA") -# pragma map(inflate_copyright,"INCOPY") -#endif - -#endif /* ZCONF_H */ +/* zconf.h -- configuration of the zlib compression library + * Copyright (C) 1995-2005 Jean-loup Gailly. + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* @(#) $Id: //poco/1.2/Foundation/src/zconf.h#1 $ */ + +#ifndef ZCONF_H +#define ZCONF_H + +/* + * If you *really* need a unique prefix for all types and library functions, + * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it. + */ +#ifdef Z_PREFIX +# define deflateInit_ z_deflateInit_ +# define deflate z_deflate +# define deflateEnd z_deflateEnd +# define inflateInit_ z_inflateInit_ +# define inflate z_inflate +# define inflateEnd z_inflateEnd +# define deflateInit2_ z_deflateInit2_ +# define deflateSetDictionary z_deflateSetDictionary +# define deflateCopy z_deflateCopy +# define deflateReset z_deflateReset +# define deflateParams z_deflateParams +# define deflateBound z_deflateBound +# define deflatePrime z_deflatePrime +# define inflateInit2_ z_inflateInit2_ +# define inflateSetDictionary z_inflateSetDictionary +# define inflateSync z_inflateSync +# define inflateSyncPoint z_inflateSyncPoint +# define inflateCopy z_inflateCopy +# define inflateReset z_inflateReset +# define inflateBack z_inflateBack +# define inflateBackEnd z_inflateBackEnd +# define compress z_compress +# define compress2 z_compress2 +# define compressBound z_compressBound +# define uncompress z_uncompress +# define adler32 z_adler32 +# define crc32 z_crc32 +# define get_crc_table z_get_crc_table +# define zError z_zError + +# define alloc_func z_alloc_func +# define free_func z_free_func +# define in_func z_in_func +# define out_func z_out_func +# define Byte z_Byte +# define uInt z_uInt +# define uLong z_uLong +# define Bytef z_Bytef +# define charf z_charf +# define intf z_intf +# define uIntf z_uIntf +# define uLongf z_uLongf +# define voidpf z_voidpf +# define voidp z_voidp +#endif + +#if defined(__MSDOS__) && !defined(MSDOS) +# define MSDOS +#endif +#if (defined(OS_2) || defined(__OS2__)) && !defined(OS2) +# define OS2 +#endif +#if defined(_WINDOWS) && !defined(WINDOWS) +# define WINDOWS +#endif +#if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__) +# ifndef WIN32 +# define WIN32 +# endif +#endif +#if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32) +# if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__) +# ifndef SYS16BIT +# define SYS16BIT +# endif +# endif +#endif + +/* + * Compile with -DMAXSEG_64K if the alloc function cannot allocate more + * than 64k bytes at a time (needed on systems with 16-bit int). + */ +#ifdef SYS16BIT +# define MAXSEG_64K +#endif +#ifdef MSDOS +# define UNALIGNED_OK +#endif + +#ifdef __STDC_VERSION__ +# ifndef STDC +# define STDC +# endif +# if __STDC_VERSION__ >= 199901L +# ifndef STDC99 +# define STDC99 +# endif +# endif +#endif +#if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus)) +# define STDC +#endif +#if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__)) +# define STDC +#endif +#if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32)) +# define STDC +#endif +#if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__)) +# define STDC +#endif + +#if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */ +# define STDC +#endif + +#ifndef STDC +# ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */ +# define const /* note: need a more gentle solution here */ +# endif +#endif + +/* Some Mac compilers merge all .h files incorrectly: */ +#if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__) +# define NO_DUMMY_DECL +#endif + +/* Maximum value for memLevel in deflateInit2 */ +#ifndef MAX_MEM_LEVEL +# ifdef MAXSEG_64K +# define MAX_MEM_LEVEL 8 +# else +# define MAX_MEM_LEVEL 9 +# endif +#endif + +/* Maximum value for windowBits in deflateInit2 and inflateInit2. + * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files + * created by gzip. (Files created by minigzip can still be extracted by + * gzip.) + */ +#ifndef MAX_WBITS +# define MAX_WBITS 15 /* 32K LZ77 window */ +#endif + +/* The memory requirements for deflate are (in bytes): + (1 << (windowBits+2)) + (1 << (memLevel+9)) + that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values) + plus a few kilobytes for small objects. For example, if you want to reduce + the default memory requirements from 256K to 128K, compile with + make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7" + Of course this will generally degrade compression (there's no free lunch). + + The memory requirements for inflate are (in bytes) 1 << windowBits + that is, 32K for windowBits=15 (default value) plus a few kilobytes + for small objects. +*/ + + /* Type declarations */ + +#ifndef OF /* function prototypes */ +# ifdef STDC +# define OF(args) args +# else +# define OF(args) () +# endif +#endif + +/* The following definitions for FAR are needed only for MSDOS mixed + * model programming (small or medium model with some far allocations). + * This was tested only with MSC; for other MSDOS compilers you may have + * to define NO_MEMCPY in zutil.h. If you don't need the mixed model, + * just define FAR to be empty. + */ +#ifdef SYS16BIT +# if defined(M_I86SM) || defined(M_I86MM) + /* MSC small or medium model */ +# define SMALL_MEDIUM +# ifdef _MSC_VER +# define FAR _far +# else +# define FAR far +# endif +# endif +# if (defined(__SMALL__) || defined(__MEDIUM__)) + /* Turbo C small or medium model */ +# define SMALL_MEDIUM +# ifdef __BORLANDC__ +# define FAR _far +# else +# define FAR far +# endif +# endif +#endif + +#if defined(WINDOWS) || defined(WIN32) + /* If building or using zlib as a DLL, define ZLIB_DLL. + * This is not mandatory, but it offers a little performance increase. + */ +# ifdef ZLIB_DLL +# if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500)) +# ifdef ZLIB_INTERNAL +# define ZEXTERN extern __declspec(dllexport) +# else +# define ZEXTERN extern __declspec(dllimport) +# endif +# endif +# endif /* ZLIB_DLL */ + /* If building or using zlib with the WINAPI/WINAPIV calling convention, + * define ZLIB_WINAPI. + * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI. + */ +# ifdef ZLIB_WINAPI +# ifdef FAR +# undef FAR +# endif +# include + /* No need for _export, use ZLIB.DEF instead. */ + /* For complete Windows compatibility, use WINAPI, not __stdcall. */ +# define ZEXPORT WINAPI +# ifdef WIN32 +# define ZEXPORTVA WINAPIV +# else +# define ZEXPORTVA FAR CDECL +# endif +# endif +#endif + +#if defined (__BEOS__) +# ifdef ZLIB_DLL +# ifdef ZLIB_INTERNAL +# define ZEXPORT __declspec(dllexport) +# define ZEXPORTVA __declspec(dllexport) +# else +# define ZEXPORT __declspec(dllimport) +# define ZEXPORTVA __declspec(dllimport) +# endif +# endif +#endif + +#ifndef ZEXTERN +# define ZEXTERN extern +#endif +#ifndef ZEXPORT +# define ZEXPORT +#endif +#ifndef ZEXPORTVA +# define ZEXPORTVA +#endif + +#ifndef FAR +# define FAR +#endif + +#if !defined(__MACTYPES__) +typedef unsigned char Byte; /* 8 bits */ +#endif +typedef unsigned int uInt; /* 16 bits or more */ +typedef unsigned long uLong; /* 32 bits or more */ + +#ifdef SMALL_MEDIUM + /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */ +# define Bytef Byte FAR +#else + typedef Byte FAR Bytef; +#endif +typedef char FAR charf; +typedef int FAR intf; +typedef uInt FAR uIntf; +typedef uLong FAR uLongf; + +#ifdef STDC + typedef void const *voidpc; + typedef void FAR *voidpf; + typedef void *voidp; +#else + typedef Byte const *voidpc; + typedef Byte FAR *voidpf; + typedef Byte *voidp; +#endif + +#if 0 /* HAVE_UNISTD_H -- this line is updated by ./configure */ +# include /* for off_t */ +# include /* for SEEK_* and off_t */ +# ifdef VMS +# include /* for off_t */ +# endif +# define z_off_t off_t +#endif +#ifndef SEEK_SET +# define SEEK_SET 0 /* Seek from beginning of file. */ +# define SEEK_CUR 1 /* Seek from current position. */ +# define SEEK_END 2 /* Set file pointer to EOF plus "offset" */ +#endif +#ifndef z_off_t +# define z_off_t long +#endif + +#if defined(__OS400__) +# define NO_vsnprintf +#endif + +#if defined(__MVS__) +# define NO_vsnprintf +# ifdef FAR +# undef FAR +# endif +#endif + +/* MVS linker does not support external names larger than 8 bytes */ +#if defined(__MVS__) +# pragma map(deflateInit_,"DEIN") +# pragma map(deflateInit2_,"DEIN2") +# pragma map(deflateEnd,"DEEND") +# pragma map(deflateBound,"DEBND") +# pragma map(inflateInit_,"ININ") +# pragma map(inflateInit2_,"ININ2") +# pragma map(inflateEnd,"INEND") +# pragma map(inflateSync,"INSY") +# pragma map(inflateSetDictionary,"INSEDI") +# pragma map(compressBound,"CMBND") +# pragma map(inflate_table,"INTABL") +# pragma map(inflate_fast,"INFA") +# pragma map(inflate_copyright,"INCOPY") +#endif + +#endif /* ZCONF_H */ diff --git a/Foundation/src/zlib.h b/Foundation/src/zlib.h index 62d0e4675..022817927 100644 --- a/Foundation/src/zlib.h +++ b/Foundation/src/zlib.h @@ -1,1357 +1,1357 @@ -/* zlib.h -- interface of the 'zlib' general purpose compression library - version 1.2.3, July 18th, 2005 - - Copyright (C) 1995-2005 Jean-loup Gailly and Mark Adler - - 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. - - Jean-loup Gailly Mark Adler - jloup@gzip.org madler@alumni.caltech.edu - - - The data format used by the zlib library is described by RFCs (Request for - Comments) 1950 to 1952 in the files http://www.ietf.org/rfc/rfc1950.txt - (zlib format), rfc1951.txt (deflate format) and rfc1952.txt (gzip format). -*/ - -#ifndef ZLIB_H -#define ZLIB_H - -#include "zconf.h" - -#ifdef __cplusplus -extern "C" { -#endif - -#define ZLIB_VERSION "1.2.3" -#define ZLIB_VERNUM 0x1230 - -/* - The 'zlib' compression library provides in-memory compression and - decompression functions, including integrity checks of the uncompressed - data. This version of the library supports only one compression method - (deflation) but other algorithms will be added later and will have the same - stream interface. - - Compression can be done in a single step if the buffers are large - enough (for example if an input file is mmap'ed), or can be done by - repeated calls of the compression function. In the latter case, the - application must provide more input and/or consume the output - (providing more output space) before each call. - - The compressed data format used by default by the in-memory functions is - the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped - around a deflate stream, which is itself documented in RFC 1951. - - The library also supports reading and writing files in gzip (.gz) format - with an interface similar to that of stdio using the functions that start - with "gz". The gzip format is different from the zlib format. gzip is a - gzip wrapper, documented in RFC 1952, wrapped around a deflate stream. - - This library can optionally read and write gzip streams in memory as well. - - The zlib format was designed to be compact and fast for use in memory - and on communications channels. The gzip format was designed for single- - file compression on file systems, has a larger header than zlib to maintain - directory information, and uses a different, slower check method than zlib. - - The library does not install any signal handler. The decoder checks - the consistency of the compressed data, so the library should never - crash even in case of corrupted input. -*/ - -typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size)); -typedef void (*free_func) OF((voidpf opaque, voidpf address)); - -struct internal_state; - -typedef struct z_stream_s { - Bytef *next_in; /* next input byte */ - uInt avail_in; /* number of bytes available at next_in */ - uLong total_in; /* total nb of input bytes read so far */ - - Bytef *next_out; /* next output byte should be put there */ - uInt avail_out; /* remaining free space at next_out */ - uLong total_out; /* total nb of bytes output so far */ - - char *msg; /* last error message, NULL if no error */ - struct internal_state FAR *state; /* not visible by applications */ - - alloc_func zalloc; /* used to allocate the internal state */ - free_func zfree; /* used to free the internal state */ - voidpf opaque; /* private data object passed to zalloc and zfree */ - - int data_type; /* best guess about the data type: binary or text */ - uLong adler; /* adler32 value of the uncompressed data */ - uLong reserved; /* reserved for future use */ -} z_stream; - -typedef z_stream FAR *z_streamp; - -/* - gzip header information passed to and from zlib routines. See RFC 1952 - for more details on the meanings of these fields. -*/ -typedef struct gz_header_s { - int text; /* true if compressed data believed to be text */ - uLong time; /* modification time */ - int xflags; /* extra flags (not used when writing a gzip file) */ - int os; /* operating system */ - Bytef *extra; /* pointer to extra field or Z_NULL if none */ - uInt extra_len; /* extra field length (valid if extra != Z_NULL) */ - uInt extra_max; /* space at extra (only when reading header) */ - Bytef *name; /* pointer to zero-terminated file name or Z_NULL */ - uInt name_max; /* space at name (only when reading header) */ - Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */ - uInt comm_max; /* space at comment (only when reading header) */ - int hcrc; /* true if there was or will be a header crc */ - int done; /* true when done reading gzip header (not used - when writing a gzip file) */ -} gz_header; - -typedef gz_header FAR *gz_headerp; - -/* - The application must update next_in and avail_in when avail_in has - dropped to zero. It must update next_out and avail_out when avail_out - has dropped to zero. The application must initialize zalloc, zfree and - opaque before calling the init function. All other fields are set by the - compression library and must not be updated by the application. - - The opaque value provided by the application will be passed as the first - parameter for calls of zalloc and zfree. This can be useful for custom - memory management. The compression library attaches no meaning to the - opaque value. - - zalloc must return Z_NULL if there is not enough memory for the object. - If zlib is used in a multi-threaded application, zalloc and zfree must be - thread safe. - - On 16-bit systems, the functions zalloc and zfree must be able to allocate - exactly 65536 bytes, but will not be required to allocate more than this - if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS, - pointers returned by zalloc for objects of exactly 65536 bytes *must* - have their offset normalized to zero. The default allocation function - provided by this library ensures this (see zutil.c). To reduce memory - requirements and avoid any allocation of 64K objects, at the expense of - compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h). - - The fields total_in and total_out can be used for statistics or - progress reports. After compression, total_in holds the total size of - the uncompressed data and may be saved for use in the decompressor - (particularly if the decompressor wants to decompress everything in - a single step). -*/ - - /* constants */ - -#define Z_NO_FLUSH 0 -#define Z_PARTIAL_FLUSH 1 /* will be removed, use Z_SYNC_FLUSH instead */ -#define Z_SYNC_FLUSH 2 -#define Z_FULL_FLUSH 3 -#define Z_FINISH 4 -#define Z_BLOCK 5 -/* Allowed flush values; see deflate() and inflate() below for details */ - -#define Z_OK 0 -#define Z_STREAM_END 1 -#define Z_NEED_DICT 2 -#define Z_ERRNO (-1) -#define Z_STREAM_ERROR (-2) -#define Z_DATA_ERROR (-3) -#define Z_MEM_ERROR (-4) -#define Z_BUF_ERROR (-5) -#define Z_VERSION_ERROR (-6) -/* Return codes for the compression/decompression functions. Negative - * values are errors, positive values are used for special but normal events. - */ - -#define Z_NO_COMPRESSION 0 -#define Z_BEST_SPEED 1 -#define Z_BEST_COMPRESSION 9 -#define Z_DEFAULT_COMPRESSION (-1) -/* compression levels */ - -#define Z_FILTERED 1 -#define Z_HUFFMAN_ONLY 2 -#define Z_RLE 3 -#define Z_FIXED 4 -#define Z_DEFAULT_STRATEGY 0 -/* compression strategy; see deflateInit2() below for details */ - -#define Z_BINARY 0 -#define Z_TEXT 1 -#define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */ -#define Z_UNKNOWN 2 -/* Possible values of the data_type field (though see inflate()) */ - -#define Z_DEFLATED 8 -/* The deflate compression method (the only one supported in this version) */ - -#define Z_NULL 0 /* for initializing zalloc, zfree, opaque */ - -#define zlib_version zlibVersion() -/* for compatibility with versions < 1.0.2 */ - - /* basic functions */ - -ZEXTERN const char * ZEXPORT zlibVersion OF((void)); -/* The application can compare zlibVersion and ZLIB_VERSION for consistency. - If the first character differs, the library code actually used is - not compatible with the zlib.h header file used by the application. - This check is automatically made by deflateInit and inflateInit. - */ - -/* -ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level)); - - Initializes the internal stream state for compression. The fields - zalloc, zfree and opaque must be initialized before by the caller. - If zalloc and zfree are set to Z_NULL, deflateInit updates them to - use default allocation functions. - - The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9: - 1 gives best speed, 9 gives best compression, 0 gives no compression at - all (the input data is simply copied a block at a time). - Z_DEFAULT_COMPRESSION requests a default compromise between speed and - compression (currently equivalent to level 6). - - deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not - enough memory, Z_STREAM_ERROR if level is not a valid compression level, - Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible - with the version assumed by the caller (ZLIB_VERSION). - msg is set to null if there is no error message. deflateInit does not - perform any compression: this will be done by deflate(). -*/ - - -ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush)); -/* - deflate compresses as much data as possible, and stops when the input - buffer becomes empty or the output buffer becomes full. It may introduce some - output latency (reading input without producing any output) except when - forced to flush. - - The detailed semantics are as follows. deflate performs one or both of the - following actions: - - - Compress more input starting at next_in and update next_in and avail_in - accordingly. If not all input can be processed (because there is not - enough room in the output buffer), next_in and avail_in are updated and - processing will resume at this point for the next call of deflate(). - - - Provide more output starting at next_out and update next_out and avail_out - accordingly. This action is forced if the parameter flush is non zero. - Forcing flush frequently degrades the compression ratio, so this parameter - should be set only when necessary (in interactive applications). - Some output may be provided even if flush is not set. - - Before the call of deflate(), the application should ensure that at least - one of the actions is possible, by providing more input and/or consuming - more output, and updating avail_in or avail_out accordingly; avail_out - should never be zero before the call. The application can consume the - compressed output when it wants, for example when the output buffer is full - (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK - and with zero avail_out, it must be called again after making room in the - output buffer because there might be more output pending. - - Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to - decide how much data to accumualte before producing output, in order to - maximize compression. - - If the parameter flush is set to Z_SYNC_FLUSH, all pending output is - flushed to the output buffer and the output is aligned on a byte boundary, so - that the decompressor can get all input data available so far. (In particular - avail_in is zero after the call if enough output space has been provided - before the call.) Flushing may degrade compression for some compression - algorithms and so it should be used only when necessary. - - If flush is set to Z_FULL_FLUSH, all output is flushed as with - Z_SYNC_FLUSH, and the compression state is reset so that decompression can - restart from this point if previous compressed data has been damaged or if - random access is desired. Using Z_FULL_FLUSH too often can seriously degrade - compression. - - If deflate returns with avail_out == 0, this function must be called again - with the same value of the flush parameter and more output space (updated - avail_out), until the flush is complete (deflate returns with non-zero - avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that - avail_out is greater than six to avoid repeated flush markers due to - avail_out == 0 on return. - - If the parameter flush is set to Z_FINISH, pending input is processed, - pending output is flushed and deflate returns with Z_STREAM_END if there - was enough output space; if deflate returns with Z_OK, this function must be - called again with Z_FINISH and more output space (updated avail_out) but no - more input data, until it returns with Z_STREAM_END or an error. After - deflate has returned Z_STREAM_END, the only possible operations on the - stream are deflateReset or deflateEnd. - - Z_FINISH can be used immediately after deflateInit if all the compression - is to be done in a single step. In this case, avail_out must be at least - the value returned by deflateBound (see below). If deflate does not return - Z_STREAM_END, then it must be called again as described above. - - deflate() sets strm->adler to the adler32 checksum of all input read - so far (that is, total_in bytes). - - deflate() may update strm->data_type if it can make a good guess about - the input data type (Z_BINARY or Z_TEXT). In doubt, the data is considered - binary. This field is only for information purposes and does not affect - the compression algorithm in any manner. - - deflate() returns Z_OK if some progress has been made (more input - processed or more output produced), Z_STREAM_END if all input has been - consumed and all output has been produced (only when flush is set to - Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example - if next_in or next_out was NULL), Z_BUF_ERROR if no progress is possible - (for example avail_in or avail_out was zero). Note that Z_BUF_ERROR is not - fatal, and deflate() can be called again with more input and more output - space to continue compressing. -*/ - - -ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm)); -/* - All dynamically allocated data structures for this stream are freed. - This function discards any unprocessed input and does not flush any - pending output. - - deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the - stream state was inconsistent, Z_DATA_ERROR if the stream was freed - prematurely (some input or output was discarded). In the error case, - msg may be set but then points to a static string (which must not be - deallocated). -*/ - - -/* -ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm)); - - Initializes the internal stream state for decompression. The fields - next_in, avail_in, zalloc, zfree and opaque must be initialized before by - the caller. If next_in is not Z_NULL and avail_in is large enough (the exact - value depends on the compression method), inflateInit determines the - compression method from the zlib header and allocates all data structures - accordingly; otherwise the allocation will be deferred to the first call of - inflate. If zalloc and zfree are set to Z_NULL, inflateInit updates them to - use default allocation functions. - - inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough - memory, Z_VERSION_ERROR if the zlib library version is incompatible with the - version assumed by the caller. msg is set to null if there is no error - message. inflateInit does not perform any decompression apart from reading - the zlib header if present: this will be done by inflate(). (So next_in and - avail_in may be modified, but next_out and avail_out are unchanged.) -*/ - - -ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush)); -/* - inflate decompresses as much data as possible, and stops when the input - buffer becomes empty or the output buffer becomes full. It may introduce - some output latency (reading input without producing any output) except when - forced to flush. - - The detailed semantics are as follows. inflate performs one or both of the - following actions: - - - Decompress more input starting at next_in and update next_in and avail_in - accordingly. If not all input can be processed (because there is not - enough room in the output buffer), next_in is updated and processing - will resume at this point for the next call of inflate(). - - - Provide more output starting at next_out and update next_out and avail_out - accordingly. inflate() provides as much output as possible, until there - is no more input data or no more space in the output buffer (see below - about the flush parameter). - - Before the call of inflate(), the application should ensure that at least - one of the actions is possible, by providing more input and/or consuming - more output, and updating the next_* and avail_* values accordingly. - The application can consume the uncompressed output when it wants, for - example when the output buffer is full (avail_out == 0), or after each - call of inflate(). If inflate returns Z_OK and with zero avail_out, it - must be called again after making room in the output buffer because there - might be more output pending. - - The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH, - Z_FINISH, or Z_BLOCK. Z_SYNC_FLUSH requests that inflate() flush as much - output as possible to the output buffer. Z_BLOCK requests that inflate() stop - if and when it gets to the next deflate block boundary. When decoding the - zlib or gzip format, this will cause inflate() to return immediately after - the header and before the first block. When doing a raw inflate, inflate() - will go ahead and process the first block, and will return when it gets to - the end of that block, or when it runs out of data. - - The Z_BLOCK option assists in appending to or combining deflate streams. - Also to assist in this, on return inflate() will set strm->data_type to the - number of unused bits in the last byte taken from strm->next_in, plus 64 - if inflate() is currently decoding the last block in the deflate stream, - plus 128 if inflate() returned immediately after decoding an end-of-block - code or decoding the complete header up to just before the first byte of the - deflate stream. The end-of-block will not be indicated until all of the - uncompressed data from that block has been written to strm->next_out. The - number of unused bits may in general be greater than seven, except when - bit 7 of data_type is set, in which case the number of unused bits will be - less than eight. - - inflate() should normally be called until it returns Z_STREAM_END or an - error. However if all decompression is to be performed in a single step - (a single call of inflate), the parameter flush should be set to - Z_FINISH. In this case all pending input is processed and all pending - output is flushed; avail_out must be large enough to hold all the - uncompressed data. (The size of the uncompressed data may have been saved - by the compressor for this purpose.) The next operation on this stream must - be inflateEnd to deallocate the decompression state. The use of Z_FINISH - is never required, but can be used to inform inflate that a faster approach - may be used for the single inflate() call. - - In this implementation, inflate() always flushes as much output as - possible to the output buffer, and always uses the faster approach on the - first call. So the only effect of the flush parameter in this implementation - is on the return value of inflate(), as noted below, or when it returns early - because Z_BLOCK is used. - - If a preset dictionary is needed after this call (see inflateSetDictionary - below), inflate sets strm->adler to the adler32 checksum of the dictionary - chosen by the compressor and returns Z_NEED_DICT; otherwise it sets - strm->adler to the adler32 checksum of all output produced so far (that is, - total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described - below. At the end of the stream, inflate() checks that its computed adler32 - checksum is equal to that saved by the compressor and returns Z_STREAM_END - only if the checksum is correct. - - inflate() will decompress and check either zlib-wrapped or gzip-wrapped - deflate data. The header type is detected automatically. Any information - contained in the gzip header is not retained, so applications that need that - information should instead use raw inflate, see inflateInit2() below, or - inflateBack() and perform their own processing of the gzip header and - trailer. - - inflate() returns Z_OK if some progress has been made (more input processed - or more output produced), Z_STREAM_END if the end of the compressed data has - been reached and all uncompressed output has been produced, Z_NEED_DICT if a - preset dictionary is needed at this point, Z_DATA_ERROR if the input data was - corrupted (input stream not conforming to the zlib format or incorrect check - value), Z_STREAM_ERROR if the stream structure was inconsistent (for example - if next_in or next_out was NULL), Z_MEM_ERROR if there was not enough memory, - Z_BUF_ERROR if no progress is possible or if there was not enough room in the - output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and - inflate() can be called again with more input and more output space to - continue decompressing. If Z_DATA_ERROR is returned, the application may then - call inflateSync() to look for a good compression block if a partial recovery - of the data is desired. -*/ - - -ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm)); -/* - All dynamically allocated data structures for this stream are freed. - This function discards any unprocessed input and does not flush any - pending output. - - inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state - was inconsistent. In the error case, msg may be set but then points to a - static string (which must not be deallocated). -*/ - - /* Advanced functions */ - -/* - The following functions are needed only in some special applications. -*/ - -/* -ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm, - int level, - int method, - int windowBits, - int memLevel, - int strategy)); - - This is another version of deflateInit with more compression options. The - fields next_in, zalloc, zfree and opaque must be initialized before by - the caller. - - The method parameter is the compression method. It must be Z_DEFLATED in - this version of the library. - - The windowBits parameter is the base two logarithm of the window size - (the size of the history buffer). It should be in the range 8..15 for this - version of the library. Larger values of this parameter result in better - compression at the expense of memory usage. The default value is 15 if - deflateInit is used instead. - - windowBits can also be -8..-15 for raw deflate. In this case, -windowBits - determines the window size. deflate() will then generate raw deflate data - with no zlib header or trailer, and will not compute an adler32 check value. - - windowBits can also be greater than 15 for optional gzip encoding. Add - 16 to windowBits to write a simple gzip header and trailer around the - compressed data instead of a zlib wrapper. The gzip header will have no - file name, no extra data, no comment, no modification time (set to zero), - no header crc, and the operating system will be set to 255 (unknown). If a - gzip stream is being written, strm->adler is a crc32 instead of an adler32. - - The memLevel parameter specifies how much memory should be allocated - for the internal compression state. memLevel=1 uses minimum memory but - is slow and reduces compression ratio; memLevel=9 uses maximum memory - for optimal speed. The default value is 8. See zconf.h for total memory - usage as a function of windowBits and memLevel. - - The strategy parameter is used to tune the compression algorithm. Use the - value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a - filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no - string match), or Z_RLE to limit match distances to one (run-length - encoding). Filtered data consists mostly of small values with a somewhat - random distribution. In this case, the compression algorithm is tuned to - compress them better. The effect of Z_FILTERED is to force more Huffman - coding and less string matching; it is somewhat intermediate between - Z_DEFAULT and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as fast as - Z_HUFFMAN_ONLY, but give better compression for PNG image data. The strategy - parameter only affects the compression ratio but not the correctness of the - compressed output even if it is not set appropriately. Z_FIXED prevents the - use of dynamic Huffman codes, allowing for a simpler decoder for special - applications. - - deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough - memory, Z_STREAM_ERROR if a parameter is invalid (such as an invalid - method). msg is set to null if there is no error message. deflateInit2 does - not perform any compression: this will be done by deflate(). -*/ - -ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm, - const Bytef *dictionary, - uInt dictLength)); -/* - Initializes the compression dictionary from the given byte sequence - without producing any compressed output. This function must be called - immediately after deflateInit, deflateInit2 or deflateReset, before any - call of deflate. The compressor and decompressor must use exactly the same - dictionary (see inflateSetDictionary). - - The dictionary should consist of strings (byte sequences) that are likely - to be encountered later in the data to be compressed, with the most commonly - used strings preferably put towards the end of the dictionary. Using a - dictionary is most useful when the data to be compressed is short and can be - predicted with good accuracy; the data can then be compressed better than - with the default empty dictionary. - - Depending on the size of the compression data structures selected by - deflateInit or deflateInit2, a part of the dictionary may in effect be - discarded, for example if the dictionary is larger than the window size in - deflate or deflate2. Thus the strings most likely to be useful should be - put at the end of the dictionary, not at the front. In addition, the - current implementation of deflate will use at most the window size minus - 262 bytes of the provided dictionary. - - Upon return of this function, strm->adler is set to the adler32 value - of the dictionary; the decompressor may later use this value to determine - which dictionary has been used by the compressor. (The adler32 value - applies to the whole dictionary even if only a subset of the dictionary is - actually used by the compressor.) If a raw deflate was requested, then the - adler32 value is not computed and strm->adler is not set. - - deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a - parameter is invalid (such as NULL dictionary) or the stream state is - inconsistent (for example if deflate has already been called for this stream - or if the compression method is bsort). deflateSetDictionary does not - perform any compression: this will be done by deflate(). -*/ - -ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest, - z_streamp source)); -/* - Sets the destination stream as a complete copy of the source stream. - - This function can be useful when several compression strategies will be - tried, for example when there are several ways of pre-processing the input - data with a filter. The streams that will be discarded should then be freed - by calling deflateEnd. Note that deflateCopy duplicates the internal - compression state which can be quite large, so this strategy is slow and - can consume lots of memory. - - deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not - enough memory, Z_STREAM_ERROR if the source stream state was inconsistent - (such as zalloc being NULL). msg is left unchanged in both source and - destination. -*/ - -ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm)); -/* - This function is equivalent to deflateEnd followed by deflateInit, - but does not free and reallocate all the internal compression state. - The stream will keep the same compression level and any other attributes - that may have been set by deflateInit2. - - deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source - stream state was inconsistent (such as zalloc or state being NULL). -*/ - -ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm, - int level, - int strategy)); -/* - Dynamically update the compression level and compression strategy. The - interpretation of level and strategy is as in deflateInit2. This can be - used to switch between compression and straight copy of the input data, or - to switch to a different kind of input data requiring a different - strategy. If the compression level is changed, the input available so far - is compressed with the old level (and may be flushed); the new level will - take effect only at the next call of deflate(). - - Before the call of deflateParams, the stream state must be set as for - a call of deflate(), since the currently available input may have to - be compressed and flushed. In particular, strm->avail_out must be non-zero. - - deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source - stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR - if strm->avail_out was zero. -*/ - -ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm, - int good_length, - int max_lazy, - int nice_length, - int max_chain)); -/* - Fine tune deflate's internal compression parameters. This should only be - used by someone who understands the algorithm used by zlib's deflate for - searching for the best matching string, and even then only by the most - fanatic optimizer trying to squeeze out the last compressed bit for their - specific input data. Read the deflate.c source code for the meaning of the - max_lazy, good_length, nice_length, and max_chain parameters. - - deflateTune() can be called after deflateInit() or deflateInit2(), and - returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream. - */ - -ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm, - uLong sourceLen)); -/* - deflateBound() returns an upper bound on the compressed size after - deflation of sourceLen bytes. It must be called after deflateInit() - or deflateInit2(). This would be used to allocate an output buffer - for deflation in a single pass, and so would be called before deflate(). -*/ - -ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm, - int bits, - int value)); -/* - deflatePrime() inserts bits in the deflate output stream. The intent - is that this function is used to start off the deflate output with the - bits leftover from a previous deflate stream when appending to it. As such, - this function can only be used for raw deflate, and must be used before the - first deflate() call after a deflateInit2() or deflateReset(). bits must be - less than or equal to 16, and that many of the least significant bits of - value will be inserted in the output. - - deflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source - stream state was inconsistent. -*/ - -ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm, - gz_headerp head)); -/* - deflateSetHeader() provides gzip header information for when a gzip - stream is requested by deflateInit2(). deflateSetHeader() may be called - after deflateInit2() or deflateReset() and before the first call of - deflate(). The text, time, os, extra field, name, and comment information - in the provided gz_header structure are written to the gzip header (xflag is - ignored -- the extra flags are set according to the compression level). The - caller must assure that, if not Z_NULL, name and comment are terminated with - a zero byte, and that if extra is not Z_NULL, that extra_len bytes are - available there. If hcrc is true, a gzip header crc is included. Note that - the current versions of the command-line version of gzip (up through version - 1.3.x) do not support header crc's, and will report that it is a "multi-part - gzip file" and give up. - - If deflateSetHeader is not used, the default gzip header has text false, - the time set to zero, and os set to 255, with no extra, name, or comment - fields. The gzip header is returned to the default state by deflateReset(). - - deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source - stream state was inconsistent. -*/ - -/* -ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm, - int windowBits)); - - This is another version of inflateInit with an extra parameter. The - fields next_in, avail_in, zalloc, zfree and opaque must be initialized - before by the caller. - - The windowBits parameter is the base two logarithm of the maximum window - size (the size of the history buffer). It should be in the range 8..15 for - this version of the library. The default value is 15 if inflateInit is used - instead. windowBits must be greater than or equal to the windowBits value - provided to deflateInit2() while compressing, or it must be equal to 15 if - deflateInit2() was not used. If a compressed stream with a larger window - size is given as input, inflate() will return with the error code - Z_DATA_ERROR instead of trying to allocate a larger window. - - windowBits can also be -8..-15 for raw inflate. In this case, -windowBits - determines the window size. inflate() will then process raw deflate data, - not looking for a zlib or gzip header, not generating a check value, and not - looking for any check values for comparison at the end of the stream. This - is for use with other formats that use the deflate compressed data format - such as zip. Those formats provide their own check values. If a custom - format is developed using the raw deflate format for compressed data, it is - recommended that a check value such as an adler32 or a crc32 be applied to - the uncompressed data as is done in the zlib, gzip, and zip formats. For - most applications, the zlib format should be used as is. Note that comments - above on the use in deflateInit2() applies to the magnitude of windowBits. - - windowBits can also be greater than 15 for optional gzip decoding. Add - 32 to windowBits to enable zlib and gzip decoding with automatic header - detection, or add 16 to decode only the gzip format (the zlib format will - return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is - a crc32 instead of an adler32. - - inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough - memory, Z_STREAM_ERROR if a parameter is invalid (such as a null strm). msg - is set to null if there is no error message. inflateInit2 does not perform - any decompression apart from reading the zlib header if present: this will - be done by inflate(). (So next_in and avail_in may be modified, but next_out - and avail_out are unchanged.) -*/ - -ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm, - const Bytef *dictionary, - uInt dictLength)); -/* - Initializes the decompression dictionary from the given uncompressed byte - sequence. This function must be called immediately after a call of inflate, - if that call returned Z_NEED_DICT. The dictionary chosen by the compressor - can be determined from the adler32 value returned by that call of inflate. - The compressor and decompressor must use exactly the same dictionary (see - deflateSetDictionary). For raw inflate, this function can be called - immediately after inflateInit2() or inflateReset() and before any call of - inflate() to set the dictionary. The application must insure that the - dictionary that was used for compression is provided. - - inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a - parameter is invalid (such as NULL dictionary) or the stream state is - inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the - expected one (incorrect adler32 value). inflateSetDictionary does not - perform any decompression: this will be done by subsequent calls of - inflate(). -*/ - -ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm)); -/* - Skips invalid compressed data until a full flush point (see above the - description of deflate with Z_FULL_FLUSH) can be found, or until all - available input is skipped. No output is provided. - - inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR - if no more input was provided, Z_DATA_ERROR if no flush point has been found, - or Z_STREAM_ERROR if the stream structure was inconsistent. In the success - case, the application may save the current current value of total_in which - indicates where valid compressed data was found. In the error case, the - application may repeatedly call inflateSync, providing more input each time, - until success or end of the input data. -*/ - -ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest, - z_streamp source)); -/* - Sets the destination stream as a complete copy of the source stream. - - This function can be useful when randomly accessing a large stream. The - first pass through the stream can periodically record the inflate state, - allowing restarting inflate at those points when randomly accessing the - stream. - - inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not - enough memory, Z_STREAM_ERROR if the source stream state was inconsistent - (such as zalloc being NULL). msg is left unchanged in both source and - destination. -*/ - -ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm)); -/* - This function is equivalent to inflateEnd followed by inflateInit, - but does not free and reallocate all the internal decompression state. - The stream will keep attributes that may have been set by inflateInit2. - - inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source - stream state was inconsistent (such as zalloc or state being NULL). -*/ - -ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm, - int bits, - int value)); -/* - This function inserts bits in the inflate input stream. The intent is - that this function is used to start inflating at a bit position in the - middle of a byte. The provided bits will be used before any bytes are used - from next_in. This function should only be used with raw inflate, and - should be used before the first inflate() call after inflateInit2() or - inflateReset(). bits must be less than or equal to 16, and that many of the - least significant bits of value will be inserted in the input. - - inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source - stream state was inconsistent. -*/ - -ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm, - gz_headerp head)); -/* - inflateGetHeader() requests that gzip header information be stored in the - provided gz_header structure. inflateGetHeader() may be called after - inflateInit2() or inflateReset(), and before the first call of inflate(). - As inflate() processes the gzip stream, head->done is zero until the header - is completed, at which time head->done is set to one. If a zlib stream is - being decoded, then head->done is set to -1 to indicate that there will be - no gzip header information forthcoming. Note that Z_BLOCK can be used to - force inflate() to return immediately after header processing is complete - and before any actual data is decompressed. - - The text, time, xflags, and os fields are filled in with the gzip header - contents. hcrc is set to true if there is a header CRC. (The header CRC - was valid if done is set to one.) If extra is not Z_NULL, then extra_max - contains the maximum number of bytes to write to extra. Once done is true, - extra_len contains the actual extra field length, and extra contains the - extra field, or that field truncated if extra_max is less than extra_len. - If name is not Z_NULL, then up to name_max characters are written there, - terminated with a zero unless the length is greater than name_max. If - comment is not Z_NULL, then up to comm_max characters are written there, - terminated with a zero unless the length is greater than comm_max. When - any of extra, name, or comment are not Z_NULL and the respective field is - not present in the header, then that field is set to Z_NULL to signal its - absence. This allows the use of deflateSetHeader() with the returned - structure to duplicate the header. However if those fields are set to - allocated memory, then the application will need to save those pointers - elsewhere so that they can be eventually freed. - - If inflateGetHeader is not used, then the header information is simply - discarded. The header is always checked for validity, including the header - CRC if present. inflateReset() will reset the process to discard the header - information. The application would need to call inflateGetHeader() again to - retrieve the header from the next gzip stream. - - inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source - stream state was inconsistent. -*/ - -/* -ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits, - unsigned char FAR *window)); - - Initialize the internal stream state for decompression using inflateBack() - calls. The fields zalloc, zfree and opaque in strm must be initialized - before the call. If zalloc and zfree are Z_NULL, then the default library- - derived memory allocation routines are used. windowBits is the base two - logarithm of the window size, in the range 8..15. window is a caller - supplied buffer of that size. Except for special applications where it is - assured that deflate was used with small window sizes, windowBits must be 15 - and a 32K byte window must be supplied to be able to decompress general - deflate streams. - - See inflateBack() for the usage of these routines. - - inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of - the paramaters are invalid, Z_MEM_ERROR if the internal state could not - be allocated, or Z_VERSION_ERROR if the version of the library does not - match the version of the header file. -*/ - -typedef unsigned (*in_func) OF((void FAR *, unsigned char FAR * FAR *)); -typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned)); - -ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm, - in_func in, void FAR *in_desc, - out_func out, void FAR *out_desc)); -/* - inflateBack() does a raw inflate with a single call using a call-back - interface for input and output. This is more efficient than inflate() for - file i/o applications in that it avoids copying between the output and the - sliding window by simply making the window itself the output buffer. This - function trusts the application to not change the output buffer passed by - the output function, at least until inflateBack() returns. - - inflateBackInit() must be called first to allocate the internal state - and to initialize the state with the user-provided window buffer. - inflateBack() may then be used multiple times to inflate a complete, raw - deflate stream with each call. inflateBackEnd() is then called to free - the allocated state. - - A raw deflate stream is one with no zlib or gzip header or trailer. - This routine would normally be used in a utility that reads zip or gzip - files and writes out uncompressed files. The utility would decode the - header and process the trailer on its own, hence this routine expects - only the raw deflate stream to decompress. This is different from the - normal behavior of inflate(), which expects either a zlib or gzip header and - trailer around the deflate stream. - - inflateBack() uses two subroutines supplied by the caller that are then - called by inflateBack() for input and output. inflateBack() calls those - routines until it reads a complete deflate stream and writes out all of the - uncompressed data, or until it encounters an error. The function's - parameters and return types are defined above in the in_func and out_func - typedefs. inflateBack() will call in(in_desc, &buf) which should return the - number of bytes of provided input, and a pointer to that input in buf. If - there is no input available, in() must return zero--buf is ignored in that - case--and inflateBack() will return a buffer error. inflateBack() will call - out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. out() - should return zero on success, or non-zero on failure. If out() returns - non-zero, inflateBack() will return with an error. Neither in() nor out() - are permitted to change the contents of the window provided to - inflateBackInit(), which is also the buffer that out() uses to write from. - The length written by out() will be at most the window size. Any non-zero - amount of input may be provided by in(). - - For convenience, inflateBack() can be provided input on the first call by - setting strm->next_in and strm->avail_in. If that input is exhausted, then - in() will be called. Therefore strm->next_in must be initialized before - calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called - immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in - must also be initialized, and then if strm->avail_in is not zero, input will - initially be taken from strm->next_in[0 .. strm->avail_in - 1]. - - The in_desc and out_desc parameters of inflateBack() is passed as the - first parameter of in() and out() respectively when they are called. These - descriptors can be optionally used to pass any information that the caller- - supplied in() and out() functions need to do their job. - - On return, inflateBack() will set strm->next_in and strm->avail_in to - pass back any unused input that was provided by the last in() call. The - return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR - if in() or out() returned an error, Z_DATA_ERROR if there was a format - error in the deflate stream (in which case strm->msg is set to indicate the - nature of the error), or Z_STREAM_ERROR if the stream was not properly - initialized. In the case of Z_BUF_ERROR, an input or output error can be - distinguished using strm->next_in which will be Z_NULL only if in() returned - an error. If strm->next is not Z_NULL, then the Z_BUF_ERROR was due to - out() returning non-zero. (in() will always be called before out(), so - strm->next_in is assured to be defined if out() returns non-zero.) Note - that inflateBack() cannot return Z_OK. -*/ - -ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm)); -/* - All memory allocated by inflateBackInit() is freed. - - inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream - state was inconsistent. -*/ - -ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void)); -/* Return flags indicating compile-time options. - - Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other: - 1.0: size of uInt - 3.2: size of uLong - 5.4: size of voidpf (pointer) - 7.6: size of z_off_t - - Compiler, assembler, and debug options: - 8: DEBUG - 9: ASMV or ASMINF -- use ASM code - 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention - 11: 0 (reserved) - - One-time table building (smaller code, but not thread-safe if true): - 12: BUILDFIXED -- build static block decoding tables when needed - 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed - 14,15: 0 (reserved) - - Library content (indicates missing functionality): - 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking - deflate code when not needed) - 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect - and decode gzip streams (to avoid linking crc code) - 18-19: 0 (reserved) - - Operation variations (changes in library functionality): - 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate - 21: FASTEST -- deflate algorithm with only one, lowest compression level - 22,23: 0 (reserved) - - The sprintf variant used by gzprintf (zero is best): - 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format - 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure! - 26: 0 = returns value, 1 = void -- 1 means inferred string length returned - - Remainder: - 27-31: 0 (reserved) - */ - - - /* utility functions */ - -/* - The following utility functions are implemented on top of the - basic stream-oriented functions. To simplify the interface, some - default options are assumed (compression level and memory usage, - standard memory allocation functions). The source code of these - utility functions can easily be modified if you need special options. -*/ - -ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen, - const Bytef *source, uLong sourceLen)); -/* - Compresses the source buffer into the destination buffer. sourceLen is - the byte length of the source buffer. Upon entry, destLen is the total - size of the destination buffer, which must be at least the value returned - by compressBound(sourceLen). Upon exit, destLen is the actual size of the - compressed buffer. - This function can be used to compress a whole file at once if the - input file is mmap'ed. - compress returns Z_OK if success, Z_MEM_ERROR if there was not - enough memory, Z_BUF_ERROR if there was not enough room in the output - buffer. -*/ - -ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen, - const Bytef *source, uLong sourceLen, - int level)); -/* - Compresses the source buffer into the destination buffer. The level - parameter has the same meaning as in deflateInit. sourceLen is the byte - length of the source buffer. Upon entry, destLen is the total size of the - destination buffer, which must be at least the value returned by - compressBound(sourceLen). Upon exit, destLen is the actual size of the - compressed buffer. - - compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough - memory, Z_BUF_ERROR if there was not enough room in the output buffer, - Z_STREAM_ERROR if the level parameter is invalid. -*/ - -ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen)); -/* - compressBound() returns an upper bound on the compressed size after - compress() or compress2() on sourceLen bytes. It would be used before - a compress() or compress2() call to allocate the destination buffer. -*/ - -ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen, - const Bytef *source, uLong sourceLen)); -/* - Decompresses the source buffer into the destination buffer. sourceLen is - the byte length of the source buffer. Upon entry, destLen is the total - size of the destination buffer, which must be large enough to hold the - entire uncompressed data. (The size of the uncompressed data must have - been saved previously by the compressor and transmitted to the decompressor - by some mechanism outside the scope of this compression library.) - Upon exit, destLen is the actual size of the compressed buffer. - This function can be used to decompress a whole file at once if the - input file is mmap'ed. - - uncompress returns Z_OK if success, Z_MEM_ERROR if there was not - enough memory, Z_BUF_ERROR if there was not enough room in the output - buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete. -*/ - - -typedef voidp gzFile; - -ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode)); -/* - Opens a gzip (.gz) file for reading or writing. The mode parameter - is as in fopen ("rb" or "wb") but can also include a compression level - ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for - Huffman only compression as in "wb1h", or 'R' for run-length encoding - as in "wb1R". (See the description of deflateInit2 for more information - about the strategy parameter.) - - gzopen can be used to read a file which is not in gzip format; in this - case gzread will directly read from the file without decompression. - - gzopen returns NULL if the file could not be opened or if there was - insufficient memory to allocate the (de)compression state; errno - can be checked to distinguish the two cases (if errno is zero, the - zlib error is Z_MEM_ERROR). */ - -ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode)); -/* - gzdopen() associates a gzFile with the file descriptor fd. File - descriptors are obtained from calls like open, dup, creat, pipe or - fileno (in the file has been previously opened with fopen). - The mode parameter is as in gzopen. - The next call of gzclose on the returned gzFile will also close the - file descriptor fd, just like fclose(fdopen(fd), mode) closes the file - descriptor fd. If you want to keep fd open, use gzdopen(dup(fd), mode). - gzdopen returns NULL if there was insufficient memory to allocate - the (de)compression state. -*/ - -ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy)); -/* - Dynamically update the compression level or strategy. See the description - of deflateInit2 for the meaning of these parameters. - gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not - opened for writing. -*/ - -ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len)); -/* - Reads the given number of uncompressed bytes from the compressed file. - If the input file was not in gzip format, gzread copies the given number - of bytes into the buffer. - gzread returns the number of uncompressed bytes actually read (0 for - end of file, -1 for error). */ - -ZEXTERN int ZEXPORT gzwrite OF((gzFile file, - voidpc buf, unsigned len)); -/* - Writes the given number of uncompressed bytes into the compressed file. - gzwrite returns the number of uncompressed bytes actually written - (0 in case of error). -*/ - -ZEXTERN int ZEXPORTVA gzprintf OF((gzFile file, const char *format, ...)); -/* - Converts, formats, and writes the args to the compressed file under - control of the format string, as in fprintf. gzprintf returns the number of - uncompressed bytes actually written (0 in case of error). The number of - uncompressed bytes written is limited to 4095. The caller should assure that - this limit is not exceeded. If it is exceeded, then gzprintf() will return - return an error (0) with nothing written. In this case, there may also be a - buffer overflow with unpredictable consequences, which is possible only if - zlib was compiled with the insecure functions sprintf() or vsprintf() - because the secure snprintf() or vsnprintf() functions were not available. -*/ - -ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s)); -/* - Writes the given null-terminated string to the compressed file, excluding - the terminating null character. - gzputs returns the number of characters written, or -1 in case of error. -*/ - -ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len)); -/* - Reads bytes from the compressed file until len-1 characters are read, or - a newline character is read and transferred to buf, or an end-of-file - condition is encountered. The string is then terminated with a null - character. - gzgets returns buf, or Z_NULL in case of error. -*/ - -ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c)); -/* - Writes c, converted to an unsigned char, into the compressed file. - gzputc returns the value that was written, or -1 in case of error. -*/ - -ZEXTERN int ZEXPORT gzgetc OF((gzFile file)); -/* - Reads one byte from the compressed file. gzgetc returns this byte - or -1 in case of end of file or error. -*/ - -ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file)); -/* - Push one character back onto the stream to be read again later. - Only one character of push-back is allowed. gzungetc() returns the - character pushed, or -1 on failure. gzungetc() will fail if a - character has been pushed but not read yet, or if c is -1. The pushed - character will be discarded if the stream is repositioned with gzseek() - or gzrewind(). -*/ - -ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush)); -/* - Flushes all pending output into the compressed file. The parameter - flush is as in the deflate() function. The return value is the zlib - error number (see function gzerror below). gzflush returns Z_OK if - the flush parameter is Z_FINISH and all output could be flushed. - gzflush should be called only when strictly necessary because it can - degrade compression. -*/ - -ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file, - z_off_t offset, int whence)); -/* - Sets the starting position for the next gzread or gzwrite on the - given compressed file. The offset represents a number of bytes in the - uncompressed data stream. The whence parameter is defined as in lseek(2); - the value SEEK_END is not supported. - If the file is opened for reading, this function is emulated but can be - extremely slow. If the file is opened for writing, only forward seeks are - supported; gzseek then compresses a sequence of zeroes up to the new - starting position. - - gzseek returns the resulting offset location as measured in bytes from - the beginning of the uncompressed stream, or -1 in case of error, in - particular if the file is opened for writing and the new starting position - would be before the current position. -*/ - -ZEXTERN int ZEXPORT gzrewind OF((gzFile file)); -/* - Rewinds the given file. This function is supported only for reading. - - gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET) -*/ - -ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file)); -/* - Returns the starting position for the next gzread or gzwrite on the - given compressed file. This position represents a number of bytes in the - uncompressed data stream. - - gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR) -*/ - -ZEXTERN int ZEXPORT gzeof OF((gzFile file)); -/* - Returns 1 when EOF has previously been detected reading the given - input stream, otherwise zero. -*/ - -ZEXTERN int ZEXPORT gzdirect OF((gzFile file)); -/* - Returns 1 if file is being read directly without decompression, otherwise - zero. -*/ - -ZEXTERN int ZEXPORT gzclose OF((gzFile file)); -/* - Flushes all pending output if necessary, closes the compressed file - and deallocates all the (de)compression state. The return value is the zlib - error number (see function gzerror below). -*/ - -ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum)); -/* - Returns the error message for the last error which occurred on the - given compressed file. errnum is set to zlib error number. If an - error occurred in the file system and not in the compression library, - errnum is set to Z_ERRNO and the application may consult errno - to get the exact error code. -*/ - -ZEXTERN void ZEXPORT gzclearerr OF((gzFile file)); -/* - Clears the error and end-of-file flags for file. This is analogous to the - clearerr() function in stdio. This is useful for continuing to read a gzip - file that is being written concurrently. -*/ - - /* checksum functions */ - -/* - These functions are not related to compression but are exported - anyway because they might be useful in applications using the - compression library. -*/ - -ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len)); -/* - Update a running Adler-32 checksum with the bytes buf[0..len-1] and - return the updated checksum. If buf is NULL, this function returns - the required initial value for the checksum. - An Adler-32 checksum is almost as reliable as a CRC32 but can be computed - much faster. Usage example: - - uLong adler = adler32(0L, Z_NULL, 0); - - while (read_buffer(buffer, length) != EOF) { - adler = adler32(adler, buffer, length); - } - if (adler != original_adler) error(); -*/ - -ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2, - z_off_t len2)); -/* - Combine two Adler-32 checksums into one. For two sequences of bytes, seq1 - and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for - each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of - seq1 and seq2 concatenated, requiring only adler1, adler2, and len2. -*/ - -ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len)); -/* - Update a running CRC-32 with the bytes buf[0..len-1] and return the - updated CRC-32. If buf is NULL, this function returns the required initial - value for the for the crc. Pre- and post-conditioning (one's complement) is - performed within this function so it shouldn't be done by the application. - Usage example: - - uLong crc = crc32(0L, Z_NULL, 0); - - while (read_buffer(buffer, length) != EOF) { - crc = crc32(crc, buffer, length); - } - if (crc != original_crc) error(); -*/ - -ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2)); - -/* - Combine two CRC-32 check values into one. For two sequences of bytes, - seq1 and seq2 with lengths len1 and len2, CRC-32 check values were - calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32 - check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and - len2. -*/ - - - /* various hacks, don't look :) */ - -/* deflateInit and inflateInit are macros to allow checking the zlib version - * and the compiler's view of z_stream: - */ -ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level, - const char *version, int stream_size)); -ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm, - const char *version, int stream_size)); -ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method, - int windowBits, int memLevel, - int strategy, const char *version, - int stream_size)); -ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits, - const char *version, int stream_size)); -ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits, - unsigned char FAR *window, - const char *version, - int stream_size)); -#define deflateInit(strm, level) \ - deflateInit_((strm), (level), ZLIB_VERSION, sizeof(z_stream)) -#define inflateInit(strm) \ - inflateInit_((strm), ZLIB_VERSION, sizeof(z_stream)) -#define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \ - deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\ - (strategy), ZLIB_VERSION, sizeof(z_stream)) -#define inflateInit2(strm, windowBits) \ - inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream)) -#define inflateBackInit(strm, windowBits, window) \ - inflateBackInit_((strm), (windowBits), (window), \ - ZLIB_VERSION, sizeof(z_stream)) - - -#if !defined(ZUTIL_H) && !defined(NO_DUMMY_DECL) - struct internal_state {int dummy;}; /* hack for buggy compilers */ -#endif - -ZEXTERN const char * ZEXPORT zError OF((int)); -ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp z)); -ZEXTERN const uLongf * ZEXPORT get_crc_table OF((void)); - -#ifdef __cplusplus -} -#endif - -#endif /* ZLIB_H */ +/* zlib.h -- interface of the 'zlib' general purpose compression library + version 1.2.3, July 18th, 2005 + + Copyright (C) 1995-2005 Jean-loup Gailly and Mark Adler + + 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. + + Jean-loup Gailly Mark Adler + jloup@gzip.org madler@alumni.caltech.edu + + + The data format used by the zlib library is described by RFCs (Request for + Comments) 1950 to 1952 in the files http://www.ietf.org/rfc/rfc1950.txt + (zlib format), rfc1951.txt (deflate format) and rfc1952.txt (gzip format). +*/ + +#ifndef ZLIB_H +#define ZLIB_H + +#include "zconf.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define ZLIB_VERSION "1.2.3" +#define ZLIB_VERNUM 0x1230 + +/* + The 'zlib' compression library provides in-memory compression and + decompression functions, including integrity checks of the uncompressed + data. This version of the library supports only one compression method + (deflation) but other algorithms will be added later and will have the same + stream interface. + + Compression can be done in a single step if the buffers are large + enough (for example if an input file is mmap'ed), or can be done by + repeated calls of the compression function. In the latter case, the + application must provide more input and/or consume the output + (providing more output space) before each call. + + The compressed data format used by default by the in-memory functions is + the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped + around a deflate stream, which is itself documented in RFC 1951. + + The library also supports reading and writing files in gzip (.gz) format + with an interface similar to that of stdio using the functions that start + with "gz". The gzip format is different from the zlib format. gzip is a + gzip wrapper, documented in RFC 1952, wrapped around a deflate stream. + + This library can optionally read and write gzip streams in memory as well. + + The zlib format was designed to be compact and fast for use in memory + and on communications channels. The gzip format was designed for single- + file compression on file systems, has a larger header than zlib to maintain + directory information, and uses a different, slower check method than zlib. + + The library does not install any signal handler. The decoder checks + the consistency of the compressed data, so the library should never + crash even in case of corrupted input. +*/ + +typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size)); +typedef void (*free_func) OF((voidpf opaque, voidpf address)); + +struct internal_state; + +typedef struct z_stream_s { + Bytef *next_in; /* next input byte */ + uInt avail_in; /* number of bytes available at next_in */ + uLong total_in; /* total nb of input bytes read so far */ + + Bytef *next_out; /* next output byte should be put there */ + uInt avail_out; /* remaining free space at next_out */ + uLong total_out; /* total nb of bytes output so far */ + + char *msg; /* last error message, NULL if no error */ + struct internal_state FAR *state; /* not visible by applications */ + + alloc_func zalloc; /* used to allocate the internal state */ + free_func zfree; /* used to free the internal state */ + voidpf opaque; /* private data object passed to zalloc and zfree */ + + int data_type; /* best guess about the data type: binary or text */ + uLong adler; /* adler32 value of the uncompressed data */ + uLong reserved; /* reserved for future use */ +} z_stream; + +typedef z_stream FAR *z_streamp; + +/* + gzip header information passed to and from zlib routines. See RFC 1952 + for more details on the meanings of these fields. +*/ +typedef struct gz_header_s { + int text; /* true if compressed data believed to be text */ + uLong time; /* modification time */ + int xflags; /* extra flags (not used when writing a gzip file) */ + int os; /* operating system */ + Bytef *extra; /* pointer to extra field or Z_NULL if none */ + uInt extra_len; /* extra field length (valid if extra != Z_NULL) */ + uInt extra_max; /* space at extra (only when reading header) */ + Bytef *name; /* pointer to zero-terminated file name or Z_NULL */ + uInt name_max; /* space at name (only when reading header) */ + Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */ + uInt comm_max; /* space at comment (only when reading header) */ + int hcrc; /* true if there was or will be a header crc */ + int done; /* true when done reading gzip header (not used + when writing a gzip file) */ +} gz_header; + +typedef gz_header FAR *gz_headerp; + +/* + The application must update next_in and avail_in when avail_in has + dropped to zero. It must update next_out and avail_out when avail_out + has dropped to zero. The application must initialize zalloc, zfree and + opaque before calling the init function. All other fields are set by the + compression library and must not be updated by the application. + + The opaque value provided by the application will be passed as the first + parameter for calls of zalloc and zfree. This can be useful for custom + memory management. The compression library attaches no meaning to the + opaque value. + + zalloc must return Z_NULL if there is not enough memory for the object. + If zlib is used in a multi-threaded application, zalloc and zfree must be + thread safe. + + On 16-bit systems, the functions zalloc and zfree must be able to allocate + exactly 65536 bytes, but will not be required to allocate more than this + if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS, + pointers returned by zalloc for objects of exactly 65536 bytes *must* + have their offset normalized to zero. The default allocation function + provided by this library ensures this (see zutil.c). To reduce memory + requirements and avoid any allocation of 64K objects, at the expense of + compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h). + + The fields total_in and total_out can be used for statistics or + progress reports. After compression, total_in holds the total size of + the uncompressed data and may be saved for use in the decompressor + (particularly if the decompressor wants to decompress everything in + a single step). +*/ + + /* constants */ + +#define Z_NO_FLUSH 0 +#define Z_PARTIAL_FLUSH 1 /* will be removed, use Z_SYNC_FLUSH instead */ +#define Z_SYNC_FLUSH 2 +#define Z_FULL_FLUSH 3 +#define Z_FINISH 4 +#define Z_BLOCK 5 +/* Allowed flush values; see deflate() and inflate() below for details */ + +#define Z_OK 0 +#define Z_STREAM_END 1 +#define Z_NEED_DICT 2 +#define Z_ERRNO (-1) +#define Z_STREAM_ERROR (-2) +#define Z_DATA_ERROR (-3) +#define Z_MEM_ERROR (-4) +#define Z_BUF_ERROR (-5) +#define Z_VERSION_ERROR (-6) +/* Return codes for the compression/decompression functions. Negative + * values are errors, positive values are used for special but normal events. + */ + +#define Z_NO_COMPRESSION 0 +#define Z_BEST_SPEED 1 +#define Z_BEST_COMPRESSION 9 +#define Z_DEFAULT_COMPRESSION (-1) +/* compression levels */ + +#define Z_FILTERED 1 +#define Z_HUFFMAN_ONLY 2 +#define Z_RLE 3 +#define Z_FIXED 4 +#define Z_DEFAULT_STRATEGY 0 +/* compression strategy; see deflateInit2() below for details */ + +#define Z_BINARY 0 +#define Z_TEXT 1 +#define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */ +#define Z_UNKNOWN 2 +/* Possible values of the data_type field (though see inflate()) */ + +#define Z_DEFLATED 8 +/* The deflate compression method (the only one supported in this version) */ + +#define Z_NULL 0 /* for initializing zalloc, zfree, opaque */ + +#define zlib_version zlibVersion() +/* for compatibility with versions < 1.0.2 */ + + /* basic functions */ + +ZEXTERN const char * ZEXPORT zlibVersion OF((void)); +/* The application can compare zlibVersion and ZLIB_VERSION for consistency. + If the first character differs, the library code actually used is + not compatible with the zlib.h header file used by the application. + This check is automatically made by deflateInit and inflateInit. + */ + +/* +ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level)); + + Initializes the internal stream state for compression. The fields + zalloc, zfree and opaque must be initialized before by the caller. + If zalloc and zfree are set to Z_NULL, deflateInit updates them to + use default allocation functions. + + The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9: + 1 gives best speed, 9 gives best compression, 0 gives no compression at + all (the input data is simply copied a block at a time). + Z_DEFAULT_COMPRESSION requests a default compromise between speed and + compression (currently equivalent to level 6). + + deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_STREAM_ERROR if level is not a valid compression level, + Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible + with the version assumed by the caller (ZLIB_VERSION). + msg is set to null if there is no error message. deflateInit does not + perform any compression: this will be done by deflate(). +*/ + + +ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush)); +/* + deflate compresses as much data as possible, and stops when the input + buffer becomes empty or the output buffer becomes full. It may introduce some + output latency (reading input without producing any output) except when + forced to flush. + + The detailed semantics are as follows. deflate performs one or both of the + following actions: + + - Compress more input starting at next_in and update next_in and avail_in + accordingly. If not all input can be processed (because there is not + enough room in the output buffer), next_in and avail_in are updated and + processing will resume at this point for the next call of deflate(). + + - Provide more output starting at next_out and update next_out and avail_out + accordingly. This action is forced if the parameter flush is non zero. + Forcing flush frequently degrades the compression ratio, so this parameter + should be set only when necessary (in interactive applications). + Some output may be provided even if flush is not set. + + Before the call of deflate(), the application should ensure that at least + one of the actions is possible, by providing more input and/or consuming + more output, and updating avail_in or avail_out accordingly; avail_out + should never be zero before the call. The application can consume the + compressed output when it wants, for example when the output buffer is full + (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK + and with zero avail_out, it must be called again after making room in the + output buffer because there might be more output pending. + + Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to + decide how much data to accumualte before producing output, in order to + maximize compression. + + If the parameter flush is set to Z_SYNC_FLUSH, all pending output is + flushed to the output buffer and the output is aligned on a byte boundary, so + that the decompressor can get all input data available so far. (In particular + avail_in is zero after the call if enough output space has been provided + before the call.) Flushing may degrade compression for some compression + algorithms and so it should be used only when necessary. + + If flush is set to Z_FULL_FLUSH, all output is flushed as with + Z_SYNC_FLUSH, and the compression state is reset so that decompression can + restart from this point if previous compressed data has been damaged or if + random access is desired. Using Z_FULL_FLUSH too often can seriously degrade + compression. + + If deflate returns with avail_out == 0, this function must be called again + with the same value of the flush parameter and more output space (updated + avail_out), until the flush is complete (deflate returns with non-zero + avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that + avail_out is greater than six to avoid repeated flush markers due to + avail_out == 0 on return. + + If the parameter flush is set to Z_FINISH, pending input is processed, + pending output is flushed and deflate returns with Z_STREAM_END if there + was enough output space; if deflate returns with Z_OK, this function must be + called again with Z_FINISH and more output space (updated avail_out) but no + more input data, until it returns with Z_STREAM_END or an error. After + deflate has returned Z_STREAM_END, the only possible operations on the + stream are deflateReset or deflateEnd. + + Z_FINISH can be used immediately after deflateInit if all the compression + is to be done in a single step. In this case, avail_out must be at least + the value returned by deflateBound (see below). If deflate does not return + Z_STREAM_END, then it must be called again as described above. + + deflate() sets strm->adler to the adler32 checksum of all input read + so far (that is, total_in bytes). + + deflate() may update strm->data_type if it can make a good guess about + the input data type (Z_BINARY or Z_TEXT). In doubt, the data is considered + binary. This field is only for information purposes and does not affect + the compression algorithm in any manner. + + deflate() returns Z_OK if some progress has been made (more input + processed or more output produced), Z_STREAM_END if all input has been + consumed and all output has been produced (only when flush is set to + Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example + if next_in or next_out was NULL), Z_BUF_ERROR if no progress is possible + (for example avail_in or avail_out was zero). Note that Z_BUF_ERROR is not + fatal, and deflate() can be called again with more input and more output + space to continue compressing. +*/ + + +ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm)); +/* + All dynamically allocated data structures for this stream are freed. + This function discards any unprocessed input and does not flush any + pending output. + + deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the + stream state was inconsistent, Z_DATA_ERROR if the stream was freed + prematurely (some input or output was discarded). In the error case, + msg may be set but then points to a static string (which must not be + deallocated). +*/ + + +/* +ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm)); + + Initializes the internal stream state for decompression. The fields + next_in, avail_in, zalloc, zfree and opaque must be initialized before by + the caller. If next_in is not Z_NULL and avail_in is large enough (the exact + value depends on the compression method), inflateInit determines the + compression method from the zlib header and allocates all data structures + accordingly; otherwise the allocation will be deferred to the first call of + inflate. If zalloc and zfree are set to Z_NULL, inflateInit updates them to + use default allocation functions. + + inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_VERSION_ERROR if the zlib library version is incompatible with the + version assumed by the caller. msg is set to null if there is no error + message. inflateInit does not perform any decompression apart from reading + the zlib header if present: this will be done by inflate(). (So next_in and + avail_in may be modified, but next_out and avail_out are unchanged.) +*/ + + +ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush)); +/* + inflate decompresses as much data as possible, and stops when the input + buffer becomes empty or the output buffer becomes full. It may introduce + some output latency (reading input without producing any output) except when + forced to flush. + + The detailed semantics are as follows. inflate performs one or both of the + following actions: + + - Decompress more input starting at next_in and update next_in and avail_in + accordingly. If not all input can be processed (because there is not + enough room in the output buffer), next_in is updated and processing + will resume at this point for the next call of inflate(). + + - Provide more output starting at next_out and update next_out and avail_out + accordingly. inflate() provides as much output as possible, until there + is no more input data or no more space in the output buffer (see below + about the flush parameter). + + Before the call of inflate(), the application should ensure that at least + one of the actions is possible, by providing more input and/or consuming + more output, and updating the next_* and avail_* values accordingly. + The application can consume the uncompressed output when it wants, for + example when the output buffer is full (avail_out == 0), or after each + call of inflate(). If inflate returns Z_OK and with zero avail_out, it + must be called again after making room in the output buffer because there + might be more output pending. + + The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH, + Z_FINISH, or Z_BLOCK. Z_SYNC_FLUSH requests that inflate() flush as much + output as possible to the output buffer. Z_BLOCK requests that inflate() stop + if and when it gets to the next deflate block boundary. When decoding the + zlib or gzip format, this will cause inflate() to return immediately after + the header and before the first block. When doing a raw inflate, inflate() + will go ahead and process the first block, and will return when it gets to + the end of that block, or when it runs out of data. + + The Z_BLOCK option assists in appending to or combining deflate streams. + Also to assist in this, on return inflate() will set strm->data_type to the + number of unused bits in the last byte taken from strm->next_in, plus 64 + if inflate() is currently decoding the last block in the deflate stream, + plus 128 if inflate() returned immediately after decoding an end-of-block + code or decoding the complete header up to just before the first byte of the + deflate stream. The end-of-block will not be indicated until all of the + uncompressed data from that block has been written to strm->next_out. The + number of unused bits may in general be greater than seven, except when + bit 7 of data_type is set, in which case the number of unused bits will be + less than eight. + + inflate() should normally be called until it returns Z_STREAM_END or an + error. However if all decompression is to be performed in a single step + (a single call of inflate), the parameter flush should be set to + Z_FINISH. In this case all pending input is processed and all pending + output is flushed; avail_out must be large enough to hold all the + uncompressed data. (The size of the uncompressed data may have been saved + by the compressor for this purpose.) The next operation on this stream must + be inflateEnd to deallocate the decompression state. The use of Z_FINISH + is never required, but can be used to inform inflate that a faster approach + may be used for the single inflate() call. + + In this implementation, inflate() always flushes as much output as + possible to the output buffer, and always uses the faster approach on the + first call. So the only effect of the flush parameter in this implementation + is on the return value of inflate(), as noted below, or when it returns early + because Z_BLOCK is used. + + If a preset dictionary is needed after this call (see inflateSetDictionary + below), inflate sets strm->adler to the adler32 checksum of the dictionary + chosen by the compressor and returns Z_NEED_DICT; otherwise it sets + strm->adler to the adler32 checksum of all output produced so far (that is, + total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described + below. At the end of the stream, inflate() checks that its computed adler32 + checksum is equal to that saved by the compressor and returns Z_STREAM_END + only if the checksum is correct. + + inflate() will decompress and check either zlib-wrapped or gzip-wrapped + deflate data. The header type is detected automatically. Any information + contained in the gzip header is not retained, so applications that need that + information should instead use raw inflate, see inflateInit2() below, or + inflateBack() and perform their own processing of the gzip header and + trailer. + + inflate() returns Z_OK if some progress has been made (more input processed + or more output produced), Z_STREAM_END if the end of the compressed data has + been reached and all uncompressed output has been produced, Z_NEED_DICT if a + preset dictionary is needed at this point, Z_DATA_ERROR if the input data was + corrupted (input stream not conforming to the zlib format or incorrect check + value), Z_STREAM_ERROR if the stream structure was inconsistent (for example + if next_in or next_out was NULL), Z_MEM_ERROR if there was not enough memory, + Z_BUF_ERROR if no progress is possible or if there was not enough room in the + output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and + inflate() can be called again with more input and more output space to + continue decompressing. If Z_DATA_ERROR is returned, the application may then + call inflateSync() to look for a good compression block if a partial recovery + of the data is desired. +*/ + + +ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm)); +/* + All dynamically allocated data structures for this stream are freed. + This function discards any unprocessed input and does not flush any + pending output. + + inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state + was inconsistent. In the error case, msg may be set but then points to a + static string (which must not be deallocated). +*/ + + /* Advanced functions */ + +/* + The following functions are needed only in some special applications. +*/ + +/* +ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm, + int level, + int method, + int windowBits, + int memLevel, + int strategy)); + + This is another version of deflateInit with more compression options. The + fields next_in, zalloc, zfree and opaque must be initialized before by + the caller. + + The method parameter is the compression method. It must be Z_DEFLATED in + this version of the library. + + The windowBits parameter is the base two logarithm of the window size + (the size of the history buffer). It should be in the range 8..15 for this + version of the library. Larger values of this parameter result in better + compression at the expense of memory usage. The default value is 15 if + deflateInit is used instead. + + windowBits can also be -8..-15 for raw deflate. In this case, -windowBits + determines the window size. deflate() will then generate raw deflate data + with no zlib header or trailer, and will not compute an adler32 check value. + + windowBits can also be greater than 15 for optional gzip encoding. Add + 16 to windowBits to write a simple gzip header and trailer around the + compressed data instead of a zlib wrapper. The gzip header will have no + file name, no extra data, no comment, no modification time (set to zero), + no header crc, and the operating system will be set to 255 (unknown). If a + gzip stream is being written, strm->adler is a crc32 instead of an adler32. + + The memLevel parameter specifies how much memory should be allocated + for the internal compression state. memLevel=1 uses minimum memory but + is slow and reduces compression ratio; memLevel=9 uses maximum memory + for optimal speed. The default value is 8. See zconf.h for total memory + usage as a function of windowBits and memLevel. + + The strategy parameter is used to tune the compression algorithm. Use the + value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a + filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no + string match), or Z_RLE to limit match distances to one (run-length + encoding). Filtered data consists mostly of small values with a somewhat + random distribution. In this case, the compression algorithm is tuned to + compress them better. The effect of Z_FILTERED is to force more Huffman + coding and less string matching; it is somewhat intermediate between + Z_DEFAULT and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as fast as + Z_HUFFMAN_ONLY, but give better compression for PNG image data. The strategy + parameter only affects the compression ratio but not the correctness of the + compressed output even if it is not set appropriately. Z_FIXED prevents the + use of dynamic Huffman codes, allowing for a simpler decoder for special + applications. + + deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_STREAM_ERROR if a parameter is invalid (such as an invalid + method). msg is set to null if there is no error message. deflateInit2 does + not perform any compression: this will be done by deflate(). +*/ + +ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm, + const Bytef *dictionary, + uInt dictLength)); +/* + Initializes the compression dictionary from the given byte sequence + without producing any compressed output. This function must be called + immediately after deflateInit, deflateInit2 or deflateReset, before any + call of deflate. The compressor and decompressor must use exactly the same + dictionary (see inflateSetDictionary). + + The dictionary should consist of strings (byte sequences) that are likely + to be encountered later in the data to be compressed, with the most commonly + used strings preferably put towards the end of the dictionary. Using a + dictionary is most useful when the data to be compressed is short and can be + predicted with good accuracy; the data can then be compressed better than + with the default empty dictionary. + + Depending on the size of the compression data structures selected by + deflateInit or deflateInit2, a part of the dictionary may in effect be + discarded, for example if the dictionary is larger than the window size in + deflate or deflate2. Thus the strings most likely to be useful should be + put at the end of the dictionary, not at the front. In addition, the + current implementation of deflate will use at most the window size minus + 262 bytes of the provided dictionary. + + Upon return of this function, strm->adler is set to the adler32 value + of the dictionary; the decompressor may later use this value to determine + which dictionary has been used by the compressor. (The adler32 value + applies to the whole dictionary even if only a subset of the dictionary is + actually used by the compressor.) If a raw deflate was requested, then the + adler32 value is not computed and strm->adler is not set. + + deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a + parameter is invalid (such as NULL dictionary) or the stream state is + inconsistent (for example if deflate has already been called for this stream + or if the compression method is bsort). deflateSetDictionary does not + perform any compression: this will be done by deflate(). +*/ + +ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest, + z_streamp source)); +/* + Sets the destination stream as a complete copy of the source stream. + + This function can be useful when several compression strategies will be + tried, for example when there are several ways of pre-processing the input + data with a filter. The streams that will be discarded should then be freed + by calling deflateEnd. Note that deflateCopy duplicates the internal + compression state which can be quite large, so this strategy is slow and + can consume lots of memory. + + deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_STREAM_ERROR if the source stream state was inconsistent + (such as zalloc being NULL). msg is left unchanged in both source and + destination. +*/ + +ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm)); +/* + This function is equivalent to deflateEnd followed by deflateInit, + but does not free and reallocate all the internal compression state. + The stream will keep the same compression level and any other attributes + that may have been set by deflateInit2. + + deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent (such as zalloc or state being NULL). +*/ + +ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm, + int level, + int strategy)); +/* + Dynamically update the compression level and compression strategy. The + interpretation of level and strategy is as in deflateInit2. This can be + used to switch between compression and straight copy of the input data, or + to switch to a different kind of input data requiring a different + strategy. If the compression level is changed, the input available so far + is compressed with the old level (and may be flushed); the new level will + take effect only at the next call of deflate(). + + Before the call of deflateParams, the stream state must be set as for + a call of deflate(), since the currently available input may have to + be compressed and flushed. In particular, strm->avail_out must be non-zero. + + deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source + stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR + if strm->avail_out was zero. +*/ + +ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm, + int good_length, + int max_lazy, + int nice_length, + int max_chain)); +/* + Fine tune deflate's internal compression parameters. This should only be + used by someone who understands the algorithm used by zlib's deflate for + searching for the best matching string, and even then only by the most + fanatic optimizer trying to squeeze out the last compressed bit for their + specific input data. Read the deflate.c source code for the meaning of the + max_lazy, good_length, nice_length, and max_chain parameters. + + deflateTune() can be called after deflateInit() or deflateInit2(), and + returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream. + */ + +ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm, + uLong sourceLen)); +/* + deflateBound() returns an upper bound on the compressed size after + deflation of sourceLen bytes. It must be called after deflateInit() + or deflateInit2(). This would be used to allocate an output buffer + for deflation in a single pass, and so would be called before deflate(). +*/ + +ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm, + int bits, + int value)); +/* + deflatePrime() inserts bits in the deflate output stream. The intent + is that this function is used to start off the deflate output with the + bits leftover from a previous deflate stream when appending to it. As such, + this function can only be used for raw deflate, and must be used before the + first deflate() call after a deflateInit2() or deflateReset(). bits must be + less than or equal to 16, and that many of the least significant bits of + value will be inserted in the output. + + deflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent. +*/ + +ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm, + gz_headerp head)); +/* + deflateSetHeader() provides gzip header information for when a gzip + stream is requested by deflateInit2(). deflateSetHeader() may be called + after deflateInit2() or deflateReset() and before the first call of + deflate(). The text, time, os, extra field, name, and comment information + in the provided gz_header structure are written to the gzip header (xflag is + ignored -- the extra flags are set according to the compression level). The + caller must assure that, if not Z_NULL, name and comment are terminated with + a zero byte, and that if extra is not Z_NULL, that extra_len bytes are + available there. If hcrc is true, a gzip header crc is included. Note that + the current versions of the command-line version of gzip (up through version + 1.3.x) do not support header crc's, and will report that it is a "multi-part + gzip file" and give up. + + If deflateSetHeader is not used, the default gzip header has text false, + the time set to zero, and os set to 255, with no extra, name, or comment + fields. The gzip header is returned to the default state by deflateReset(). + + deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent. +*/ + +/* +ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm, + int windowBits)); + + This is another version of inflateInit with an extra parameter. The + fields next_in, avail_in, zalloc, zfree and opaque must be initialized + before by the caller. + + The windowBits parameter is the base two logarithm of the maximum window + size (the size of the history buffer). It should be in the range 8..15 for + this version of the library. The default value is 15 if inflateInit is used + instead. windowBits must be greater than or equal to the windowBits value + provided to deflateInit2() while compressing, or it must be equal to 15 if + deflateInit2() was not used. If a compressed stream with a larger window + size is given as input, inflate() will return with the error code + Z_DATA_ERROR instead of trying to allocate a larger window. + + windowBits can also be -8..-15 for raw inflate. In this case, -windowBits + determines the window size. inflate() will then process raw deflate data, + not looking for a zlib or gzip header, not generating a check value, and not + looking for any check values for comparison at the end of the stream. This + is for use with other formats that use the deflate compressed data format + such as zip. Those formats provide their own check values. If a custom + format is developed using the raw deflate format for compressed data, it is + recommended that a check value such as an adler32 or a crc32 be applied to + the uncompressed data as is done in the zlib, gzip, and zip formats. For + most applications, the zlib format should be used as is. Note that comments + above on the use in deflateInit2() applies to the magnitude of windowBits. + + windowBits can also be greater than 15 for optional gzip decoding. Add + 32 to windowBits to enable zlib and gzip decoding with automatic header + detection, or add 16 to decode only the gzip format (the zlib format will + return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is + a crc32 instead of an adler32. + + inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_STREAM_ERROR if a parameter is invalid (such as a null strm). msg + is set to null if there is no error message. inflateInit2 does not perform + any decompression apart from reading the zlib header if present: this will + be done by inflate(). (So next_in and avail_in may be modified, but next_out + and avail_out are unchanged.) +*/ + +ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm, + const Bytef *dictionary, + uInt dictLength)); +/* + Initializes the decompression dictionary from the given uncompressed byte + sequence. This function must be called immediately after a call of inflate, + if that call returned Z_NEED_DICT. The dictionary chosen by the compressor + can be determined from the adler32 value returned by that call of inflate. + The compressor and decompressor must use exactly the same dictionary (see + deflateSetDictionary). For raw inflate, this function can be called + immediately after inflateInit2() or inflateReset() and before any call of + inflate() to set the dictionary. The application must insure that the + dictionary that was used for compression is provided. + + inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a + parameter is invalid (such as NULL dictionary) or the stream state is + inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the + expected one (incorrect adler32 value). inflateSetDictionary does not + perform any decompression: this will be done by subsequent calls of + inflate(). +*/ + +ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm)); +/* + Skips invalid compressed data until a full flush point (see above the + description of deflate with Z_FULL_FLUSH) can be found, or until all + available input is skipped. No output is provided. + + inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR + if no more input was provided, Z_DATA_ERROR if no flush point has been found, + or Z_STREAM_ERROR if the stream structure was inconsistent. In the success + case, the application may save the current current value of total_in which + indicates where valid compressed data was found. In the error case, the + application may repeatedly call inflateSync, providing more input each time, + until success or end of the input data. +*/ + +ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest, + z_streamp source)); +/* + Sets the destination stream as a complete copy of the source stream. + + This function can be useful when randomly accessing a large stream. The + first pass through the stream can periodically record the inflate state, + allowing restarting inflate at those points when randomly accessing the + stream. + + inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_STREAM_ERROR if the source stream state was inconsistent + (such as zalloc being NULL). msg is left unchanged in both source and + destination. +*/ + +ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm)); +/* + This function is equivalent to inflateEnd followed by inflateInit, + but does not free and reallocate all the internal decompression state. + The stream will keep attributes that may have been set by inflateInit2. + + inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent (such as zalloc or state being NULL). +*/ + +ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm, + int bits, + int value)); +/* + This function inserts bits in the inflate input stream. The intent is + that this function is used to start inflating at a bit position in the + middle of a byte. The provided bits will be used before any bytes are used + from next_in. This function should only be used with raw inflate, and + should be used before the first inflate() call after inflateInit2() or + inflateReset(). bits must be less than or equal to 16, and that many of the + least significant bits of value will be inserted in the input. + + inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent. +*/ + +ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm, + gz_headerp head)); +/* + inflateGetHeader() requests that gzip header information be stored in the + provided gz_header structure. inflateGetHeader() may be called after + inflateInit2() or inflateReset(), and before the first call of inflate(). + As inflate() processes the gzip stream, head->done is zero until the header + is completed, at which time head->done is set to one. If a zlib stream is + being decoded, then head->done is set to -1 to indicate that there will be + no gzip header information forthcoming. Note that Z_BLOCK can be used to + force inflate() to return immediately after header processing is complete + and before any actual data is decompressed. + + The text, time, xflags, and os fields are filled in with the gzip header + contents. hcrc is set to true if there is a header CRC. (The header CRC + was valid if done is set to one.) If extra is not Z_NULL, then extra_max + contains the maximum number of bytes to write to extra. Once done is true, + extra_len contains the actual extra field length, and extra contains the + extra field, or that field truncated if extra_max is less than extra_len. + If name is not Z_NULL, then up to name_max characters are written there, + terminated with a zero unless the length is greater than name_max. If + comment is not Z_NULL, then up to comm_max characters are written there, + terminated with a zero unless the length is greater than comm_max. When + any of extra, name, or comment are not Z_NULL and the respective field is + not present in the header, then that field is set to Z_NULL to signal its + absence. This allows the use of deflateSetHeader() with the returned + structure to duplicate the header. However if those fields are set to + allocated memory, then the application will need to save those pointers + elsewhere so that they can be eventually freed. + + If inflateGetHeader is not used, then the header information is simply + discarded. The header is always checked for validity, including the header + CRC if present. inflateReset() will reset the process to discard the header + information. The application would need to call inflateGetHeader() again to + retrieve the header from the next gzip stream. + + inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent. +*/ + +/* +ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits, + unsigned char FAR *window)); + + Initialize the internal stream state for decompression using inflateBack() + calls. The fields zalloc, zfree and opaque in strm must be initialized + before the call. If zalloc and zfree are Z_NULL, then the default library- + derived memory allocation routines are used. windowBits is the base two + logarithm of the window size, in the range 8..15. window is a caller + supplied buffer of that size. Except for special applications where it is + assured that deflate was used with small window sizes, windowBits must be 15 + and a 32K byte window must be supplied to be able to decompress general + deflate streams. + + See inflateBack() for the usage of these routines. + + inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of + the paramaters are invalid, Z_MEM_ERROR if the internal state could not + be allocated, or Z_VERSION_ERROR if the version of the library does not + match the version of the header file. +*/ + +typedef unsigned (*in_func) OF((void FAR *, unsigned char FAR * FAR *)); +typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned)); + +ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm, + in_func in, void FAR *in_desc, + out_func out, void FAR *out_desc)); +/* + inflateBack() does a raw inflate with a single call using a call-back + interface for input and output. This is more efficient than inflate() for + file i/o applications in that it avoids copying between the output and the + sliding window by simply making the window itself the output buffer. This + function trusts the application to not change the output buffer passed by + the output function, at least until inflateBack() returns. + + inflateBackInit() must be called first to allocate the internal state + and to initialize the state with the user-provided window buffer. + inflateBack() may then be used multiple times to inflate a complete, raw + deflate stream with each call. inflateBackEnd() is then called to free + the allocated state. + + A raw deflate stream is one with no zlib or gzip header or trailer. + This routine would normally be used in a utility that reads zip or gzip + files and writes out uncompressed files. The utility would decode the + header and process the trailer on its own, hence this routine expects + only the raw deflate stream to decompress. This is different from the + normal behavior of inflate(), which expects either a zlib or gzip header and + trailer around the deflate stream. + + inflateBack() uses two subroutines supplied by the caller that are then + called by inflateBack() for input and output. inflateBack() calls those + routines until it reads a complete deflate stream and writes out all of the + uncompressed data, or until it encounters an error. The function's + parameters and return types are defined above in the in_func and out_func + typedefs. inflateBack() will call in(in_desc, &buf) which should return the + number of bytes of provided input, and a pointer to that input in buf. If + there is no input available, in() must return zero--buf is ignored in that + case--and inflateBack() will return a buffer error. inflateBack() will call + out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. out() + should return zero on success, or non-zero on failure. If out() returns + non-zero, inflateBack() will return with an error. Neither in() nor out() + are permitted to change the contents of the window provided to + inflateBackInit(), which is also the buffer that out() uses to write from. + The length written by out() will be at most the window size. Any non-zero + amount of input may be provided by in(). + + For convenience, inflateBack() can be provided input on the first call by + setting strm->next_in and strm->avail_in. If that input is exhausted, then + in() will be called. Therefore strm->next_in must be initialized before + calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called + immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in + must also be initialized, and then if strm->avail_in is not zero, input will + initially be taken from strm->next_in[0 .. strm->avail_in - 1]. + + The in_desc and out_desc parameters of inflateBack() is passed as the + first parameter of in() and out() respectively when they are called. These + descriptors can be optionally used to pass any information that the caller- + supplied in() and out() functions need to do their job. + + On return, inflateBack() will set strm->next_in and strm->avail_in to + pass back any unused input that was provided by the last in() call. The + return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR + if in() or out() returned an error, Z_DATA_ERROR if there was a format + error in the deflate stream (in which case strm->msg is set to indicate the + nature of the error), or Z_STREAM_ERROR if the stream was not properly + initialized. In the case of Z_BUF_ERROR, an input or output error can be + distinguished using strm->next_in which will be Z_NULL only if in() returned + an error. If strm->next is not Z_NULL, then the Z_BUF_ERROR was due to + out() returning non-zero. (in() will always be called before out(), so + strm->next_in is assured to be defined if out() returns non-zero.) Note + that inflateBack() cannot return Z_OK. +*/ + +ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm)); +/* + All memory allocated by inflateBackInit() is freed. + + inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream + state was inconsistent. +*/ + +ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void)); +/* Return flags indicating compile-time options. + + Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other: + 1.0: size of uInt + 3.2: size of uLong + 5.4: size of voidpf (pointer) + 7.6: size of z_off_t + + Compiler, assembler, and debug options: + 8: DEBUG + 9: ASMV or ASMINF -- use ASM code + 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention + 11: 0 (reserved) + + One-time table building (smaller code, but not thread-safe if true): + 12: BUILDFIXED -- build static block decoding tables when needed + 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed + 14,15: 0 (reserved) + + Library content (indicates missing functionality): + 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking + deflate code when not needed) + 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect + and decode gzip streams (to avoid linking crc code) + 18-19: 0 (reserved) + + Operation variations (changes in library functionality): + 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate + 21: FASTEST -- deflate algorithm with only one, lowest compression level + 22,23: 0 (reserved) + + The sprintf variant used by gzprintf (zero is best): + 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format + 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure! + 26: 0 = returns value, 1 = void -- 1 means inferred string length returned + + Remainder: + 27-31: 0 (reserved) + */ + + + /* utility functions */ + +/* + The following utility functions are implemented on top of the + basic stream-oriented functions. To simplify the interface, some + default options are assumed (compression level and memory usage, + standard memory allocation functions). The source code of these + utility functions can easily be modified if you need special options. +*/ + +ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen, + const Bytef *source, uLong sourceLen)); +/* + Compresses the source buffer into the destination buffer. sourceLen is + the byte length of the source buffer. Upon entry, destLen is the total + size of the destination buffer, which must be at least the value returned + by compressBound(sourceLen). Upon exit, destLen is the actual size of the + compressed buffer. + This function can be used to compress a whole file at once if the + input file is mmap'ed. + compress returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_BUF_ERROR if there was not enough room in the output + buffer. +*/ + +ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen, + const Bytef *source, uLong sourceLen, + int level)); +/* + Compresses the source buffer into the destination buffer. The level + parameter has the same meaning as in deflateInit. sourceLen is the byte + length of the source buffer. Upon entry, destLen is the total size of the + destination buffer, which must be at least the value returned by + compressBound(sourceLen). Upon exit, destLen is the actual size of the + compressed buffer. + + compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_BUF_ERROR if there was not enough room in the output buffer, + Z_STREAM_ERROR if the level parameter is invalid. +*/ + +ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen)); +/* + compressBound() returns an upper bound on the compressed size after + compress() or compress2() on sourceLen bytes. It would be used before + a compress() or compress2() call to allocate the destination buffer. +*/ + +ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen, + const Bytef *source, uLong sourceLen)); +/* + Decompresses the source buffer into the destination buffer. sourceLen is + the byte length of the source buffer. Upon entry, destLen is the total + size of the destination buffer, which must be large enough to hold the + entire uncompressed data. (The size of the uncompressed data must have + been saved previously by the compressor and transmitted to the decompressor + by some mechanism outside the scope of this compression library.) + Upon exit, destLen is the actual size of the compressed buffer. + This function can be used to decompress a whole file at once if the + input file is mmap'ed. + + uncompress returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_BUF_ERROR if there was not enough room in the output + buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete. +*/ + + +typedef voidp gzFile; + +ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode)); +/* + Opens a gzip (.gz) file for reading or writing. The mode parameter + is as in fopen ("rb" or "wb") but can also include a compression level + ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for + Huffman only compression as in "wb1h", or 'R' for run-length encoding + as in "wb1R". (See the description of deflateInit2 for more information + about the strategy parameter.) + + gzopen can be used to read a file which is not in gzip format; in this + case gzread will directly read from the file without decompression. + + gzopen returns NULL if the file could not be opened or if there was + insufficient memory to allocate the (de)compression state; errno + can be checked to distinguish the two cases (if errno is zero, the + zlib error is Z_MEM_ERROR). */ + +ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode)); +/* + gzdopen() associates a gzFile with the file descriptor fd. File + descriptors are obtained from calls like open, dup, creat, pipe or + fileno (in the file has been previously opened with fopen). + The mode parameter is as in gzopen. + The next call of gzclose on the returned gzFile will also close the + file descriptor fd, just like fclose(fdopen(fd), mode) closes the file + descriptor fd. If you want to keep fd open, use gzdopen(dup(fd), mode). + gzdopen returns NULL if there was insufficient memory to allocate + the (de)compression state. +*/ + +ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy)); +/* + Dynamically update the compression level or strategy. See the description + of deflateInit2 for the meaning of these parameters. + gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not + opened for writing. +*/ + +ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len)); +/* + Reads the given number of uncompressed bytes from the compressed file. + If the input file was not in gzip format, gzread copies the given number + of bytes into the buffer. + gzread returns the number of uncompressed bytes actually read (0 for + end of file, -1 for error). */ + +ZEXTERN int ZEXPORT gzwrite OF((gzFile file, + voidpc buf, unsigned len)); +/* + Writes the given number of uncompressed bytes into the compressed file. + gzwrite returns the number of uncompressed bytes actually written + (0 in case of error). +*/ + +ZEXTERN int ZEXPORTVA gzprintf OF((gzFile file, const char *format, ...)); +/* + Converts, formats, and writes the args to the compressed file under + control of the format string, as in fprintf. gzprintf returns the number of + uncompressed bytes actually written (0 in case of error). The number of + uncompressed bytes written is limited to 4095. The caller should assure that + this limit is not exceeded. If it is exceeded, then gzprintf() will return + return an error (0) with nothing written. In this case, there may also be a + buffer overflow with unpredictable consequences, which is possible only if + zlib was compiled with the insecure functions sprintf() or vsprintf() + because the secure snprintf() or vsnprintf() functions were not available. +*/ + +ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s)); +/* + Writes the given null-terminated string to the compressed file, excluding + the terminating null character. + gzputs returns the number of characters written, or -1 in case of error. +*/ + +ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len)); +/* + Reads bytes from the compressed file until len-1 characters are read, or + a newline character is read and transferred to buf, or an end-of-file + condition is encountered. The string is then terminated with a null + character. + gzgets returns buf, or Z_NULL in case of error. +*/ + +ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c)); +/* + Writes c, converted to an unsigned char, into the compressed file. + gzputc returns the value that was written, or -1 in case of error. +*/ + +ZEXTERN int ZEXPORT gzgetc OF((gzFile file)); +/* + Reads one byte from the compressed file. gzgetc returns this byte + or -1 in case of end of file or error. +*/ + +ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file)); +/* + Push one character back onto the stream to be read again later. + Only one character of push-back is allowed. gzungetc() returns the + character pushed, or -1 on failure. gzungetc() will fail if a + character has been pushed but not read yet, or if c is -1. The pushed + character will be discarded if the stream is repositioned with gzseek() + or gzrewind(). +*/ + +ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush)); +/* + Flushes all pending output into the compressed file. The parameter + flush is as in the deflate() function. The return value is the zlib + error number (see function gzerror below). gzflush returns Z_OK if + the flush parameter is Z_FINISH and all output could be flushed. + gzflush should be called only when strictly necessary because it can + degrade compression. +*/ + +ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file, + z_off_t offset, int whence)); +/* + Sets the starting position for the next gzread or gzwrite on the + given compressed file. The offset represents a number of bytes in the + uncompressed data stream. The whence parameter is defined as in lseek(2); + the value SEEK_END is not supported. + If the file is opened for reading, this function is emulated but can be + extremely slow. If the file is opened for writing, only forward seeks are + supported; gzseek then compresses a sequence of zeroes up to the new + starting position. + + gzseek returns the resulting offset location as measured in bytes from + the beginning of the uncompressed stream, or -1 in case of error, in + particular if the file is opened for writing and the new starting position + would be before the current position. +*/ + +ZEXTERN int ZEXPORT gzrewind OF((gzFile file)); +/* + Rewinds the given file. This function is supported only for reading. + + gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET) +*/ + +ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file)); +/* + Returns the starting position for the next gzread or gzwrite on the + given compressed file. This position represents a number of bytes in the + uncompressed data stream. + + gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR) +*/ + +ZEXTERN int ZEXPORT gzeof OF((gzFile file)); +/* + Returns 1 when EOF has previously been detected reading the given + input stream, otherwise zero. +*/ + +ZEXTERN int ZEXPORT gzdirect OF((gzFile file)); +/* + Returns 1 if file is being read directly without decompression, otherwise + zero. +*/ + +ZEXTERN int ZEXPORT gzclose OF((gzFile file)); +/* + Flushes all pending output if necessary, closes the compressed file + and deallocates all the (de)compression state. The return value is the zlib + error number (see function gzerror below). +*/ + +ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum)); +/* + Returns the error message for the last error which occurred on the + given compressed file. errnum is set to zlib error number. If an + error occurred in the file system and not in the compression library, + errnum is set to Z_ERRNO and the application may consult errno + to get the exact error code. +*/ + +ZEXTERN void ZEXPORT gzclearerr OF((gzFile file)); +/* + Clears the error and end-of-file flags for file. This is analogous to the + clearerr() function in stdio. This is useful for continuing to read a gzip + file that is being written concurrently. +*/ + + /* checksum functions */ + +/* + These functions are not related to compression but are exported + anyway because they might be useful in applications using the + compression library. +*/ + +ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len)); +/* + Update a running Adler-32 checksum with the bytes buf[0..len-1] and + return the updated checksum. If buf is NULL, this function returns + the required initial value for the checksum. + An Adler-32 checksum is almost as reliable as a CRC32 but can be computed + much faster. Usage example: + + uLong adler = adler32(0L, Z_NULL, 0); + + while (read_buffer(buffer, length) != EOF) { + adler = adler32(adler, buffer, length); + } + if (adler != original_adler) error(); +*/ + +ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2, + z_off_t len2)); +/* + Combine two Adler-32 checksums into one. For two sequences of bytes, seq1 + and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for + each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of + seq1 and seq2 concatenated, requiring only adler1, adler2, and len2. +*/ + +ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len)); +/* + Update a running CRC-32 with the bytes buf[0..len-1] and return the + updated CRC-32. If buf is NULL, this function returns the required initial + value for the for the crc. Pre- and post-conditioning (one's complement) is + performed within this function so it shouldn't be done by the application. + Usage example: + + uLong crc = crc32(0L, Z_NULL, 0); + + while (read_buffer(buffer, length) != EOF) { + crc = crc32(crc, buffer, length); + } + if (crc != original_crc) error(); +*/ + +ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2)); + +/* + Combine two CRC-32 check values into one. For two sequences of bytes, + seq1 and seq2 with lengths len1 and len2, CRC-32 check values were + calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32 + check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and + len2. +*/ + + + /* various hacks, don't look :) */ + +/* deflateInit and inflateInit are macros to allow checking the zlib version + * and the compiler's view of z_stream: + */ +ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level, + const char *version, int stream_size)); +ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm, + const char *version, int stream_size)); +ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method, + int windowBits, int memLevel, + int strategy, const char *version, + int stream_size)); +ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits, + const char *version, int stream_size)); +ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits, + unsigned char FAR *window, + const char *version, + int stream_size)); +#define deflateInit(strm, level) \ + deflateInit_((strm), (level), ZLIB_VERSION, sizeof(z_stream)) +#define inflateInit(strm) \ + inflateInit_((strm), ZLIB_VERSION, sizeof(z_stream)) +#define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \ + deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\ + (strategy), ZLIB_VERSION, sizeof(z_stream)) +#define inflateInit2(strm, windowBits) \ + inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream)) +#define inflateBackInit(strm, windowBits, window) \ + inflateBackInit_((strm), (windowBits), (window), \ + ZLIB_VERSION, sizeof(z_stream)) + + +#if !defined(ZUTIL_H) && !defined(NO_DUMMY_DECL) + struct internal_state {int dummy;}; /* hack for buggy compilers */ +#endif + +ZEXTERN const char * ZEXPORT zError OF((int)); +ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp z)); +ZEXTERN const uLongf * ZEXPORT get_crc_table OF((void)); + +#ifdef __cplusplus +} +#endif + +#endif /* ZLIB_H */ diff --git a/Foundation/src/zutil.c b/Foundation/src/zutil.c index 18cd13b7a..ca1113fe2 100644 --- a/Foundation/src/zutil.c +++ b/Foundation/src/zutil.c @@ -1,318 +1,318 @@ -/* zutil.c -- target dependent utility functions for the compression library - * Copyright (C) 1995-2005 Jean-loup Gailly. - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -/* @(#) $Id: //poco/1.2/Foundation/src/zutil.c#1 $ */ - -#include "zutil.h" - -#ifndef NO_DUMMY_DECL -struct internal_state {int dummy;}; /* for buggy compilers */ -#endif - -const char * const z_errmsg[10] = { -"need dictionary", /* Z_NEED_DICT 2 */ -"stream end", /* Z_STREAM_END 1 */ -"", /* Z_OK 0 */ -"file error", /* Z_ERRNO (-1) */ -"stream error", /* Z_STREAM_ERROR (-2) */ -"data error", /* Z_DATA_ERROR (-3) */ -"insufficient memory", /* Z_MEM_ERROR (-4) */ -"buffer error", /* Z_BUF_ERROR (-5) */ -"incompatible version",/* Z_VERSION_ERROR (-6) */ -""}; - - -const char * ZEXPORT zlibVersion() -{ - return ZLIB_VERSION; -} - -uLong ZEXPORT zlibCompileFlags() -{ - uLong flags; - - flags = 0; - switch (sizeof(uInt)) { - case 2: break; - case 4: flags += 1; break; - case 8: flags += 2; break; - default: flags += 3; - } - switch (sizeof(uLong)) { - case 2: break; - case 4: flags += 1 << 2; break; - case 8: flags += 2 << 2; break; - default: flags += 3 << 2; - } - switch (sizeof(voidpf)) { - case 2: break; - case 4: flags += 1 << 4; break; - case 8: flags += 2 << 4; break; - default: flags += 3 << 4; - } - switch (sizeof(z_off_t)) { - case 2: break; - case 4: flags += 1 << 6; break; - case 8: flags += 2 << 6; break; - default: flags += 3 << 6; - } -#ifdef DEBUG - flags += 1 << 8; -#endif -#if defined(ASMV) || defined(ASMINF) - flags += 1 << 9; -#endif -#ifdef ZLIB_WINAPI - flags += 1 << 10; -#endif -#ifdef BUILDFIXED - flags += 1 << 12; -#endif -#ifdef DYNAMIC_CRC_TABLE - flags += 1 << 13; -#endif -#ifdef NO_GZCOMPRESS - flags += 1L << 16; -#endif -#ifdef NO_GZIP - flags += 1L << 17; -#endif -#ifdef PKZIP_BUG_WORKAROUND - flags += 1L << 20; -#endif -#ifdef FASTEST - flags += 1L << 21; -#endif -#ifdef STDC -# ifdef NO_vsnprintf - flags += 1L << 25; -# ifdef HAS_vsprintf_void - flags += 1L << 26; -# endif -# else -# ifdef HAS_vsnprintf_void - flags += 1L << 26; -# endif -# endif -#else - flags += 1L << 24; -# ifdef NO_snprintf - flags += 1L << 25; -# ifdef HAS_sprintf_void - flags += 1L << 26; -# endif -# else -# ifdef HAS_snprintf_void - flags += 1L << 26; -# endif -# endif -#endif - return flags; -} - -#ifdef DEBUG - -# ifndef verbose -# define verbose 0 -# endif -int z_verbose = verbose; - -void z_error (m) - char *m; -{ - fprintf(stderr, "%s\n", m); - exit(1); -} -#endif - -/* exported to allow conversion of error code to string for compress() and - * uncompress() - */ -const char * ZEXPORT zError(err) - int err; -{ - return ERR_MSG(err); -} - -#if defined(_WIN32_WCE) - /* The Microsoft C Run-Time Library for Windows CE doesn't have - * errno. We define it as a global variable to simplify porting. - * Its value is always 0 and should not be used. - */ - int errno = 0; -#endif - -#ifndef HAVE_MEMCPY - -void zmemcpy(dest, source, len) - Bytef* dest; - const Bytef* source; - uInt len; -{ - if (len == 0) return; - do { - *dest++ = *source++; /* ??? to be unrolled */ - } while (--len != 0); -} - -int zmemcmp(s1, s2, len) - const Bytef* s1; - const Bytef* s2; - uInt len; -{ - uInt j; - - for (j = 0; j < len; j++) { - if (s1[j] != s2[j]) return 2*(s1[j] > s2[j])-1; - } - return 0; -} - -void zmemzero(dest, len) - Bytef* dest; - uInt len; -{ - if (len == 0) return; - do { - *dest++ = 0; /* ??? to be unrolled */ - } while (--len != 0); -} -#endif - - -#ifdef SYS16BIT - -#ifdef __TURBOC__ -/* Turbo C in 16-bit mode */ - -# define MY_ZCALLOC - -/* Turbo C malloc() does not allow dynamic allocation of 64K bytes - * and farmalloc(64K) returns a pointer with an offset of 8, so we - * must fix the pointer. Warning: the pointer must be put back to its - * original form in order to free it, use zcfree(). - */ - -#define MAX_PTR 10 -/* 10*64K = 640K */ - -local int next_ptr = 0; - -typedef struct ptr_table_s { - voidpf org_ptr; - voidpf new_ptr; -} ptr_table; - -local ptr_table table[MAX_PTR]; -/* This table is used to remember the original form of pointers - * to large buffers (64K). Such pointers are normalized with a zero offset. - * Since MSDOS is not a preemptive multitasking OS, this table is not - * protected from concurrent access. This hack doesn't work anyway on - * a protected system like OS/2. Use Microsoft C instead. - */ - -voidpf zcalloc (voidpf opaque, unsigned items, unsigned size) -{ - voidpf buf = opaque; /* just to make some compilers happy */ - ulg bsize = (ulg)items*size; - - /* If we allocate less than 65520 bytes, we assume that farmalloc - * will return a usable pointer which doesn't have to be normalized. - */ - if (bsize < 65520L) { - buf = farmalloc(bsize); - if (*(ush*)&buf != 0) return buf; - } else { - buf = farmalloc(bsize + 16L); - } - if (buf == NULL || next_ptr >= MAX_PTR) return NULL; - table[next_ptr].org_ptr = buf; - - /* Normalize the pointer to seg:0 */ - *((ush*)&buf+1) += ((ush)((uch*)buf-0) + 15) >> 4; - *(ush*)&buf = 0; - table[next_ptr++].new_ptr = buf; - return buf; -} - -void zcfree (voidpf opaque, voidpf ptr) -{ - int n; - if (*(ush*)&ptr != 0) { /* object < 64K */ - farfree(ptr); - return; - } - /* Find the original pointer */ - for (n = 0; n < next_ptr; n++) { - if (ptr != table[n].new_ptr) continue; - - farfree(table[n].org_ptr); - while (++n < next_ptr) { - table[n-1] = table[n]; - } - next_ptr--; - return; - } - ptr = opaque; /* just to make some compilers happy */ - Assert(0, "zcfree: ptr not found"); -} - -#endif /* __TURBOC__ */ - - -#ifdef M_I86 -/* Microsoft C in 16-bit mode */ - -# define MY_ZCALLOC - -#if (!defined(_MSC_VER) || (_MSC_VER <= 600)) -# define _halloc halloc -# define _hfree hfree -#endif - -voidpf zcalloc (voidpf opaque, unsigned items, unsigned size) -{ - if (opaque) opaque = 0; /* to make compiler happy */ - return _halloc((long)items, size); -} - -void zcfree (voidpf opaque, voidpf ptr) -{ - if (opaque) opaque = 0; /* to make compiler happy */ - _hfree(ptr); -} - -#endif /* M_I86 */ - -#endif /* SYS16BIT */ - - -#ifndef MY_ZCALLOC /* Any system without a special alloc function */ - -#ifndef STDC -extern voidp malloc OF((uInt size)); -extern voidp calloc OF((uInt items, uInt size)); -extern void free OF((voidpf ptr)); -#endif - -voidpf zcalloc (opaque, items, size) - voidpf opaque; - unsigned items; - unsigned size; -{ - if (opaque) items += size - size; /* make compiler happy */ - return sizeof(uInt) > 2 ? (voidpf)malloc(items * size) : - (voidpf)calloc(items, size); -} - -void zcfree (opaque, ptr) - voidpf opaque; - voidpf ptr; -{ - free(ptr); - if (opaque) return; /* make compiler happy */ -} - -#endif /* MY_ZCALLOC */ +/* zutil.c -- target dependent utility functions for the compression library + * Copyright (C) 1995-2005 Jean-loup Gailly. + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* @(#) $Id: //poco/1.2/Foundation/src/zutil.c#1 $ */ + +#include "zutil.h" + +#ifndef NO_DUMMY_DECL +struct internal_state {int dummy;}; /* for buggy compilers */ +#endif + +const char * const z_errmsg[10] = { +"need dictionary", /* Z_NEED_DICT 2 */ +"stream end", /* Z_STREAM_END 1 */ +"", /* Z_OK 0 */ +"file error", /* Z_ERRNO (-1) */ +"stream error", /* Z_STREAM_ERROR (-2) */ +"data error", /* Z_DATA_ERROR (-3) */ +"insufficient memory", /* Z_MEM_ERROR (-4) */ +"buffer error", /* Z_BUF_ERROR (-5) */ +"incompatible version",/* Z_VERSION_ERROR (-6) */ +""}; + + +const char * ZEXPORT zlibVersion() +{ + return ZLIB_VERSION; +} + +uLong ZEXPORT zlibCompileFlags() +{ + uLong flags; + + flags = 0; + switch (sizeof(uInt)) { + case 2: break; + case 4: flags += 1; break; + case 8: flags += 2; break; + default: flags += 3; + } + switch (sizeof(uLong)) { + case 2: break; + case 4: flags += 1 << 2; break; + case 8: flags += 2 << 2; break; + default: flags += 3 << 2; + } + switch (sizeof(voidpf)) { + case 2: break; + case 4: flags += 1 << 4; break; + case 8: flags += 2 << 4; break; + default: flags += 3 << 4; + } + switch (sizeof(z_off_t)) { + case 2: break; + case 4: flags += 1 << 6; break; + case 8: flags += 2 << 6; break; + default: flags += 3 << 6; + } +#ifdef DEBUG + flags += 1 << 8; +#endif +#if defined(ASMV) || defined(ASMINF) + flags += 1 << 9; +#endif +#ifdef ZLIB_WINAPI + flags += 1 << 10; +#endif +#ifdef BUILDFIXED + flags += 1 << 12; +#endif +#ifdef DYNAMIC_CRC_TABLE + flags += 1 << 13; +#endif +#ifdef NO_GZCOMPRESS + flags += 1L << 16; +#endif +#ifdef NO_GZIP + flags += 1L << 17; +#endif +#ifdef PKZIP_BUG_WORKAROUND + flags += 1L << 20; +#endif +#ifdef FASTEST + flags += 1L << 21; +#endif +#ifdef STDC +# ifdef NO_vsnprintf + flags += 1L << 25; +# ifdef HAS_vsprintf_void + flags += 1L << 26; +# endif +# else +# ifdef HAS_vsnprintf_void + flags += 1L << 26; +# endif +# endif +#else + flags += 1L << 24; +# ifdef NO_snprintf + flags += 1L << 25; +# ifdef HAS_sprintf_void + flags += 1L << 26; +# endif +# else +# ifdef HAS_snprintf_void + flags += 1L << 26; +# endif +# endif +#endif + return flags; +} + +#ifdef DEBUG + +# ifndef verbose +# define verbose 0 +# endif +int z_verbose = verbose; + +void z_error (m) + char *m; +{ + fprintf(stderr, "%s\n", m); + exit(1); +} +#endif + +/* exported to allow conversion of error code to string for compress() and + * uncompress() + */ +const char * ZEXPORT zError(err) + int err; +{ + return ERR_MSG(err); +} + +#if defined(_WIN32_WCE) + /* The Microsoft C Run-Time Library for Windows CE doesn't have + * errno. We define it as a global variable to simplify porting. + * Its value is always 0 and should not be used. + */ + int errno = 0; +#endif + +#ifndef HAVE_MEMCPY + +void zmemcpy(dest, source, len) + Bytef* dest; + const Bytef* source; + uInt len; +{ + if (len == 0) return; + do { + *dest++ = *source++; /* ??? to be unrolled */ + } while (--len != 0); +} + +int zmemcmp(s1, s2, len) + const Bytef* s1; + const Bytef* s2; + uInt len; +{ + uInt j; + + for (j = 0; j < len; j++) { + if (s1[j] != s2[j]) return 2*(s1[j] > s2[j])-1; + } + return 0; +} + +void zmemzero(dest, len) + Bytef* dest; + uInt len; +{ + if (len == 0) return; + do { + *dest++ = 0; /* ??? to be unrolled */ + } while (--len != 0); +} +#endif + + +#ifdef SYS16BIT + +#ifdef __TURBOC__ +/* Turbo C in 16-bit mode */ + +# define MY_ZCALLOC + +/* Turbo C malloc() does not allow dynamic allocation of 64K bytes + * and farmalloc(64K) returns a pointer with an offset of 8, so we + * must fix the pointer. Warning: the pointer must be put back to its + * original form in order to free it, use zcfree(). + */ + +#define MAX_PTR 10 +/* 10*64K = 640K */ + +local int next_ptr = 0; + +typedef struct ptr_table_s { + voidpf org_ptr; + voidpf new_ptr; +} ptr_table; + +local ptr_table table[MAX_PTR]; +/* This table is used to remember the original form of pointers + * to large buffers (64K). Such pointers are normalized with a zero offset. + * Since MSDOS is not a preemptive multitasking OS, this table is not + * protected from concurrent access. This hack doesn't work anyway on + * a protected system like OS/2. Use Microsoft C instead. + */ + +voidpf zcalloc (voidpf opaque, unsigned items, unsigned size) +{ + voidpf buf = opaque; /* just to make some compilers happy */ + ulg bsize = (ulg)items*size; + + /* If we allocate less than 65520 bytes, we assume that farmalloc + * will return a usable pointer which doesn't have to be normalized. + */ + if (bsize < 65520L) { + buf = farmalloc(bsize); + if (*(ush*)&buf != 0) return buf; + } else { + buf = farmalloc(bsize + 16L); + } + if (buf == NULL || next_ptr >= MAX_PTR) return NULL; + table[next_ptr].org_ptr = buf; + + /* Normalize the pointer to seg:0 */ + *((ush*)&buf+1) += ((ush)((uch*)buf-0) + 15) >> 4; + *(ush*)&buf = 0; + table[next_ptr++].new_ptr = buf; + return buf; +} + +void zcfree (voidpf opaque, voidpf ptr) +{ + int n; + if (*(ush*)&ptr != 0) { /* object < 64K */ + farfree(ptr); + return; + } + /* Find the original pointer */ + for (n = 0; n < next_ptr; n++) { + if (ptr != table[n].new_ptr) continue; + + farfree(table[n].org_ptr); + while (++n < next_ptr) { + table[n-1] = table[n]; + } + next_ptr--; + return; + } + ptr = opaque; /* just to make some compilers happy */ + Assert(0, "zcfree: ptr not found"); +} + +#endif /* __TURBOC__ */ + + +#ifdef M_I86 +/* Microsoft C in 16-bit mode */ + +# define MY_ZCALLOC + +#if (!defined(_MSC_VER) || (_MSC_VER <= 600)) +# define _halloc halloc +# define _hfree hfree +#endif + +voidpf zcalloc (voidpf opaque, unsigned items, unsigned size) +{ + if (opaque) opaque = 0; /* to make compiler happy */ + return _halloc((long)items, size); +} + +void zcfree (voidpf opaque, voidpf ptr) +{ + if (opaque) opaque = 0; /* to make compiler happy */ + _hfree(ptr); +} + +#endif /* M_I86 */ + +#endif /* SYS16BIT */ + + +#ifndef MY_ZCALLOC /* Any system without a special alloc function */ + +#ifndef STDC +extern voidp malloc OF((uInt size)); +extern voidp calloc OF((uInt items, uInt size)); +extern void free OF((voidpf ptr)); +#endif + +voidpf zcalloc (opaque, items, size) + voidpf opaque; + unsigned items; + unsigned size; +{ + if (opaque) items += size - size; /* make compiler happy */ + return sizeof(uInt) > 2 ? (voidpf)malloc(items * size) : + (voidpf)calloc(items, size); +} + +void zcfree (opaque, ptr) + voidpf opaque; + voidpf ptr; +{ + free(ptr); + if (opaque) return; /* make compiler happy */ +} + +#endif /* MY_ZCALLOC */ diff --git a/Foundation/src/zutil.h b/Foundation/src/zutil.h index e223c12f8..324e51a92 100644 --- a/Foundation/src/zutil.h +++ b/Foundation/src/zutil.h @@ -1,269 +1,269 @@ -/* zutil.h -- internal interface and configuration of the compression library - * Copyright (C) 1995-2005 Jean-loup Gailly. - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -/* WARNING: this file should *not* be used by applications. It is - part of the implementation of the compression library and is - subject to change. Applications should only use zlib.h. - */ - -/* @(#) $Id: //poco/1.2/Foundation/src/zutil.h#1 $ */ - -#ifndef ZUTIL_H -#define ZUTIL_H - -#define ZLIB_INTERNAL -#include "zlib.h" - -#ifdef STDC -# ifndef _WIN32_WCE -# include -# endif -# include -# include -#endif -#ifdef NO_ERRNO_H -# ifdef _WIN32_WCE - /* The Microsoft C Run-Time Library for Windows CE doesn't have - * errno. We define it as a global variable to simplify porting. - * Its value is always 0 and should not be used. We rename it to - * avoid conflict with other libraries that use the same workaround. - */ -# define errno z_errno -# endif - extern int errno; -#else -# ifndef _WIN32_WCE -# include -# endif -#endif - -#ifndef local -# define local static -#endif -/* compile with -Dlocal if your debugger can't find static symbols */ - -typedef unsigned char uch; -typedef uch FAR uchf; -typedef unsigned short ush; -typedef ush FAR ushf; -typedef unsigned long ulg; - -extern const char * const z_errmsg[10]; /* indexed by 2-zlib_error */ -/* (size given to avoid silly warnings with Visual C++) */ - -#define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)] - -#define ERR_RETURN(strm,err) \ - return (strm->msg = (char*)ERR_MSG(err), (err)) -/* To be used only when the state is known to be valid */ - - /* common constants */ - -#ifndef DEF_WBITS -# define DEF_WBITS MAX_WBITS -#endif -/* default windowBits for decompression. MAX_WBITS is for compression only */ - -#if MAX_MEM_LEVEL >= 8 -# define DEF_MEM_LEVEL 8 -#else -# define DEF_MEM_LEVEL MAX_MEM_LEVEL -#endif -/* default memLevel */ - -#define STORED_BLOCK 0 -#define STATIC_TREES 1 -#define DYN_TREES 2 -/* The three kinds of block type */ - -#define MIN_MATCH 3 -#define MAX_MATCH 258 -/* The minimum and maximum match lengths */ - -#define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */ - - /* target dependencies */ - -#if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32)) -# define OS_CODE 0x00 -# if defined(__TURBOC__) || defined(__BORLANDC__) -# if(__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__)) - /* Allow compilation with ANSI keywords only enabled */ - void _Cdecl farfree( void *block ); - void *_Cdecl farmalloc( unsigned long nbytes ); -# else -# include -# endif -# else /* MSC or DJGPP */ -# include -# endif -#endif - -#ifdef AMIGA -# define OS_CODE 0x01 -#endif - -#if defined(VAXC) || defined(VMS) -# define OS_CODE 0x02 -# define F_OPEN(name, mode) \ - fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512") -#endif - -#if defined(ATARI) || defined(atarist) -# define OS_CODE 0x05 -#endif - -#ifdef OS2 -# define OS_CODE 0x06 -# ifdef M_I86 - #include -# endif -#endif - -#if defined(MACOS) || defined(TARGET_OS_MAC) -# define OS_CODE 0x07 -# if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os -# include /* for fdopen */ -# else -# ifndef fdopen -# define fdopen(fd,mode) NULL /* No fdopen() */ -# endif -# endif -#endif - -#ifdef TOPS20 -# define OS_CODE 0x0a -#endif - -#ifdef WIN32 -# ifndef __CYGWIN__ /* Cygwin is Unix, not Win32 */ -# define OS_CODE 0x0b -# endif -#endif - -#ifdef __50SERIES /* Prime/PRIMOS */ -# define OS_CODE 0x0f -#endif - -#if defined(_BEOS_) || defined(RISCOS) -# define fdopen(fd,mode) NULL /* No fdopen() */ -#endif - -#if (defined(_MSC_VER) && (_MSC_VER > 600)) -# if defined(_WIN32_WCE) -# define fdopen(fd,mode) NULL /* No fdopen() */ -# ifndef _PTRDIFF_T_DEFINED - typedef int ptrdiff_t; -# define _PTRDIFF_T_DEFINED -# endif -# else -# define fdopen(fd,type) _fdopen(fd,type) -# endif -#endif - - /* common defaults */ - -#ifndef OS_CODE -# define OS_CODE 0x03 /* assume Unix */ -#endif - -#ifndef F_OPEN -# define F_OPEN(name, mode) fopen((name), (mode)) -#endif - - /* functions */ - -#if defined(STDC99) || (defined(__TURBOC__) && __TURBOC__ >= 0x550) -# ifndef HAVE_VSNPRINTF -# define HAVE_VSNPRINTF -# endif -#endif -#if defined(__CYGWIN__) -# ifndef HAVE_VSNPRINTF -# define HAVE_VSNPRINTF -# endif -#endif -#ifndef HAVE_VSNPRINTF -# ifdef MSDOS - /* vsnprintf may exist on some MS-DOS compilers (DJGPP?), - but for now we just assume it doesn't. */ -# define NO_vsnprintf -# endif -# ifdef __TURBOC__ -# define NO_vsnprintf -# endif -# ifdef WIN32 - /* In Win32, vsnprintf is available as the "non-ANSI" _vsnprintf. */ -# if !defined(vsnprintf) && !defined(NO_vsnprintf) -# define vsnprintf _vsnprintf -# endif -# endif -# ifdef __SASC -# define NO_vsnprintf -# endif -#endif -#ifdef VMS -# define NO_vsnprintf -#endif - -#if defined(pyr) -# define NO_MEMCPY -#endif -#if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__) - /* Use our own functions for small and medium model with MSC <= 5.0. - * You may have to use the same strategy for Borland C (untested). - * The __SC__ check is for Symantec. - */ -# define NO_MEMCPY -#endif -#if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY) -# define HAVE_MEMCPY -#endif -#ifdef HAVE_MEMCPY -# ifdef SMALL_MEDIUM /* MSDOS small or medium model */ -# define zmemcpy _fmemcpy -# define zmemcmp _fmemcmp -# define zmemzero(dest, len) _fmemset(dest, 0, len) -# else -# define zmemcpy memcpy -# define zmemcmp memcmp -# define zmemzero(dest, len) memset(dest, 0, len) -# endif -#else - extern void zmemcpy OF((Bytef* dest, const Bytef* source, uInt len)); - extern int zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len)); - extern void zmemzero OF((Bytef* dest, uInt len)); -#endif - -/* Diagnostic functions */ -#ifdef DEBUG -# include - extern int z_verbose; - extern void z_error OF((char *m)); -# define Assert(cond,msg) {if(!(cond)) z_error(msg);} -# define Trace(x) {if (z_verbose>=0) fprintf x ;} -# define Tracev(x) {if (z_verbose>0) fprintf x ;} -# define Tracevv(x) {if (z_verbose>1) fprintf x ;} -# define Tracec(c,x) {if (z_verbose>0 && (c)) fprintf x ;} -# define Tracecv(c,x) {if (z_verbose>1 && (c)) fprintf x ;} -#else -# define Assert(cond,msg) -# define Trace(x) -# define Tracev(x) -# define Tracevv(x) -# define Tracec(c,x) -# define Tracecv(c,x) -#endif - - -voidpf zcalloc OF((voidpf opaque, unsigned items, unsigned size)); -void zcfree OF((voidpf opaque, voidpf ptr)); - -#define ZALLOC(strm, items, size) \ - (*((strm)->zalloc))((strm)->opaque, (items), (size)) -#define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidpf)(addr)) -#define TRY_FREE(s, p) {if (p) ZFREE(s, p);} - -#endif /* ZUTIL_H */ +/* zutil.h -- internal interface and configuration of the compression library + * Copyright (C) 1995-2005 Jean-loup Gailly. + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* WARNING: this file should *not* be used by applications. It is + part of the implementation of the compression library and is + subject to change. Applications should only use zlib.h. + */ + +/* @(#) $Id: //poco/1.2/Foundation/src/zutil.h#1 $ */ + +#ifndef ZUTIL_H +#define ZUTIL_H + +#define ZLIB_INTERNAL +#include "zlib.h" + +#ifdef STDC +# ifndef _WIN32_WCE +# include +# endif +# include +# include +#endif +#ifdef NO_ERRNO_H +# ifdef _WIN32_WCE + /* The Microsoft C Run-Time Library for Windows CE doesn't have + * errno. We define it as a global variable to simplify porting. + * Its value is always 0 and should not be used. We rename it to + * avoid conflict with other libraries that use the same workaround. + */ +# define errno z_errno +# endif + extern int errno; +#else +# ifndef _WIN32_WCE +# include +# endif +#endif + +#ifndef local +# define local static +#endif +/* compile with -Dlocal if your debugger can't find static symbols */ + +typedef unsigned char uch; +typedef uch FAR uchf; +typedef unsigned short ush; +typedef ush FAR ushf; +typedef unsigned long ulg; + +extern const char * const z_errmsg[10]; /* indexed by 2-zlib_error */ +/* (size given to avoid silly warnings with Visual C++) */ + +#define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)] + +#define ERR_RETURN(strm,err) \ + return (strm->msg = (char*)ERR_MSG(err), (err)) +/* To be used only when the state is known to be valid */ + + /* common constants */ + +#ifndef DEF_WBITS +# define DEF_WBITS MAX_WBITS +#endif +/* default windowBits for decompression. MAX_WBITS is for compression only */ + +#if MAX_MEM_LEVEL >= 8 +# define DEF_MEM_LEVEL 8 +#else +# define DEF_MEM_LEVEL MAX_MEM_LEVEL +#endif +/* default memLevel */ + +#define STORED_BLOCK 0 +#define STATIC_TREES 1 +#define DYN_TREES 2 +/* The three kinds of block type */ + +#define MIN_MATCH 3 +#define MAX_MATCH 258 +/* The minimum and maximum match lengths */ + +#define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */ + + /* target dependencies */ + +#if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32)) +# define OS_CODE 0x00 +# if defined(__TURBOC__) || defined(__BORLANDC__) +# if(__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__)) + /* Allow compilation with ANSI keywords only enabled */ + void _Cdecl farfree( void *block ); + void *_Cdecl farmalloc( unsigned long nbytes ); +# else +# include +# endif +# else /* MSC or DJGPP */ +# include +# endif +#endif + +#ifdef AMIGA +# define OS_CODE 0x01 +#endif + +#if defined(VAXC) || defined(VMS) +# define OS_CODE 0x02 +# define F_OPEN(name, mode) \ + fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512") +#endif + +#if defined(ATARI) || defined(atarist) +# define OS_CODE 0x05 +#endif + +#ifdef OS2 +# define OS_CODE 0x06 +# ifdef M_I86 + #include +# endif +#endif + +#if defined(MACOS) || defined(TARGET_OS_MAC) +# define OS_CODE 0x07 +# if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os +# include /* for fdopen */ +# else +# ifndef fdopen +# define fdopen(fd,mode) NULL /* No fdopen() */ +# endif +# endif +#endif + +#ifdef TOPS20 +# define OS_CODE 0x0a +#endif + +#ifdef WIN32 +# ifndef __CYGWIN__ /* Cygwin is Unix, not Win32 */ +# define OS_CODE 0x0b +# endif +#endif + +#ifdef __50SERIES /* Prime/PRIMOS */ +# define OS_CODE 0x0f +#endif + +#if defined(_BEOS_) || defined(RISCOS) +# define fdopen(fd,mode) NULL /* No fdopen() */ +#endif + +#if (defined(_MSC_VER) && (_MSC_VER > 600)) +# if defined(_WIN32_WCE) +# define fdopen(fd,mode) NULL /* No fdopen() */ +# ifndef _PTRDIFF_T_DEFINED + typedef int ptrdiff_t; +# define _PTRDIFF_T_DEFINED +# endif +# else +# define fdopen(fd,type) _fdopen(fd,type) +# endif +#endif + + /* common defaults */ + +#ifndef OS_CODE +# define OS_CODE 0x03 /* assume Unix */ +#endif + +#ifndef F_OPEN +# define F_OPEN(name, mode) fopen((name), (mode)) +#endif + + /* functions */ + +#if defined(STDC99) || (defined(__TURBOC__) && __TURBOC__ >= 0x550) +# ifndef HAVE_VSNPRINTF +# define HAVE_VSNPRINTF +# endif +#endif +#if defined(__CYGWIN__) +# ifndef HAVE_VSNPRINTF +# define HAVE_VSNPRINTF +# endif +#endif +#ifndef HAVE_VSNPRINTF +# ifdef MSDOS + /* vsnprintf may exist on some MS-DOS compilers (DJGPP?), + but for now we just assume it doesn't. */ +# define NO_vsnprintf +# endif +# ifdef __TURBOC__ +# define NO_vsnprintf +# endif +# ifdef WIN32 + /* In Win32, vsnprintf is available as the "non-ANSI" _vsnprintf. */ +# if !defined(vsnprintf) && !defined(NO_vsnprintf) +# define vsnprintf _vsnprintf +# endif +# endif +# ifdef __SASC +# define NO_vsnprintf +# endif +#endif +#ifdef VMS +# define NO_vsnprintf +#endif + +#if defined(pyr) +# define NO_MEMCPY +#endif +#if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__) + /* Use our own functions for small and medium model with MSC <= 5.0. + * You may have to use the same strategy for Borland C (untested). + * The __SC__ check is for Symantec. + */ +# define NO_MEMCPY +#endif +#if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY) +# define HAVE_MEMCPY +#endif +#ifdef HAVE_MEMCPY +# ifdef SMALL_MEDIUM /* MSDOS small or medium model */ +# define zmemcpy _fmemcpy +# define zmemcmp _fmemcmp +# define zmemzero(dest, len) _fmemset(dest, 0, len) +# else +# define zmemcpy memcpy +# define zmemcmp memcmp +# define zmemzero(dest, len) memset(dest, 0, len) +# endif +#else + extern void zmemcpy OF((Bytef* dest, const Bytef* source, uInt len)); + extern int zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len)); + extern void zmemzero OF((Bytef* dest, uInt len)); +#endif + +/* Diagnostic functions */ +#ifdef DEBUG +# include + extern int z_verbose; + extern void z_error OF((char *m)); +# define Assert(cond,msg) {if(!(cond)) z_error(msg);} +# define Trace(x) {if (z_verbose>=0) fprintf x ;} +# define Tracev(x) {if (z_verbose>0) fprintf x ;} +# define Tracevv(x) {if (z_verbose>1) fprintf x ;} +# define Tracec(c,x) {if (z_verbose>0 && (c)) fprintf x ;} +# define Tracecv(c,x) {if (z_verbose>1 && (c)) fprintf x ;} +#else +# define Assert(cond,msg) +# define Trace(x) +# define Tracev(x) +# define Tracevv(x) +# define Tracec(c,x) +# define Tracecv(c,x) +#endif + + +voidpf zcalloc OF((voidpf opaque, unsigned items, unsigned size)); +void zcfree OF((voidpf opaque, voidpf ptr)); + +#define ZALLOC(strm, items, size) \ + (*((strm)->zalloc))((strm)->opaque, (items), (size)) +#define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidpf)(addr)) +#define TRY_FREE(s, p) {if (p) ZFREE(s, p);} + +#endif /* ZUTIL_H */ diff --git a/Foundation/testsuite/Makefile b/Foundation/testsuite/Makefile index c74021cfb..3a79c8715 100644 --- a/Foundation/testsuite/Makefile +++ b/Foundation/testsuite/Makefile @@ -1,14 +1,14 @@ -# -# Makefile -# -# $Id: //poco/1.2/Foundation/testsuite/Makefile#1 $ -# -# Makefile for Poco Foundation testsuite -# - -.PHONY: projects -clean all: projects -projects: - $(MAKE) -f Makefile-Driver $(MAKECMDGOALS) - $(MAKE) -f Makefile-TestLibrary $(MAKECMDGOALS) - $(MAKE) -f Makefile-TestApp $(MAKECMDGOALS) +# +# Makefile +# +# $Id: //poco/1.2/Foundation/testsuite/Makefile#1 $ +# +# Makefile for Poco Foundation testsuite +# + +.PHONY: projects +clean all: projects +projects: + $(MAKE) -f Makefile-Driver $(MAKECMDGOALS) + $(MAKE) -f Makefile-TestLibrary $(MAKECMDGOALS) + $(MAKE) -f Makefile-TestApp $(MAKECMDGOALS) diff --git a/Foundation/testsuite/Makefile-Driver b/Foundation/testsuite/Makefile-Driver index 2c8d103d2..197bdec19 100644 --- a/Foundation/testsuite/Makefile-Driver +++ b/Foundation/testsuite/Makefile-Driver @@ -1,42 +1,42 @@ -# -# Makefile -# -# $Id: //poco/1.2/Foundation/testsuite/Makefile-Driver#1 $ -# -# Makefile for Poco Foundation testsuite -# - -include $(POCO_BASE)/build/rules/global - -objects = ActiveMethodTest ActivityTest ActiveDispatcherTest \ - AutoPtrTest SharedPtrTest AutoReleasePoolTest Base64Test \ - BinaryReaderWriterTest LineEndingConverterTest \ - ByteOrderTest ChannelTest ClassLoaderTest CoreTest CoreTestSuite \ - CountingStreamTest CryptTestSuite DateTimeFormatterTest \ - DateTimeParserTest DateTimeTest LocalDateTimeTest DateTimeTestSuite DigestStreamTest \ - Driver DynamicFactoryTest FPETest FileChannelTest FileTest GlobTest FilesystemTestSuite \ - FoundationTestSuite HMACEngineTest HexBinaryTest LoggerTest \ - LoggingFactoryTest LoggingRegistryTest LoggingTestSuite LogStreamTest \ - NamedEventTest NamedMutexTest ProcessesTestSuite ProcessTest \ - MemoryPoolTest MD2EngineTest MD4EngineTest MD5EngineTest ManifestTest \ - NDCTest NotificationCenterTest NotificationQueueTest \ - NotificationsTestSuite NullStreamTest NumberFormatterTest \ - NumberParserTest PathTest PatternFormatterTest RWLockTest \ - RandomStreamTest RandomTest RegularExpressionTest SHA1EngineTest \ - SemaphoreTest SharedLibraryTest SharedLibraryTestSuite \ - SimpleFileChannelTest StopwatchTest \ - StreamConverterTest StreamCopierTest StreamTokenizerTest \ - StreamsTestSuite StringTest StringTokenizerTest TaskTestSuite TaskTest \ - TaskManagerTest TestChannel TeeStreamTest \ - TextConverterTest TextIteratorTest TextTestSuite \ - ThreadLocalTest ThreadPoolTest ThreadTest ThreadingTestSuite TimerTest \ - TimespanTest TimestampTest TimezoneTest URIStreamOpenerTest URITest \ - URITestSuite UUIDGeneratorTest UUIDTest UUIDTestSuite ZLibTest \ - TestPlugin DummyDelegate BasicEventTest FIFOEventTest PriorityEventTest EventTestSuite \ - LRUCacheTest ExpireCacheTest ExpireLRUCacheTest CacheTestSuite AnyTest HashTest FormatTest - -target = testrunner -target_version = 1 -target_libs = PocoFoundation CppUnit - -include $(POCO_BASE)/build/rules/exec +# +# Makefile +# +# $Id: //poco/1.2/Foundation/testsuite/Makefile-Driver#1 $ +# +# Makefile for Poco Foundation testsuite +# + +include $(POCO_BASE)/build/rules/global + +objects = ActiveMethodTest ActivityTest ActiveDispatcherTest \ + AutoPtrTest SharedPtrTest AutoReleasePoolTest Base64Test \ + BinaryReaderWriterTest LineEndingConverterTest \ + ByteOrderTest ChannelTest ClassLoaderTest CoreTest CoreTestSuite \ + CountingStreamTest CryptTestSuite DateTimeFormatterTest \ + DateTimeParserTest DateTimeTest LocalDateTimeTest DateTimeTestSuite DigestStreamTest \ + Driver DynamicFactoryTest FPETest FileChannelTest FileTest GlobTest FilesystemTestSuite \ + FoundationTestSuite HMACEngineTest HexBinaryTest LoggerTest \ + LoggingFactoryTest LoggingRegistryTest LoggingTestSuite LogStreamTest \ + NamedEventTest NamedMutexTest ProcessesTestSuite ProcessTest \ + MemoryPoolTest MD2EngineTest MD4EngineTest MD5EngineTest ManifestTest \ + NDCTest NotificationCenterTest NotificationQueueTest \ + NotificationsTestSuite NullStreamTest NumberFormatterTest \ + NumberParserTest PathTest PatternFormatterTest RWLockTest \ + RandomStreamTest RandomTest RegularExpressionTest SHA1EngineTest \ + SemaphoreTest SharedLibraryTest SharedLibraryTestSuite \ + SimpleFileChannelTest StopwatchTest \ + StreamConverterTest StreamCopierTest StreamTokenizerTest \ + StreamsTestSuite StringTest StringTokenizerTest TaskTestSuite TaskTest \ + TaskManagerTest TestChannel TeeStreamTest \ + TextConverterTest TextIteratorTest TextTestSuite \ + ThreadLocalTest ThreadPoolTest ThreadTest ThreadingTestSuite TimerTest \ + TimespanTest TimestampTest TimezoneTest URIStreamOpenerTest URITest \ + URITestSuite UUIDGeneratorTest UUIDTest UUIDTestSuite ZLibTest \ + TestPlugin DummyDelegate BasicEventTest FIFOEventTest PriorityEventTest EventTestSuite \ + LRUCacheTest ExpireCacheTest ExpireLRUCacheTest CacheTestSuite AnyTest HashTest FormatTest + +target = testrunner +target_version = 1 +target_libs = PocoFoundation CppUnit + +include $(POCO_BASE)/build/rules/exec diff --git a/Foundation/testsuite/Makefile-TestApp b/Foundation/testsuite/Makefile-TestApp index a57924d52..5d16da601 100644 --- a/Foundation/testsuite/Makefile-TestApp +++ b/Foundation/testsuite/Makefile-TestApp @@ -1,17 +1,17 @@ -# -# Makefile -# -# $Id: //poco/1.2/Foundation/testsuite/Makefile-TestApp#1 $ -# -# Makefile for Poco TestApp -# - -include $(POCO_BASE)/build/rules/global - -objects = TestApp - -target = TestApp -target_version = 1 -target_libs = PocoFoundation - -include $(POCO_BASE)/build/rules/exec +# +# Makefile +# +# $Id: //poco/1.2/Foundation/testsuite/Makefile-TestApp#1 $ +# +# Makefile for Poco TestApp +# + +include $(POCO_BASE)/build/rules/global + +objects = TestApp + +target = TestApp +target_version = 1 +target_libs = PocoFoundation + +include $(POCO_BASE)/build/rules/exec diff --git a/Foundation/testsuite/Makefile-TestLibrary b/Foundation/testsuite/Makefile-TestLibrary index b7191405e..94ef67a03 100644 --- a/Foundation/testsuite/Makefile-TestLibrary +++ b/Foundation/testsuite/Makefile-TestLibrary @@ -1,17 +1,17 @@ -# -# Makefile -# -# $Id: //poco/1.2/Foundation/testsuite/Makefile-TestLibrary#1 $ -# -# Makefile for Poco Foundation testsuite -# - -include $(POCO_BASE)/build/rules/global - -objects = TestPlugin TestLibrary - -target = TestLibrary -target_version = 1 -target_libs = PocoFoundation - -include $(POCO_BASE)/build/rules/dylib +# +# Makefile +# +# $Id: //poco/1.2/Foundation/testsuite/Makefile-TestLibrary#1 $ +# +# Makefile for Poco Foundation testsuite +# + +include $(POCO_BASE)/build/rules/global + +objects = TestPlugin TestLibrary + +target = TestLibrary +target_version = 1 +target_libs = PocoFoundation + +include $(POCO_BASE)/build/rules/dylib diff --git a/Foundation/testsuite/TestApp_vs71.vcproj b/Foundation/testsuite/TestApp_vs71.vcproj index 3b4f4dd5a..9b62631f0 100644 --- a/Foundation/testsuite/TestApp_vs71.vcproj +++ b/Foundation/testsuite/TestApp_vs71.vcproj @@ -1,143 +1,143 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Foundation/testsuite/TestApp_vs80.vcproj b/Foundation/testsuite/TestApp_vs80.vcproj index 1177ff9c6..92db85a7d 100644 --- a/Foundation/testsuite/TestApp_vs80.vcproj +++ b/Foundation/testsuite/TestApp_vs80.vcproj @@ -1,208 +1,208 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Foundation/testsuite/TestLibrary_vs71.vcproj b/Foundation/testsuite/TestLibrary_vs71.vcproj index 4e3ee1522..057090456 100644 --- a/Foundation/testsuite/TestLibrary_vs71.vcproj +++ b/Foundation/testsuite/TestLibrary_vs71.vcproj @@ -1,158 +1,158 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Foundation/testsuite/TestLibrary_vs80.vcproj b/Foundation/testsuite/TestLibrary_vs80.vcproj index d3e70abc2..667caebc3 100644 --- a/Foundation/testsuite/TestLibrary_vs80.vcproj +++ b/Foundation/testsuite/TestLibrary_vs80.vcproj @@ -1,226 +1,226 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Foundation/testsuite/TestSuite_vs71.vcproj b/Foundation/testsuite/TestSuite_vs71.vcproj index 4e2e1e7b7..e106934be 100644 --- a/Foundation/testsuite/TestSuite_vs71.vcproj +++ b/Foundation/testsuite/TestSuite_vs71.vcproj @@ -1,989 +1,989 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Foundation/testsuite/TestSuite_vs80.vcproj b/Foundation/testsuite/TestSuite_vs80.vcproj index a6a120ce4..317570253 100644 --- a/Foundation/testsuite/TestSuite_vs80.vcproj +++ b/Foundation/testsuite/TestSuite_vs80.vcproj @@ -1,1265 +1,1265 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Foundation/testsuite/src/ActiveDispatcherTest.cpp b/Foundation/testsuite/src/ActiveDispatcherTest.cpp index 4d056069c..b2fb32914 100644 --- a/Foundation/testsuite/src/ActiveDispatcherTest.cpp +++ b/Foundation/testsuite/src/ActiveDispatcherTest.cpp @@ -1,190 +1,190 @@ -// -// ActiveDispatcherTest.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/ActiveDispatcherTest.cpp#1 $ -// -// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. -// 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. -// -// 3. Redistributions in any form must be accompanied by information on -// how to obtain complete source code for this software and any -// accompanying software that uses this software. The source code -// must either be included in the distribution or be available for no -// more than the cost of distribution plus a nominal fee, and must be -// freely redistributable under reasonable conditions. For an -// executable file, complete source code means the source code for all -// modules it contains. It does not include source code for modules or -// files that typically accompany the major components of the operating -// system on which the executable file runs. -// -// 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. -// - - -#include "ActiveDispatcherTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/ActiveDispatcher.h" -#include "Poco/ActiveMethod.h" -#include "Poco/Thread.h" -#include "Poco/Event.h" -#include "Poco/Exception.h" - - -using Poco::ActiveDispatcher; -using Poco::ActiveMethod; -using Poco::ActiveResult; -using Poco::ActiveStarter; -using Poco::Thread; -using Poco::Event; -using Poco::Exception; - - -namespace -{ - class ActiveObject: public ActiveDispatcher - { - public: - ActiveObject(): - testMethod(this, &ActiveObject::testMethodImpl) - { - } - - ~ActiveObject() - { - } - - ActiveMethod > testMethod; - - void cont() - { - _continue.set(); - } - - protected: - int testMethodImpl(const int& n) - { - if (n == 100) throw Exception("n == 100"); - _continue.wait(); - return n; - } - - private: - Event _continue; - }; -} - - -ActiveDispatcherTest::ActiveDispatcherTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -ActiveDispatcherTest::~ActiveDispatcherTest() -{ -} - - -void ActiveDispatcherTest::testWait() -{ - ActiveObject activeObj; - ActiveResult result = activeObj.testMethod(123); - assert (!result.available()); - activeObj.cont(); - result.wait(); - assert (result.available()); - assert (result.data() == 123); - assert (!result.failed()); -} - - -void ActiveDispatcherTest::testWaitInterval() -{ - ActiveObject activeObj; - ActiveResult result = activeObj.testMethod(123); - assert (!result.available()); - try - { - result.wait(100); - fail("wait must fail"); - } - catch (Exception&) - { - } - activeObj.cont(); - result.wait(10000); - assert (result.available()); - assert (result.data() == 123); - assert (!result.failed()); -} - - -void ActiveDispatcherTest::testTryWait() -{ - ActiveObject activeObj; - ActiveResult result = activeObj.testMethod(123); - assert (!result.available()); - assert (!result.tryWait(200)); - activeObj.cont(); - assert (result.tryWait(10000)); - assert (result.available()); - assert (result.data() == 123); - assert (!result.failed()); -} - - -void ActiveDispatcherTest::testFailure() -{ - ActiveObject activeObj; - ActiveResult result = activeObj.testMethod(100); - result.wait(); - assert (result.available()); - assert (result.failed()); - std::string msg = result.error(); - assert (msg == "n == 100"); -} - - -void ActiveDispatcherTest::setUp() -{ -} - - -void ActiveDispatcherTest::tearDown() -{ -} - - -CppUnit::Test* ActiveDispatcherTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("ActiveDispatcherTest"); - - CppUnit_addTest(pSuite, ActiveDispatcherTest, testWait); - CppUnit_addTest(pSuite, ActiveDispatcherTest, testWaitInterval); - CppUnit_addTest(pSuite, ActiveDispatcherTest, testTryWait); - CppUnit_addTest(pSuite, ActiveDispatcherTest, testFailure); - - return pSuite; -} +// +// ActiveDispatcherTest.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/ActiveDispatcherTest.cpp#1 $ +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// 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. +// +// 3. Redistributions in any form must be accompanied by information on +// how to obtain complete source code for this software and any +// accompanying software that uses this software. The source code +// must either be included in the distribution or be available for no +// more than the cost of distribution plus a nominal fee, and must be +// freely redistributable under reasonable conditions. For an +// executable file, complete source code means the source code for all +// modules it contains. It does not include source code for modules or +// files that typically accompany the major components of the operating +// system on which the executable file runs. +// +// 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. +// + + +#include "ActiveDispatcherTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/ActiveDispatcher.h" +#include "Poco/ActiveMethod.h" +#include "Poco/Thread.h" +#include "Poco/Event.h" +#include "Poco/Exception.h" + + +using Poco::ActiveDispatcher; +using Poco::ActiveMethod; +using Poco::ActiveResult; +using Poco::ActiveStarter; +using Poco::Thread; +using Poco::Event; +using Poco::Exception; + + +namespace +{ + class ActiveObject: public ActiveDispatcher + { + public: + ActiveObject(): + testMethod(this, &ActiveObject::testMethodImpl) + { + } + + ~ActiveObject() + { + } + + ActiveMethod > testMethod; + + void cont() + { + _continue.set(); + } + + protected: + int testMethodImpl(const int& n) + { + if (n == 100) throw Exception("n == 100"); + _continue.wait(); + return n; + } + + private: + Event _continue; + }; +} + + +ActiveDispatcherTest::ActiveDispatcherTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +ActiveDispatcherTest::~ActiveDispatcherTest() +{ +} + + +void ActiveDispatcherTest::testWait() +{ + ActiveObject activeObj; + ActiveResult result = activeObj.testMethod(123); + assert (!result.available()); + activeObj.cont(); + result.wait(); + assert (result.available()); + assert (result.data() == 123); + assert (!result.failed()); +} + + +void ActiveDispatcherTest::testWaitInterval() +{ + ActiveObject activeObj; + ActiveResult result = activeObj.testMethod(123); + assert (!result.available()); + try + { + result.wait(100); + fail("wait must fail"); + } + catch (Exception&) + { + } + activeObj.cont(); + result.wait(10000); + assert (result.available()); + assert (result.data() == 123); + assert (!result.failed()); +} + + +void ActiveDispatcherTest::testTryWait() +{ + ActiveObject activeObj; + ActiveResult result = activeObj.testMethod(123); + assert (!result.available()); + assert (!result.tryWait(200)); + activeObj.cont(); + assert (result.tryWait(10000)); + assert (result.available()); + assert (result.data() == 123); + assert (!result.failed()); +} + + +void ActiveDispatcherTest::testFailure() +{ + ActiveObject activeObj; + ActiveResult result = activeObj.testMethod(100); + result.wait(); + assert (result.available()); + assert (result.failed()); + std::string msg = result.error(); + assert (msg == "n == 100"); +} + + +void ActiveDispatcherTest::setUp() +{ +} + + +void ActiveDispatcherTest::tearDown() +{ +} + + +CppUnit::Test* ActiveDispatcherTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("ActiveDispatcherTest"); + + CppUnit_addTest(pSuite, ActiveDispatcherTest, testWait); + CppUnit_addTest(pSuite, ActiveDispatcherTest, testWaitInterval); + CppUnit_addTest(pSuite, ActiveDispatcherTest, testTryWait); + CppUnit_addTest(pSuite, ActiveDispatcherTest, testFailure); + + return pSuite; +} diff --git a/Foundation/testsuite/src/ActiveDispatcherTest.h b/Foundation/testsuite/src/ActiveDispatcherTest.h index c27f9fd68..f97b58864 100644 --- a/Foundation/testsuite/src/ActiveDispatcherTest.h +++ b/Foundation/testsuite/src/ActiveDispatcherTest.h @@ -1,76 +1,76 @@ -// -// ActiveDispatcherTest.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/ActiveDispatcherTest.h#1 $ -// -// Definition of the ActiveDispatcherTest class. -// -// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. -// 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. -// -// 3. Redistributions in any form must be accompanied by information on -// how to obtain complete source code for this software and any -// accompanying software that uses this software. The source code -// must either be included in the distribution or be available for no -// more than the cost of distribution plus a nominal fee, and must be -// freely redistributable under reasonable conditions. For an -// executable file, complete source code means the source code for all -// modules it contains. It does not include source code for modules or -// files that typically accompany the major components of the operating -// system on which the executable file runs. -// -// 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 ActiveDispatcherTest_INCLUDED -#define ActiveDispatcherTest_INCLUDED - - -#include "Poco/Foundation.h" -#include "CppUnit/TestCase.h" - - -class ActiveDispatcherTest: public CppUnit::TestCase -{ -public: - ActiveDispatcherTest(const std::string& name); - ~ActiveDispatcherTest(); - - void testWait(); - void testWaitInterval(); - void testTryWait(); - void testFailure(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // ActiveDispatcherTest_INCLUDED +// +// ActiveDispatcherTest.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/ActiveDispatcherTest.h#1 $ +// +// Definition of the ActiveDispatcherTest class. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// 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. +// +// 3. Redistributions in any form must be accompanied by information on +// how to obtain complete source code for this software and any +// accompanying software that uses this software. The source code +// must either be included in the distribution or be available for no +// more than the cost of distribution plus a nominal fee, and must be +// freely redistributable under reasonable conditions. For an +// executable file, complete source code means the source code for all +// modules it contains. It does not include source code for modules or +// files that typically accompany the major components of the operating +// system on which the executable file runs. +// +// 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 ActiveDispatcherTest_INCLUDED +#define ActiveDispatcherTest_INCLUDED + + +#include "Poco/Foundation.h" +#include "CppUnit/TestCase.h" + + +class ActiveDispatcherTest: public CppUnit::TestCase +{ +public: + ActiveDispatcherTest(const std::string& name); + ~ActiveDispatcherTest(); + + void testWait(); + void testWaitInterval(); + void testTryWait(); + void testFailure(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // ActiveDispatcherTest_INCLUDED diff --git a/Foundation/testsuite/src/ActiveMethodTest.cpp b/Foundation/testsuite/src/ActiveMethodTest.cpp index 85ce7926d..656c2bc26 100644 --- a/Foundation/testsuite/src/ActiveMethodTest.cpp +++ b/Foundation/testsuite/src/ActiveMethodTest.cpp @@ -1,174 +1,174 @@ -// -// ActiveMethodTest.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/ActiveMethodTest.cpp#1 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "ActiveMethodTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/ActiveMethod.h" -#include "Poco/Thread.h" -#include "Poco/Event.h" -#include "Poco/Exception.h" - - -using Poco::ActiveMethod; -using Poco::ActiveResult; -using Poco::Thread; -using Poco::Event; -using Poco::Exception; - - -namespace -{ - class ActiveObject - { - public: - ActiveObject(): - testMethod(this, &ActiveObject::testMethodImpl) - { - } - - ~ActiveObject() - { - } - - ActiveMethod testMethod; - - void cont() - { - _continue.set(); - } - - protected: - int testMethodImpl(const int& n) - { - if (n == 100) throw Exception("n == 100"); - _continue.wait(); - return n; - } - - private: - Event _continue; - }; -} - - -ActiveMethodTest::ActiveMethodTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -ActiveMethodTest::~ActiveMethodTest() -{ -} - - -void ActiveMethodTest::testWait() -{ - ActiveObject activeObj; - ActiveResult result = activeObj.testMethod(123); - assert (!result.available()); - activeObj.cont(); - result.wait(); - assert (result.available()); - assert (result.data() == 123); - assert (!result.failed()); -} - - -void ActiveMethodTest::testWaitInterval() -{ - ActiveObject activeObj; - ActiveResult result = activeObj.testMethod(123); - assert (!result.available()); - try - { - result.wait(100); - fail("wait must fail"); - } - catch (Exception&) - { - } - activeObj.cont(); - result.wait(10000); - assert (result.available()); - assert (result.data() == 123); - assert (!result.failed()); -} - - -void ActiveMethodTest::testTryWait() -{ - ActiveObject activeObj; - ActiveResult result = activeObj.testMethod(123); - assert (!result.available()); - assert (!result.tryWait(200)); - activeObj.cont(); - assert (result.tryWait(10000)); - assert (result.available()); - assert (result.data() == 123); - assert (!result.failed()); -} - - -void ActiveMethodTest::testFailure() -{ - ActiveObject activeObj; - ActiveResult result = activeObj.testMethod(100); - result.wait(); - assert (result.available()); - assert (result.failed()); - std::string msg = result.error(); - assert (msg == "n == 100"); -} - - -void ActiveMethodTest::setUp() -{ -} - - -void ActiveMethodTest::tearDown() -{ -} - - -CppUnit::Test* ActiveMethodTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("ActiveMethodTest"); - - CppUnit_addTest(pSuite, ActiveMethodTest, testWait); - CppUnit_addTest(pSuite, ActiveMethodTest, testWaitInterval); - CppUnit_addTest(pSuite, ActiveMethodTest, testTryWait); - CppUnit_addTest(pSuite, ActiveMethodTest, testFailure); - - return pSuite; -} +// +// ActiveMethodTest.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/ActiveMethodTest.cpp#1 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "ActiveMethodTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/ActiveMethod.h" +#include "Poco/Thread.h" +#include "Poco/Event.h" +#include "Poco/Exception.h" + + +using Poco::ActiveMethod; +using Poco::ActiveResult; +using Poco::Thread; +using Poco::Event; +using Poco::Exception; + + +namespace +{ + class ActiveObject + { + public: + ActiveObject(): + testMethod(this, &ActiveObject::testMethodImpl) + { + } + + ~ActiveObject() + { + } + + ActiveMethod testMethod; + + void cont() + { + _continue.set(); + } + + protected: + int testMethodImpl(const int& n) + { + if (n == 100) throw Exception("n == 100"); + _continue.wait(); + return n; + } + + private: + Event _continue; + }; +} + + +ActiveMethodTest::ActiveMethodTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +ActiveMethodTest::~ActiveMethodTest() +{ +} + + +void ActiveMethodTest::testWait() +{ + ActiveObject activeObj; + ActiveResult result = activeObj.testMethod(123); + assert (!result.available()); + activeObj.cont(); + result.wait(); + assert (result.available()); + assert (result.data() == 123); + assert (!result.failed()); +} + + +void ActiveMethodTest::testWaitInterval() +{ + ActiveObject activeObj; + ActiveResult result = activeObj.testMethod(123); + assert (!result.available()); + try + { + result.wait(100); + fail("wait must fail"); + } + catch (Exception&) + { + } + activeObj.cont(); + result.wait(10000); + assert (result.available()); + assert (result.data() == 123); + assert (!result.failed()); +} + + +void ActiveMethodTest::testTryWait() +{ + ActiveObject activeObj; + ActiveResult result = activeObj.testMethod(123); + assert (!result.available()); + assert (!result.tryWait(200)); + activeObj.cont(); + assert (result.tryWait(10000)); + assert (result.available()); + assert (result.data() == 123); + assert (!result.failed()); +} + + +void ActiveMethodTest::testFailure() +{ + ActiveObject activeObj; + ActiveResult result = activeObj.testMethod(100); + result.wait(); + assert (result.available()); + assert (result.failed()); + std::string msg = result.error(); + assert (msg == "n == 100"); +} + + +void ActiveMethodTest::setUp() +{ +} + + +void ActiveMethodTest::tearDown() +{ +} + + +CppUnit::Test* ActiveMethodTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("ActiveMethodTest"); + + CppUnit_addTest(pSuite, ActiveMethodTest, testWait); + CppUnit_addTest(pSuite, ActiveMethodTest, testWaitInterval); + CppUnit_addTest(pSuite, ActiveMethodTest, testTryWait); + CppUnit_addTest(pSuite, ActiveMethodTest, testFailure); + + return pSuite; +} diff --git a/Foundation/testsuite/src/ActiveMethodTest.h b/Foundation/testsuite/src/ActiveMethodTest.h index 2611c6df4..f0767404c 100644 --- a/Foundation/testsuite/src/ActiveMethodTest.h +++ b/Foundation/testsuite/src/ActiveMethodTest.h @@ -1,63 +1,63 @@ -// -// ActiveMethodTest.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/ActiveMethodTest.h#1 $ -// -// Definition of the ActiveMethodTest class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 ActiveMethodTest_INCLUDED -#define ActiveMethodTest_INCLUDED - - -#include "Poco/Foundation.h" -#include "CppUnit/TestCase.h" - - -class ActiveMethodTest: public CppUnit::TestCase -{ -public: - ActiveMethodTest(const std::string& name); - ~ActiveMethodTest(); - - void testWait(); - void testWaitInterval(); - void testTryWait(); - void testFailure(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // ActiveMethodTest_INCLUDED +// +// ActiveMethodTest.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/ActiveMethodTest.h#1 $ +// +// Definition of the ActiveMethodTest class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 ActiveMethodTest_INCLUDED +#define ActiveMethodTest_INCLUDED + + +#include "Poco/Foundation.h" +#include "CppUnit/TestCase.h" + + +class ActiveMethodTest: public CppUnit::TestCase +{ +public: + ActiveMethodTest(const std::string& name); + ~ActiveMethodTest(); + + void testWait(); + void testWaitInterval(); + void testTryWait(); + void testFailure(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // ActiveMethodTest_INCLUDED diff --git a/Foundation/testsuite/src/ActivityTest.cpp b/Foundation/testsuite/src/ActivityTest.cpp index 013450419..e5859e188 100644 --- a/Foundation/testsuite/src/ActivityTest.cpp +++ b/Foundation/testsuite/src/ActivityTest.cpp @@ -1,124 +1,124 @@ -// -// ActivityTest.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/ActivityTest.cpp#1 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "ActivityTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/Activity.h" -#include "Poco/Thread.h" - - -using Poco::Activity; -using Poco::Thread; - - -namespace -{ - class ActiveObject - { - public: - ActiveObject(): - _activity(this, &ActiveObject::run), - _count(0) - { - } - - ~ActiveObject() - { - } - - Activity& activity() - { - return _activity; - } - - int count() const - { - return _count; - } - - protected: - void run() - { - while (!_activity.isStopped()) - ++_count; - } - - private: - Activity _activity; - int _count; - }; -} - - -ActivityTest::ActivityTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -ActivityTest::~ActivityTest() -{ -} - - -void ActivityTest::testActivity() -{ - ActiveObject activeObj; - assert (activeObj.activity().isStopped()); - activeObj.activity().start(); - assert (!activeObj.activity().isStopped()); - Thread::sleep(1000); - assert (activeObj.activity().isRunning()); - activeObj.activity().stop(); - activeObj.activity().wait(); - assert (activeObj.count() > 0); -} - - -void ActivityTest::setUp() -{ -} - - -void ActivityTest::tearDown() -{ -} - - -CppUnit::Test* ActivityTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("ActivityTest"); - - CppUnit_addTest(pSuite, ActivityTest, testActivity); - - return pSuite; -} +// +// ActivityTest.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/ActivityTest.cpp#1 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "ActivityTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/Activity.h" +#include "Poco/Thread.h" + + +using Poco::Activity; +using Poco::Thread; + + +namespace +{ + class ActiveObject + { + public: + ActiveObject(): + _activity(this, &ActiveObject::run), + _count(0) + { + } + + ~ActiveObject() + { + } + + Activity& activity() + { + return _activity; + } + + int count() const + { + return _count; + } + + protected: + void run() + { + while (!_activity.isStopped()) + ++_count; + } + + private: + Activity _activity; + int _count; + }; +} + + +ActivityTest::ActivityTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +ActivityTest::~ActivityTest() +{ +} + + +void ActivityTest::testActivity() +{ + ActiveObject activeObj; + assert (activeObj.activity().isStopped()); + activeObj.activity().start(); + assert (!activeObj.activity().isStopped()); + Thread::sleep(1000); + assert (activeObj.activity().isRunning()); + activeObj.activity().stop(); + activeObj.activity().wait(); + assert (activeObj.count() > 0); +} + + +void ActivityTest::setUp() +{ +} + + +void ActivityTest::tearDown() +{ +} + + +CppUnit::Test* ActivityTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("ActivityTest"); + + CppUnit_addTest(pSuite, ActivityTest, testActivity); + + return pSuite; +} diff --git a/Foundation/testsuite/src/ActivityTest.h b/Foundation/testsuite/src/ActivityTest.h index 043e6af65..22edaa37b 100644 --- a/Foundation/testsuite/src/ActivityTest.h +++ b/Foundation/testsuite/src/ActivityTest.h @@ -1,60 +1,60 @@ -// -// ActivityTest.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/ActivityTest.h#1 $ -// -// Definition of the ActivityTest class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 ActivityTest_INCLUDED -#define ActivityTest_INCLUDED - - -#include "Poco/Foundation.h" -#include "CppUnit/TestCase.h" - - -class ActivityTest: public CppUnit::TestCase -{ -public: - ActivityTest(const std::string& name); - ~ActivityTest(); - - void testActivity(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // ActivityTest_INCLUDED +// +// ActivityTest.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/ActivityTest.h#1 $ +// +// Definition of the ActivityTest class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 ActivityTest_INCLUDED +#define ActivityTest_INCLUDED + + +#include "Poco/Foundation.h" +#include "CppUnit/TestCase.h" + + +class ActivityTest: public CppUnit::TestCase +{ +public: + ActivityTest(const std::string& name); + ~ActivityTest(); + + void testActivity(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // ActivityTest_INCLUDED diff --git a/Foundation/testsuite/src/AnyTest.cpp b/Foundation/testsuite/src/AnyTest.cpp index fe57acbd9..0feffd0ee 100644 --- a/Foundation/testsuite/src/AnyTest.cpp +++ b/Foundation/testsuite/src/AnyTest.cpp @@ -1,142 +1,142 @@ -// -// AnyTest.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/AnyTest.cpp#2 $ -// -// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "AnyTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/Exception.h" -#include "Poco/Any.h" -#include "Poco/Bugcheck.h" -#include - - -using namespace Poco; - - -class SomeClass -{ -public: - int i; - std::string str; - SomeClass(int h, std::string s): i (h), str(s) - { - }; - bool operator==(const SomeClass& other) const - { - return i == other.i && str == other.str; - } -}; - - -AnyTest::AnyTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -AnyTest::~AnyTest() -{ -} - - -void AnyTest::testInt() -{ - Any a = 13; - assert (a.type() == typeid(int)); - int* i = AnyCast(&a); - assert (*i == 13); - Any b = a; - assert (b.type() == typeid(int)); - int *cpyI = AnyCast(&b); - assert (*cpyI == *i); - *cpyI = 20; - assert (*cpyI != *i); - std::string* s = AnyCast(&a); - assert (s == NULL); - - int tmp = AnyCast(a); - const Any c = a; - tmp = AnyCast(a); -} - - -void AnyTest::testComplexType() -{ - SomeClass str(13,std::string("hello")); - Any a = str; - Any b = a; - assert (a.type() == typeid(SomeClass)); - assert (b.type() == typeid(SomeClass)); - SomeClass str2 = AnyCast(a); - assert (str == str2); - const SomeClass& strCRef = RefAnyCast(a); - assert (str == strCRef); - SomeClass& strRef = RefAnyCast(a); - assert (str == strRef); -} - - -void AnyTest::testVector() -{ - std::vector tmp; - tmp.push_back(1); - tmp.push_back(2); - tmp.push_back(3); - Any a = tmp; - assert (a.type() == typeid(std::vector)); - std::vectortmp2 = AnyCast >(a); - const std::vector& vecCRef = RefAnyCast >(a); - std::vector& vecRef = RefAnyCast >(a); - vecRef[0] = 0; - assert (vecRef[0] == vecCRef[0]); -} - - -void AnyTest::setUp() -{ -} - - -void AnyTest::tearDown() -{ -} - - -CppUnit::Test* AnyTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("AnyTest"); - - CppUnit_addTest(pSuite, AnyTest, testInt); - CppUnit_addTest(pSuite, AnyTest, testComplexType); - CppUnit_addTest(pSuite, AnyTest, testVector); - - return pSuite; -} +// +// AnyTest.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/AnyTest.cpp#2 $ +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "AnyTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/Exception.h" +#include "Poco/Any.h" +#include "Poco/Bugcheck.h" +#include + + +using namespace Poco; + + +class SomeClass +{ +public: + int i; + std::string str; + SomeClass(int h, std::string s): i (h), str(s) + { + }; + bool operator==(const SomeClass& other) const + { + return i == other.i && str == other.str; + } +}; + + +AnyTest::AnyTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +AnyTest::~AnyTest() +{ +} + + +void AnyTest::testInt() +{ + Any a = 13; + assert (a.type() == typeid(int)); + int* i = AnyCast(&a); + assert (*i == 13); + Any b = a; + assert (b.type() == typeid(int)); + int *cpyI = AnyCast(&b); + assert (*cpyI == *i); + *cpyI = 20; + assert (*cpyI != *i); + std::string* s = AnyCast(&a); + assert (s == NULL); + + int tmp = AnyCast(a); + const Any c = a; + tmp = AnyCast(a); +} + + +void AnyTest::testComplexType() +{ + SomeClass str(13,std::string("hello")); + Any a = str; + Any b = a; + assert (a.type() == typeid(SomeClass)); + assert (b.type() == typeid(SomeClass)); + SomeClass str2 = AnyCast(a); + assert (str == str2); + const SomeClass& strCRef = RefAnyCast(a); + assert (str == strCRef); + SomeClass& strRef = RefAnyCast(a); + assert (str == strRef); +} + + +void AnyTest::testVector() +{ + std::vector tmp; + tmp.push_back(1); + tmp.push_back(2); + tmp.push_back(3); + Any a = tmp; + assert (a.type() == typeid(std::vector)); + std::vectortmp2 = AnyCast >(a); + const std::vector& vecCRef = RefAnyCast >(a); + std::vector& vecRef = RefAnyCast >(a); + vecRef[0] = 0; + assert (vecRef[0] == vecCRef[0]); +} + + +void AnyTest::setUp() +{ +} + + +void AnyTest::tearDown() +{ +} + + +CppUnit::Test* AnyTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("AnyTest"); + + CppUnit_addTest(pSuite, AnyTest, testInt); + CppUnit_addTest(pSuite, AnyTest, testComplexType); + CppUnit_addTest(pSuite, AnyTest, testVector); + + return pSuite; +} diff --git a/Foundation/testsuite/src/AnyTest.h b/Foundation/testsuite/src/AnyTest.h index 12fd30087..a04bc12a6 100644 --- a/Foundation/testsuite/src/AnyTest.h +++ b/Foundation/testsuite/src/AnyTest.h @@ -1,58 +1,58 @@ -// -// AnyTest.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/AnyTest.h#1 $ -// -// Tests for Any types -// -// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 AnyTest_INCLUDED -#define AnyTest_INCLUDED - - -#include "Poco/Foundation.h" -#include "CppUnit/TestCase.h" - - -class AnyTest: public CppUnit::TestCase -{ -public: - AnyTest(const std::string& name); - ~AnyTest(); - - void testInt(); - void testComplexType(); - void testVector(); - - void setUp(); - void tearDown(); - static CppUnit::Test* suite(); -}; - - -#endif // AnyTest_INCLUDED +// +// AnyTest.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/AnyTest.h#1 $ +// +// Tests for Any types +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 AnyTest_INCLUDED +#define AnyTest_INCLUDED + + +#include "Poco/Foundation.h" +#include "CppUnit/TestCase.h" + + +class AnyTest: public CppUnit::TestCase +{ +public: + AnyTest(const std::string& name); + ~AnyTest(); + + void testInt(); + void testComplexType(); + void testVector(); + + void setUp(); + void tearDown(); + static CppUnit::Test* suite(); +}; + + +#endif // AnyTest_INCLUDED diff --git a/Foundation/testsuite/src/AutoPtrTest.cpp b/Foundation/testsuite/src/AutoPtrTest.cpp index d0b65fc91..3a5d1c338 100644 --- a/Foundation/testsuite/src/AutoPtrTest.cpp +++ b/Foundation/testsuite/src/AutoPtrTest.cpp @@ -1,204 +1,204 @@ -// -// AutoPtrTest.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/AutoPtrTest.cpp#2 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "AutoPtrTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/AutoPtr.h" -#include "Poco/Exception.h" - - -using Poco::AutoPtr; -using Poco::NullPointerException; - - -namespace -{ - class TestObj - { - public: - TestObj(): _rc(1) - { - ++_count; - } - - void duplicate() - { - ++_rc; - } - - void release() - { - if (--_rc == 0) - delete this; - } - - int rc() const - { - return _rc; - } - - static int count() - { - return _count; - } - - protected: - ~TestObj() - { - --_count; - } - - private: - int _rc; - static int _count; - }; - - int TestObj::_count = 0; -} - - -AutoPtrTest::AutoPtrTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -AutoPtrTest::~AutoPtrTest() -{ -} - - -void AutoPtrTest::testAutoPtr() -{ - { - AutoPtr ptr = new TestObj; - assert (ptr->rc() == 1); - AutoPtr ptr2 = ptr; - assert (ptr->rc() == 2); - ptr2 = new TestObj; - assert (ptr->rc() == 1); - AutoPtr ptr3; - ptr3 = ptr2; - assert (ptr2->rc() == 2); - ptr3 = new TestObj; - assert (ptr2->rc() == 1); - ptr3 = ptr2; - assert (ptr2->rc() == 2); - assert (TestObj::count() > 0); - } - assert (TestObj::count() == 0); -} - - -void AutoPtrTest::testOps() -{ - AutoPtr ptr1; - assertNull(ptr1.get()); - TestObj* pTO1 = new TestObj; - TestObj* pTO2 = new TestObj; - if (pTO2 < pTO1) - { - TestObj* pTmp = pTO1; - pTO1 = pTO2; - pTO2 = pTmp; - } - assert (pTO1 < pTO2); - ptr1 = pTO1; - AutoPtr ptr2 = pTO2; - AutoPtr ptr3 = ptr1; - AutoPtr ptr4; - assert (ptr1.get() == pTO1); - assert (ptr1 == pTO1); - assert (ptr2.get() == pTO2); - assert (ptr2 == pTO2); - assert (ptr3.get() == pTO1); - assert (ptr3 == pTO1); - - assert (ptr1 == pTO1); - assert (ptr1 != pTO2); - assert (ptr1 < pTO2); - assert (ptr1 <= pTO2); - assert (ptr2 > pTO1); - assert (ptr2 >= pTO1); - - assert (ptr1 == ptr3); - assert (ptr1 != ptr2); - assert (ptr1 < ptr2); - assert (ptr1 <= ptr2); - assert (ptr2 > ptr1); - assert (ptr2 >= ptr1); - - ptr1 = pTO1; - ptr2 = pTO2; - ptr1.swap(ptr2); - assert (ptr2.get() == pTO1); - assert (ptr1.get() == pTO2); - - try - { - assert (ptr4->rc() > 0); - fail ("must throw NullPointerException"); - } - catch (NullPointerException&) - { - } - - assert (!(ptr4 == ptr1)); - assert (!(ptr4 == ptr2)); - assert (ptr4 != ptr1); - assert (ptr4 != ptr2); - - ptr4 = ptr2; - assert (ptr4 == ptr2); - assert (!(ptr4 != ptr2)); -} - - -void AutoPtrTest::setUp() -{ -} - - -void AutoPtrTest::tearDown() -{ -} - - -CppUnit::Test* AutoPtrTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("AutoPtrTest"); - - CppUnit_addTest(pSuite, AutoPtrTest, testAutoPtr); - CppUnit_addTest(pSuite, AutoPtrTest, testOps); - - return pSuite; -} +// +// AutoPtrTest.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/AutoPtrTest.cpp#2 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "AutoPtrTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/AutoPtr.h" +#include "Poco/Exception.h" + + +using Poco::AutoPtr; +using Poco::NullPointerException; + + +namespace +{ + class TestObj + { + public: + TestObj(): _rc(1) + { + ++_count; + } + + void duplicate() + { + ++_rc; + } + + void release() + { + if (--_rc == 0) + delete this; + } + + int rc() const + { + return _rc; + } + + static int count() + { + return _count; + } + + protected: + ~TestObj() + { + --_count; + } + + private: + int _rc; + static int _count; + }; + + int TestObj::_count = 0; +} + + +AutoPtrTest::AutoPtrTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +AutoPtrTest::~AutoPtrTest() +{ +} + + +void AutoPtrTest::testAutoPtr() +{ + { + AutoPtr ptr = new TestObj; + assert (ptr->rc() == 1); + AutoPtr ptr2 = ptr; + assert (ptr->rc() == 2); + ptr2 = new TestObj; + assert (ptr->rc() == 1); + AutoPtr ptr3; + ptr3 = ptr2; + assert (ptr2->rc() == 2); + ptr3 = new TestObj; + assert (ptr2->rc() == 1); + ptr3 = ptr2; + assert (ptr2->rc() == 2); + assert (TestObj::count() > 0); + } + assert (TestObj::count() == 0); +} + + +void AutoPtrTest::testOps() +{ + AutoPtr ptr1; + assertNull(ptr1.get()); + TestObj* pTO1 = new TestObj; + TestObj* pTO2 = new TestObj; + if (pTO2 < pTO1) + { + TestObj* pTmp = pTO1; + pTO1 = pTO2; + pTO2 = pTmp; + } + assert (pTO1 < pTO2); + ptr1 = pTO1; + AutoPtr ptr2 = pTO2; + AutoPtr ptr3 = ptr1; + AutoPtr ptr4; + assert (ptr1.get() == pTO1); + assert (ptr1 == pTO1); + assert (ptr2.get() == pTO2); + assert (ptr2 == pTO2); + assert (ptr3.get() == pTO1); + assert (ptr3 == pTO1); + + assert (ptr1 == pTO1); + assert (ptr1 != pTO2); + assert (ptr1 < pTO2); + assert (ptr1 <= pTO2); + assert (ptr2 > pTO1); + assert (ptr2 >= pTO1); + + assert (ptr1 == ptr3); + assert (ptr1 != ptr2); + assert (ptr1 < ptr2); + assert (ptr1 <= ptr2); + assert (ptr2 > ptr1); + assert (ptr2 >= ptr1); + + ptr1 = pTO1; + ptr2 = pTO2; + ptr1.swap(ptr2); + assert (ptr2.get() == pTO1); + assert (ptr1.get() == pTO2); + + try + { + assert (ptr4->rc() > 0); + fail ("must throw NullPointerException"); + } + catch (NullPointerException&) + { + } + + assert (!(ptr4 == ptr1)); + assert (!(ptr4 == ptr2)); + assert (ptr4 != ptr1); + assert (ptr4 != ptr2); + + ptr4 = ptr2; + assert (ptr4 == ptr2); + assert (!(ptr4 != ptr2)); +} + + +void AutoPtrTest::setUp() +{ +} + + +void AutoPtrTest::tearDown() +{ +} + + +CppUnit::Test* AutoPtrTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("AutoPtrTest"); + + CppUnit_addTest(pSuite, AutoPtrTest, testAutoPtr); + CppUnit_addTest(pSuite, AutoPtrTest, testOps); + + return pSuite; +} diff --git a/Foundation/testsuite/src/AutoPtrTest.h b/Foundation/testsuite/src/AutoPtrTest.h index c9d680875..a5d86923f 100644 --- a/Foundation/testsuite/src/AutoPtrTest.h +++ b/Foundation/testsuite/src/AutoPtrTest.h @@ -1,61 +1,61 @@ -// -// AutoPtrTest.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/AutoPtrTest.h#1 $ -// -// Definition of the AutoPtrTest class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 AutoPtrTest_INCLUDED -#define AutoPtrTest_INCLUDED - - -#include "Poco/Foundation.h" -#include "CppUnit/TestCase.h" - - -class AutoPtrTest: public CppUnit::TestCase -{ -public: - AutoPtrTest(const std::string& name); - ~AutoPtrTest(); - - void testAutoPtr(); - void testOps(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // AutoPtrTest_INCLUDED +// +// AutoPtrTest.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/AutoPtrTest.h#1 $ +// +// Definition of the AutoPtrTest class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 AutoPtrTest_INCLUDED +#define AutoPtrTest_INCLUDED + + +#include "Poco/Foundation.h" +#include "CppUnit/TestCase.h" + + +class AutoPtrTest: public CppUnit::TestCase +{ +public: + AutoPtrTest(const std::string& name); + ~AutoPtrTest(); + + void testAutoPtr(); + void testOps(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // AutoPtrTest_INCLUDED diff --git a/Foundation/testsuite/src/AutoReleasePoolTest.cpp b/Foundation/testsuite/src/AutoReleasePoolTest.cpp index 6ad9e7bbb..2dad0b31c 100644 --- a/Foundation/testsuite/src/AutoReleasePoolTest.cpp +++ b/Foundation/testsuite/src/AutoReleasePoolTest.cpp @@ -1,126 +1,126 @@ -// -// AutoReleasePoolTest.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/AutoReleasePoolTest.cpp#1 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "AutoReleasePoolTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/AutoReleasePool.h" - - -using Poco::AutoReleasePool; - - -namespace -{ - class TestObj - { - public: - TestObj(): _rc(1) - { - ++_count; - } - - void duplicate() - { - ++_rc; - } - - void release() - { - if (--_rc == 0) - delete this; - } - - int rc() const - { - return _rc; - } - - static int count() - { - return _count; - } - - protected: - ~TestObj() - { - --_count; - } - - private: - int _rc; - static int _count; - }; - - int TestObj::_count = 0; -} - - -AutoReleasePoolTest::AutoReleasePoolTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -AutoReleasePoolTest::~AutoReleasePoolTest() -{ -} - - -void AutoReleasePoolTest::testAutoReleasePool() -{ - AutoReleasePool arp; - arp.add(new TestObj); - arp.add(new TestObj); - assert (TestObj::count() == 2); - arp.release(); - assert (TestObj::count() == 0); -} - - -void AutoReleasePoolTest::setUp() -{ -} - - -void AutoReleasePoolTest::tearDown() -{ -} - - -CppUnit::Test* AutoReleasePoolTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("AutoReleasePoolTest"); - - CppUnit_addTest(pSuite, AutoReleasePoolTest, testAutoReleasePool); - - return pSuite; -} +// +// AutoReleasePoolTest.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/AutoReleasePoolTest.cpp#1 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "AutoReleasePoolTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/AutoReleasePool.h" + + +using Poco::AutoReleasePool; + + +namespace +{ + class TestObj + { + public: + TestObj(): _rc(1) + { + ++_count; + } + + void duplicate() + { + ++_rc; + } + + void release() + { + if (--_rc == 0) + delete this; + } + + int rc() const + { + return _rc; + } + + static int count() + { + return _count; + } + + protected: + ~TestObj() + { + --_count; + } + + private: + int _rc; + static int _count; + }; + + int TestObj::_count = 0; +} + + +AutoReleasePoolTest::AutoReleasePoolTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +AutoReleasePoolTest::~AutoReleasePoolTest() +{ +} + + +void AutoReleasePoolTest::testAutoReleasePool() +{ + AutoReleasePool arp; + arp.add(new TestObj); + arp.add(new TestObj); + assert (TestObj::count() == 2); + arp.release(); + assert (TestObj::count() == 0); +} + + +void AutoReleasePoolTest::setUp() +{ +} + + +void AutoReleasePoolTest::tearDown() +{ +} + + +CppUnit::Test* AutoReleasePoolTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("AutoReleasePoolTest"); + + CppUnit_addTest(pSuite, AutoReleasePoolTest, testAutoReleasePool); + + return pSuite; +} diff --git a/Foundation/testsuite/src/AutoReleasePoolTest.h b/Foundation/testsuite/src/AutoReleasePoolTest.h index d4cf9d551..9df1500d3 100644 --- a/Foundation/testsuite/src/AutoReleasePoolTest.h +++ b/Foundation/testsuite/src/AutoReleasePoolTest.h @@ -1,60 +1,60 @@ -// -// AutoReleasePoolTest.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/AutoReleasePoolTest.h#1 $ -// -// Definition of the AutoReleasePoolTest class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 AutoReleasePoolTest_INCLUDED -#define AutoReleasePoolTest_INCLUDED - - -#include "Poco/Foundation.h" -#include "CppUnit/TestCase.h" - - -class AutoReleasePoolTest: public CppUnit::TestCase -{ -public: - AutoReleasePoolTest(const std::string& name); - ~AutoReleasePoolTest(); - - void testAutoReleasePool(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // AutoReleasePoolTest_INCLUDED +// +// AutoReleasePoolTest.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/AutoReleasePoolTest.h#1 $ +// +// Definition of the AutoReleasePoolTest class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 AutoReleasePoolTest_INCLUDED +#define AutoReleasePoolTest_INCLUDED + + +#include "Poco/Foundation.h" +#include "CppUnit/TestCase.h" + + +class AutoReleasePoolTest: public CppUnit::TestCase +{ +public: + AutoReleasePoolTest(const std::string& name); + ~AutoReleasePoolTest(); + + void testAutoReleasePool(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // AutoReleasePoolTest_INCLUDED diff --git a/Foundation/testsuite/src/Base64Test.cpp b/Foundation/testsuite/src/Base64Test.cpp index e1f8d8d29..16f297cd1 100644 --- a/Foundation/testsuite/src/Base64Test.cpp +++ b/Foundation/testsuite/src/Base64Test.cpp @@ -1,199 +1,199 @@ -// -// Base64Test.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/Base64Test.cpp#1 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Base64Test.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/Base64Encoder.h" -#include "Poco/Base64Decoder.h" -#include "Poco/Exception.h" -#include - - -using Poco::Base64Encoder; -using Poco::Base64Decoder; -using Poco::DataFormatException; - - -Base64Test::Base64Test(const std::string& name): CppUnit::TestCase(name) -{ -} - - -Base64Test::~Base64Test() -{ -} - - -void Base64Test::testEncoder() -{ - { - std::ostringstream str; - Base64Encoder encoder(str); - encoder << std::string("\00\01\02\03\04\05", 6); - encoder.close(); - assert (str.str() == "AAECAwQF"); - } - { - std::ostringstream str; - Base64Encoder encoder(str); - encoder << std::string("\00\01\02\03", 4); - encoder.close(); - assert (str.str() == "AAECAw=="); - } - { - std::ostringstream str; - Base64Encoder encoder(str); - encoder << "ABCDEF"; - encoder.close(); - assert (str.str() == "QUJDREVG"); - } -} - - -void Base64Test::testDecoder() -{ - { - std::istringstream istr("AAECAwQF"); - Base64Decoder decoder(istr); - assert (decoder.good() && decoder.get() == 0); - assert (decoder.good() && decoder.get() == 1); - assert (decoder.good() && decoder.get() == 2); - assert (decoder.good() && decoder.get() == 3); - assert (decoder.good() && decoder.get() == 4); - assert (decoder.good() && decoder.get() == 5); - assert (decoder.good() && decoder.get() == -1); - } - { - std::istringstream istr("AAECAwQ="); - Base64Decoder decoder(istr); - assert (decoder.good() && decoder.get() == 0); - assert (decoder.good() && decoder.get() == 1); - assert (decoder.good() && decoder.get() == 2); - assert (decoder.good() && decoder.get() == 3); - assert (decoder.good() && decoder.get() == 4); - assert (decoder.good() && decoder.get() == -1); - } - { - std::istringstream istr("AAECAw=="); - Base64Decoder decoder(istr); - assert (decoder.good() && decoder.get() == 0); - assert (decoder.good() && decoder.get() == 1); - assert (decoder.good() && decoder.get() == 2); - assert (decoder.good() && decoder.get() == 3); - assert (decoder.good() && decoder.get() == -1); - } - { - std::istringstream istr("QUJDREVG"); - Base64Decoder decoder(istr); - std::string s; - decoder >> s; - assert (s == "ABCDEF"); - assert (decoder.eof()); - assert (!decoder.fail()); - } - { - std::istringstream istr("QUJ\r\nDRE\r\nVG"); - Base64Decoder decoder(istr); - std::string s; - decoder >> s; - assert (s == "ABCDEF"); - assert (decoder.eof()); - assert (!decoder.fail()); - } - { - std::istringstream istr("QUJD#REVG"); - Base64Decoder decoder(istr); - std::string s; - try - { - decoder >> s; - assert (decoder.bad()); - } - catch (DataFormatException&) - { - } - assert (!decoder.eof()); - } -} - - -void Base64Test::testEncodeDecode() -{ - { - std::stringstream str; - Base64Encoder encoder(str); - encoder << "The quick brown fox "; - encoder << "jumped over the lazy dog."; - encoder.close(); - Base64Decoder decoder(str); - std::string s; - int c = decoder.get(); - while (c != -1) { s += char(c); c = decoder.get(); } - assert (s == "The quick brown fox jumped over the lazy dog."); - } - { - std::string src; - for (int i = 0; i < 255; ++i) src += char(i); - std::stringstream str; - Base64Encoder encoder(str); - encoder.write(src.data(), (std::streamsize) src.size()); - encoder.close(); - Base64Decoder decoder(str); - std::string s; - int c = decoder.get(); - while (c != -1) { s += char(c); c = decoder.get(); } - assert (s == src); - } -} - - -void Base64Test::setUp() -{ -} - - -void Base64Test::tearDown() -{ -} - - -CppUnit::Test* Base64Test::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("Base64Test"); - - CppUnit_addTest(pSuite, Base64Test, testEncoder); - CppUnit_addTest(pSuite, Base64Test, testDecoder); - CppUnit_addTest(pSuite, Base64Test, testEncodeDecode); - - return pSuite; -} +// +// Base64Test.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/Base64Test.cpp#1 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Base64Test.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/Base64Encoder.h" +#include "Poco/Base64Decoder.h" +#include "Poco/Exception.h" +#include + + +using Poco::Base64Encoder; +using Poco::Base64Decoder; +using Poco::DataFormatException; + + +Base64Test::Base64Test(const std::string& name): CppUnit::TestCase(name) +{ +} + + +Base64Test::~Base64Test() +{ +} + + +void Base64Test::testEncoder() +{ + { + std::ostringstream str; + Base64Encoder encoder(str); + encoder << std::string("\00\01\02\03\04\05", 6); + encoder.close(); + assert (str.str() == "AAECAwQF"); + } + { + std::ostringstream str; + Base64Encoder encoder(str); + encoder << std::string("\00\01\02\03", 4); + encoder.close(); + assert (str.str() == "AAECAw=="); + } + { + std::ostringstream str; + Base64Encoder encoder(str); + encoder << "ABCDEF"; + encoder.close(); + assert (str.str() == "QUJDREVG"); + } +} + + +void Base64Test::testDecoder() +{ + { + std::istringstream istr("AAECAwQF"); + Base64Decoder decoder(istr); + assert (decoder.good() && decoder.get() == 0); + assert (decoder.good() && decoder.get() == 1); + assert (decoder.good() && decoder.get() == 2); + assert (decoder.good() && decoder.get() == 3); + assert (decoder.good() && decoder.get() == 4); + assert (decoder.good() && decoder.get() == 5); + assert (decoder.good() && decoder.get() == -1); + } + { + std::istringstream istr("AAECAwQ="); + Base64Decoder decoder(istr); + assert (decoder.good() && decoder.get() == 0); + assert (decoder.good() && decoder.get() == 1); + assert (decoder.good() && decoder.get() == 2); + assert (decoder.good() && decoder.get() == 3); + assert (decoder.good() && decoder.get() == 4); + assert (decoder.good() && decoder.get() == -1); + } + { + std::istringstream istr("AAECAw=="); + Base64Decoder decoder(istr); + assert (decoder.good() && decoder.get() == 0); + assert (decoder.good() && decoder.get() == 1); + assert (decoder.good() && decoder.get() == 2); + assert (decoder.good() && decoder.get() == 3); + assert (decoder.good() && decoder.get() == -1); + } + { + std::istringstream istr("QUJDREVG"); + Base64Decoder decoder(istr); + std::string s; + decoder >> s; + assert (s == "ABCDEF"); + assert (decoder.eof()); + assert (!decoder.fail()); + } + { + std::istringstream istr("QUJ\r\nDRE\r\nVG"); + Base64Decoder decoder(istr); + std::string s; + decoder >> s; + assert (s == "ABCDEF"); + assert (decoder.eof()); + assert (!decoder.fail()); + } + { + std::istringstream istr("QUJD#REVG"); + Base64Decoder decoder(istr); + std::string s; + try + { + decoder >> s; + assert (decoder.bad()); + } + catch (DataFormatException&) + { + } + assert (!decoder.eof()); + } +} + + +void Base64Test::testEncodeDecode() +{ + { + std::stringstream str; + Base64Encoder encoder(str); + encoder << "The quick brown fox "; + encoder << "jumped over the lazy dog."; + encoder.close(); + Base64Decoder decoder(str); + std::string s; + int c = decoder.get(); + while (c != -1) { s += char(c); c = decoder.get(); } + assert (s == "The quick brown fox jumped over the lazy dog."); + } + { + std::string src; + for (int i = 0; i < 255; ++i) src += char(i); + std::stringstream str; + Base64Encoder encoder(str); + encoder.write(src.data(), (std::streamsize) src.size()); + encoder.close(); + Base64Decoder decoder(str); + std::string s; + int c = decoder.get(); + while (c != -1) { s += char(c); c = decoder.get(); } + assert (s == src); + } +} + + +void Base64Test::setUp() +{ +} + + +void Base64Test::tearDown() +{ +} + + +CppUnit::Test* Base64Test::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("Base64Test"); + + CppUnit_addTest(pSuite, Base64Test, testEncoder); + CppUnit_addTest(pSuite, Base64Test, testDecoder); + CppUnit_addTest(pSuite, Base64Test, testEncodeDecode); + + return pSuite; +} diff --git a/Foundation/testsuite/src/Base64Test.h b/Foundation/testsuite/src/Base64Test.h index b83e2a701..77a41a2a3 100644 --- a/Foundation/testsuite/src/Base64Test.h +++ b/Foundation/testsuite/src/Base64Test.h @@ -1,62 +1,62 @@ -// -// Base64Test.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/Base64Test.h#1 $ -// -// Definition of the Base64Test class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 Base64Test_INCLUDED -#define Base64Test_INCLUDED - - -#include "Poco/Foundation.h" -#include "CppUnit/TestCase.h" - - -class Base64Test: public CppUnit::TestCase -{ -public: - Base64Test(const std::string& name); - ~Base64Test(); - - void testEncoder(); - void testDecoder(); - void testEncodeDecode(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // Base64Test_INCLUDED +// +// Base64Test.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/Base64Test.h#1 $ +// +// Definition of the Base64Test class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 Base64Test_INCLUDED +#define Base64Test_INCLUDED + + +#include "Poco/Foundation.h" +#include "CppUnit/TestCase.h" + + +class Base64Test: public CppUnit::TestCase +{ +public: + Base64Test(const std::string& name); + ~Base64Test(); + + void testEncoder(); + void testDecoder(); + void testEncodeDecode(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // Base64Test_INCLUDED diff --git a/Foundation/testsuite/src/BasicEventTest.cpp b/Foundation/testsuite/src/BasicEventTest.cpp index 249ca0ad1..6e1c01d2a 100644 --- a/Foundation/testsuite/src/BasicEventTest.cpp +++ b/Foundation/testsuite/src/BasicEventTest.cpp @@ -1,358 +1,358 @@ -// -// BasicEventTest.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/BasicEventTest.cpp#2 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "BasicEventTest.h" -#include "DummyDelegate.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/Delegate.h" -#include "Poco/Expire.h" -#include "Poco/Thread.h" -#include "Poco/Exception.h" - - -using namespace Poco; - - -#define LARGEINC 100 - - -BasicEventTest::BasicEventTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -BasicEventTest::~BasicEventTest() -{ -} - -void BasicEventTest::testNoDelegate() -{ - int tmp = 0; - EventArgs args; - - assert (_count == 0); - Simple.notify(this, tmp); - assert (_count == 0); - - Simple += Delegate(this, &BasicEventTest::onSimple); - Simple -= Delegate(this, &BasicEventTest::onSimple); - Simple.notify(this, tmp); - assert (_count == 0); - - ConstSimple += Delegate(this, &BasicEventTest::onConstSimple); - ConstSimple -= Delegate(this, &BasicEventTest::onConstSimple); - ConstSimple.notify(this, tmp); - assert (_count == 0); - - //Note: passing &args will not work due to & - EventArgs* pArgs = &args; - Complex += Delegate(this, &BasicEventTest::onComplex); - Complex -= Delegate(this, &BasicEventTest::onComplex); - Complex.notify(this, pArgs); - assert (_count == 0); - - Complex2 += Delegate(this, &BasicEventTest::onComplex2); - Complex2 -= Delegate(this, &BasicEventTest::onComplex2); - Complex2.notify(this, args); - assert (_count == 0); - - const EventArgs* pCArgs = &args; - ConstComplex += Delegate(this, &BasicEventTest::onConstComplex); - ConstComplex -= Delegate(this, &BasicEventTest::onConstComplex); - ConstComplex.notify(this, pCArgs); - assert (_count == 0); - - Const2Complex += Delegate(this, &BasicEventTest::onConst2Complex); - Const2Complex -= Delegate(this, &BasicEventTest::onConst2Complex); - Const2Complex.notify(this, pArgs); - assert (_count == 0); -} - -void BasicEventTest::testSingleDelegate() -{ - int tmp = 0; - EventArgs args; - - assert (_count == 0); - - Simple += Delegate(this, &BasicEventTest::onSimple); - Simple.notify(this, tmp); - assert (_count == 1); - - ConstSimple += Delegate(this, &BasicEventTest::onConstSimple); - ConstSimple.notify(this, tmp); - assert (_count == 2); - - EventArgs* pArgs = &args; - Complex += Delegate(this, &BasicEventTest::onComplex); - Complex.notify(this, pArgs); - assert (_count == 3); - - Complex2 += Delegate(this, &BasicEventTest::onComplex2); - Complex2.notify(this, args); - assert (_count == 4); - - const EventArgs* pCArgs = &args; - ConstComplex += Delegate(this, &BasicEventTest::onConstComplex); - ConstComplex.notify(this, pCArgs); - assert (_count == 5); - - Const2Complex += Delegate(this, &BasicEventTest::onConst2Complex); - Const2Complex.notify(this, pArgs); - assert (_count == 6); - // check if 2nd notify also works - Const2Complex.notify(this, pArgs); - assert (_count == 7); - -} - -void BasicEventTest::testDuplicateRegister() -{ - int tmp = 0; - - assert (_count == 0); - - Simple += Delegate(this, &BasicEventTest::onSimple); - Simple += Delegate(this, &BasicEventTest::onSimple); - Simple.notify(this, tmp); - assert (_count == 1); - Simple -= Delegate(this, &BasicEventTest::onSimple); - Simple.notify(this, tmp); - assert (_count == 1); -} - -void BasicEventTest::testDuplicateUnregister() -{ - // duplicate unregister shouldn't give an error, - int tmp = 0; - - assert (_count == 0); - - Simple -= Delegate(this, &BasicEventTest::onSimple); // should work - Simple.notify(this, tmp); - assert (_count == 0); - - Simple += Delegate(this, &BasicEventTest::onSimple); - Simple.notify(this, tmp); - assert (_count == 1); - - Simple -= Delegate(this, &BasicEventTest::onSimple); - Simple.notify(this, tmp); - assert (_count == 1); - - Simple -= Delegate(this, &BasicEventTest::onSimple); - Simple.notify(this, tmp); - assert (_count == 1); -} - -void BasicEventTest::testDisabling() -{ - int tmp = 0; - - assert (_count == 0); - - Simple += Delegate(this, &BasicEventTest::onSimple); - Simple.disable(); - Simple.notify(this, tmp); - assert (_count == 0); - Simple.enable(); - Simple.notify(this, tmp); - assert (_count == 1); - - // unregister should also work with disabled event - Simple.disable(); - Simple -= Delegate(this, &BasicEventTest::onSimple); - Simple.enable(); - Simple.notify(this, tmp); - assert (_count == 1); -} - -void BasicEventTest::testExpire() -{ - int tmp = 0; - - assert (_count == 0); - - Simple += Expire(Delegate(this, &BasicEventTest::onSimple), 500); - Simple.notify(this, tmp); - assert (_count == 1); - Poco::Thread::sleep(700); - Simple.notify(this, tmp); - assert (_count == 1); -} - -void BasicEventTest::testExpireReRegister() -{ - int tmp = 0; - - assert (_count == 0); - - Simple += Expire(Delegate(this, &BasicEventTest::onSimple), 500); - Simple.notify(this, tmp); - assert (_count == 1); - Poco::Thread::sleep(200); - Simple.notify(this, tmp); - assert (_count == 2); - // renew registration - Simple += Expire(Delegate(this, &BasicEventTest::onSimple), 600); - Poco::Thread::sleep(400); - Simple.notify(this, tmp); - assert (_count == 3); - Poco::Thread::sleep(300); - Simple.notify(this, tmp); - assert (_count == 3); -} - -void BasicEventTest::testReturnParams() -{ - DummyDelegate o1; - Simple += Delegate(&o1, &DummyDelegate::onSimple); - - int tmp = 0; - Simple.notify(this, tmp); - assert (tmp == 1); -} - -void BasicEventTest::testOverwriteDelegate() -{ - DummyDelegate o1; - Simple += Delegate(&o1, &DummyDelegate::onSimple2); - // o1 can only have one entry, thus the next line will replace the entry - Simple += Delegate(&o1, &DummyDelegate::onSimple); - - int tmp = 0; // onsimple requires 0 as input - Simple.notify(this, tmp); - assert (tmp == 1); - // now overwrite with onsimple2 with requires as input tmp = 1 - Simple += Expire(Delegate(&o1, &DummyDelegate::onSimple2), 23000); - Simple.notify(this, tmp); - assert (tmp == 2); -} - -void BasicEventTest::testAsyncNotify() -{ - Poco::BasicEvent* pSimple= new Poco::BasicEvent(); - (*pSimple) += Delegate(this, &BasicEventTest::onAsync); - assert (_count == 0); - int tmp = 0; - Poco::ActiveResultretArg = pSimple->notifyAsync(this, tmp); - delete pSimple; // must work even when the event got deleted! - pSimple = NULL; - assert (_count == 0); - retArg.wait(); - assert (retArg.data() == tmp); - assert (_count == LARGEINC); -} - -void BasicEventTest::onSimple(const void* pSender, int& i) -{ - _count++; -} - -void BasicEventTest::onSimpleOther(const void* pSender, int& i) -{ - _count+=100; -} - -void BasicEventTest::onConstSimple(const void* pSender, const int& i) -{ - _count++; -} - -void BasicEventTest::onComplex(const void* pSender, Poco::EventArgs* & i) -{ - _count++; -} - -void BasicEventTest::onComplex2(const void* pSender, Poco::EventArgs & i) -{ - _count++; -} - -void BasicEventTest::onConstComplex(const void* pSender, const Poco::EventArgs*& i) -{ - _count++; -} - -void BasicEventTest::onConst2Complex(const void* pSender, const Poco::EventArgs * const & i) -{ - _count++; -} - -void BasicEventTest::onAsync(const void* pSender, int& i) -{ - Poco::Thread::sleep(700); - _count += LARGEINC ; -} - -int BasicEventTest::getCount() const -{ - return _count; -} - -void BasicEventTest::setUp() -{ - _count = 0; - // must clear events, otherwise repeating test executions will fail - // because tests are only created once, only setup is called before - // each test run - Simple.clear(); - ConstSimple.clear(); - Complex.clear(); - Complex2.clear(); - ConstComplex.clear(); - Const2Complex.clear(); -} - - -void BasicEventTest::tearDown() -{ -} - - -CppUnit::Test* BasicEventTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("BasicEventTest"); - - CppUnit_addTest(pSuite, BasicEventTest, testNoDelegate); - CppUnit_addTest(pSuite, BasicEventTest, testSingleDelegate); - CppUnit_addTest(pSuite, BasicEventTest, testReturnParams); - CppUnit_addTest(pSuite, BasicEventTest, testDuplicateRegister); - CppUnit_addTest(pSuite, BasicEventTest, testDuplicateUnregister); - CppUnit_addTest(pSuite, BasicEventTest, testDisabling); - CppUnit_addTest(pSuite, BasicEventTest, testExpire); - CppUnit_addTest(pSuite, BasicEventTest, testExpireReRegister); - CppUnit_addTest(pSuite, BasicEventTest, testOverwriteDelegate); - CppUnit_addTest(pSuite, BasicEventTest, testAsyncNotify); - return pSuite; -} +// +// BasicEventTest.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/BasicEventTest.cpp#2 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "BasicEventTest.h" +#include "DummyDelegate.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/Delegate.h" +#include "Poco/Expire.h" +#include "Poco/Thread.h" +#include "Poco/Exception.h" + + +using namespace Poco; + + +#define LARGEINC 100 + + +BasicEventTest::BasicEventTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +BasicEventTest::~BasicEventTest() +{ +} + +void BasicEventTest::testNoDelegate() +{ + int tmp = 0; + EventArgs args; + + assert (_count == 0); + Simple.notify(this, tmp); + assert (_count == 0); + + Simple += Delegate(this, &BasicEventTest::onSimple); + Simple -= Delegate(this, &BasicEventTest::onSimple); + Simple.notify(this, tmp); + assert (_count == 0); + + ConstSimple += Delegate(this, &BasicEventTest::onConstSimple); + ConstSimple -= Delegate(this, &BasicEventTest::onConstSimple); + ConstSimple.notify(this, tmp); + assert (_count == 0); + + //Note: passing &args will not work due to & + EventArgs* pArgs = &args; + Complex += Delegate(this, &BasicEventTest::onComplex); + Complex -= Delegate(this, &BasicEventTest::onComplex); + Complex.notify(this, pArgs); + assert (_count == 0); + + Complex2 += Delegate(this, &BasicEventTest::onComplex2); + Complex2 -= Delegate(this, &BasicEventTest::onComplex2); + Complex2.notify(this, args); + assert (_count == 0); + + const EventArgs* pCArgs = &args; + ConstComplex += Delegate(this, &BasicEventTest::onConstComplex); + ConstComplex -= Delegate(this, &BasicEventTest::onConstComplex); + ConstComplex.notify(this, pCArgs); + assert (_count == 0); + + Const2Complex += Delegate(this, &BasicEventTest::onConst2Complex); + Const2Complex -= Delegate(this, &BasicEventTest::onConst2Complex); + Const2Complex.notify(this, pArgs); + assert (_count == 0); +} + +void BasicEventTest::testSingleDelegate() +{ + int tmp = 0; + EventArgs args; + + assert (_count == 0); + + Simple += Delegate(this, &BasicEventTest::onSimple); + Simple.notify(this, tmp); + assert (_count == 1); + + ConstSimple += Delegate(this, &BasicEventTest::onConstSimple); + ConstSimple.notify(this, tmp); + assert (_count == 2); + + EventArgs* pArgs = &args; + Complex += Delegate(this, &BasicEventTest::onComplex); + Complex.notify(this, pArgs); + assert (_count == 3); + + Complex2 += Delegate(this, &BasicEventTest::onComplex2); + Complex2.notify(this, args); + assert (_count == 4); + + const EventArgs* pCArgs = &args; + ConstComplex += Delegate(this, &BasicEventTest::onConstComplex); + ConstComplex.notify(this, pCArgs); + assert (_count == 5); + + Const2Complex += Delegate(this, &BasicEventTest::onConst2Complex); + Const2Complex.notify(this, pArgs); + assert (_count == 6); + // check if 2nd notify also works + Const2Complex.notify(this, pArgs); + assert (_count == 7); + +} + +void BasicEventTest::testDuplicateRegister() +{ + int tmp = 0; + + assert (_count == 0); + + Simple += Delegate(this, &BasicEventTest::onSimple); + Simple += Delegate(this, &BasicEventTest::onSimple); + Simple.notify(this, tmp); + assert (_count == 1); + Simple -= Delegate(this, &BasicEventTest::onSimple); + Simple.notify(this, tmp); + assert (_count == 1); +} + +void BasicEventTest::testDuplicateUnregister() +{ + // duplicate unregister shouldn't give an error, + int tmp = 0; + + assert (_count == 0); + + Simple -= Delegate(this, &BasicEventTest::onSimple); // should work + Simple.notify(this, tmp); + assert (_count == 0); + + Simple += Delegate(this, &BasicEventTest::onSimple); + Simple.notify(this, tmp); + assert (_count == 1); + + Simple -= Delegate(this, &BasicEventTest::onSimple); + Simple.notify(this, tmp); + assert (_count == 1); + + Simple -= Delegate(this, &BasicEventTest::onSimple); + Simple.notify(this, tmp); + assert (_count == 1); +} + +void BasicEventTest::testDisabling() +{ + int tmp = 0; + + assert (_count == 0); + + Simple += Delegate(this, &BasicEventTest::onSimple); + Simple.disable(); + Simple.notify(this, tmp); + assert (_count == 0); + Simple.enable(); + Simple.notify(this, tmp); + assert (_count == 1); + + // unregister should also work with disabled event + Simple.disable(); + Simple -= Delegate(this, &BasicEventTest::onSimple); + Simple.enable(); + Simple.notify(this, tmp); + assert (_count == 1); +} + +void BasicEventTest::testExpire() +{ + int tmp = 0; + + assert (_count == 0); + + Simple += Expire(Delegate(this, &BasicEventTest::onSimple), 500); + Simple.notify(this, tmp); + assert (_count == 1); + Poco::Thread::sleep(700); + Simple.notify(this, tmp); + assert (_count == 1); +} + +void BasicEventTest::testExpireReRegister() +{ + int tmp = 0; + + assert (_count == 0); + + Simple += Expire(Delegate(this, &BasicEventTest::onSimple), 500); + Simple.notify(this, tmp); + assert (_count == 1); + Poco::Thread::sleep(200); + Simple.notify(this, tmp); + assert (_count == 2); + // renew registration + Simple += Expire(Delegate(this, &BasicEventTest::onSimple), 600); + Poco::Thread::sleep(400); + Simple.notify(this, tmp); + assert (_count == 3); + Poco::Thread::sleep(300); + Simple.notify(this, tmp); + assert (_count == 3); +} + +void BasicEventTest::testReturnParams() +{ + DummyDelegate o1; + Simple += Delegate(&o1, &DummyDelegate::onSimple); + + int tmp = 0; + Simple.notify(this, tmp); + assert (tmp == 1); +} + +void BasicEventTest::testOverwriteDelegate() +{ + DummyDelegate o1; + Simple += Delegate(&o1, &DummyDelegate::onSimple2); + // o1 can only have one entry, thus the next line will replace the entry + Simple += Delegate(&o1, &DummyDelegate::onSimple); + + int tmp = 0; // onsimple requires 0 as input + Simple.notify(this, tmp); + assert (tmp == 1); + // now overwrite with onsimple2 with requires as input tmp = 1 + Simple += Expire(Delegate(&o1, &DummyDelegate::onSimple2), 23000); + Simple.notify(this, tmp); + assert (tmp == 2); +} + +void BasicEventTest::testAsyncNotify() +{ + Poco::BasicEvent* pSimple= new Poco::BasicEvent(); + (*pSimple) += Delegate(this, &BasicEventTest::onAsync); + assert (_count == 0); + int tmp = 0; + Poco::ActiveResultretArg = pSimple->notifyAsync(this, tmp); + delete pSimple; // must work even when the event got deleted! + pSimple = NULL; + assert (_count == 0); + retArg.wait(); + assert (retArg.data() == tmp); + assert (_count == LARGEINC); +} + +void BasicEventTest::onSimple(const void* pSender, int& i) +{ + _count++; +} + +void BasicEventTest::onSimpleOther(const void* pSender, int& i) +{ + _count+=100; +} + +void BasicEventTest::onConstSimple(const void* pSender, const int& i) +{ + _count++; +} + +void BasicEventTest::onComplex(const void* pSender, Poco::EventArgs* & i) +{ + _count++; +} + +void BasicEventTest::onComplex2(const void* pSender, Poco::EventArgs & i) +{ + _count++; +} + +void BasicEventTest::onConstComplex(const void* pSender, const Poco::EventArgs*& i) +{ + _count++; +} + +void BasicEventTest::onConst2Complex(const void* pSender, const Poco::EventArgs * const & i) +{ + _count++; +} + +void BasicEventTest::onAsync(const void* pSender, int& i) +{ + Poco::Thread::sleep(700); + _count += LARGEINC ; +} + +int BasicEventTest::getCount() const +{ + return _count; +} + +void BasicEventTest::setUp() +{ + _count = 0; + // must clear events, otherwise repeating test executions will fail + // because tests are only created once, only setup is called before + // each test run + Simple.clear(); + ConstSimple.clear(); + Complex.clear(); + Complex2.clear(); + ConstComplex.clear(); + Const2Complex.clear(); +} + + +void BasicEventTest::tearDown() +{ +} + + +CppUnit::Test* BasicEventTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("BasicEventTest"); + + CppUnit_addTest(pSuite, BasicEventTest, testNoDelegate); + CppUnit_addTest(pSuite, BasicEventTest, testSingleDelegate); + CppUnit_addTest(pSuite, BasicEventTest, testReturnParams); + CppUnit_addTest(pSuite, BasicEventTest, testDuplicateRegister); + CppUnit_addTest(pSuite, BasicEventTest, testDuplicateUnregister); + CppUnit_addTest(pSuite, BasicEventTest, testDisabling); + CppUnit_addTest(pSuite, BasicEventTest, testExpire); + CppUnit_addTest(pSuite, BasicEventTest, testExpireReRegister); + CppUnit_addTest(pSuite, BasicEventTest, testOverwriteDelegate); + CppUnit_addTest(pSuite, BasicEventTest, testAsyncNotify); + return pSuite; +} diff --git a/Foundation/testsuite/src/BasicEventTest.h b/Foundation/testsuite/src/BasicEventTest.h index ca85b14d1..2f0191425 100644 --- a/Foundation/testsuite/src/BasicEventTest.h +++ b/Foundation/testsuite/src/BasicEventTest.h @@ -1,89 +1,89 @@ -// -// BasicEventTest.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/BasicEventTest.h#2 $ -// -// Tests for BasicEvent -// -// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 BasicEventTest_INCLUDED -#define BasicEventTest_INCLUDED - - -#include "Poco/Foundation.h" -#include "CppUnit/TestCase.h" -#include "Poco/BasicEvent.h" -#include "Poco/EventArgs.h" - - -class BasicEventTest: public CppUnit::TestCase -{ - Poco::BasicEvent Simple; - Poco::BasicEvent ConstSimple; - Poco::BasicEvent Complex; - Poco::BasicEvent Complex2; - Poco::BasicEvent ConstComplex; - Poco::BasicEvent Const2Complex; -public: - BasicEventTest(const std::string& name); - ~BasicEventTest(); - - void testNoDelegate(); - void testSingleDelegate(); - void testDuplicateRegister(); - void testDuplicateUnregister(); - void testDisabling(); - void testExpire(); - void testExpireReRegister(); - void testReturnParams(); - void testOverwriteDelegate(); - void testAsyncNotify(); - - void setUp(); - void tearDown(); - static CppUnit::Test* suite(); - -protected: - - void onSimple(const void* pSender, int& i); - void onSimpleOther(const void* pSender, int& i); - void onConstSimple(const void* pSender, const int& i); - void onComplex(const void* pSender, Poco::EventArgs* & i); - void onComplex2(const void* pSender, Poco::EventArgs & i); - void onConstComplex(const void* pSender, const Poco::EventArgs*& i); - void onConst2Complex(const void* pSender, const Poco::EventArgs * const & i); - void onAsync(const void* pSender, int& i); - - int getCount() const; -private: - int _count; -}; - - -#endif // BasicEventTest_INCLUDED +// +// BasicEventTest.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/BasicEventTest.h#2 $ +// +// Tests for BasicEvent +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 BasicEventTest_INCLUDED +#define BasicEventTest_INCLUDED + + +#include "Poco/Foundation.h" +#include "CppUnit/TestCase.h" +#include "Poco/BasicEvent.h" +#include "Poco/EventArgs.h" + + +class BasicEventTest: public CppUnit::TestCase +{ + Poco::BasicEvent Simple; + Poco::BasicEvent ConstSimple; + Poco::BasicEvent Complex; + Poco::BasicEvent Complex2; + Poco::BasicEvent ConstComplex; + Poco::BasicEvent Const2Complex; +public: + BasicEventTest(const std::string& name); + ~BasicEventTest(); + + void testNoDelegate(); + void testSingleDelegate(); + void testDuplicateRegister(); + void testDuplicateUnregister(); + void testDisabling(); + void testExpire(); + void testExpireReRegister(); + void testReturnParams(); + void testOverwriteDelegate(); + void testAsyncNotify(); + + void setUp(); + void tearDown(); + static CppUnit::Test* suite(); + +protected: + + void onSimple(const void* pSender, int& i); + void onSimpleOther(const void* pSender, int& i); + void onConstSimple(const void* pSender, const int& i); + void onComplex(const void* pSender, Poco::EventArgs* & i); + void onComplex2(const void* pSender, Poco::EventArgs & i); + void onConstComplex(const void* pSender, const Poco::EventArgs*& i); + void onConst2Complex(const void* pSender, const Poco::EventArgs * const & i); + void onAsync(const void* pSender, int& i); + + int getCount() const; +private: + int _count; +}; + + +#endif // BasicEventTest_INCLUDED diff --git a/Foundation/testsuite/src/BinaryReaderWriterTest.cpp b/Foundation/testsuite/src/BinaryReaderWriterTest.cpp index 8233faedb..1e44486e8 100644 --- a/Foundation/testsuite/src/BinaryReaderWriterTest.cpp +++ b/Foundation/testsuite/src/BinaryReaderWriterTest.cpp @@ -1,254 +1,254 @@ -// -// BinaryReaderWriterTest.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/BinaryReaderWriterTest.cpp#1 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "BinaryReaderWriterTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/BinaryWriter.h" -#include "Poco/BinaryReader.h" -#include - - -using Poco::BinaryWriter; -using Poco::BinaryReader; -using Poco::Int32; -using Poco::UInt32; -using Poco::Int64; -using Poco::UInt64; - - -BinaryReaderWriterTest::BinaryReaderWriterTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -BinaryReaderWriterTest::~BinaryReaderWriterTest() -{ -} - - -void BinaryReaderWriterTest::testNative() -{ - std::stringstream sstream; - BinaryWriter writer(sstream); - BinaryReader reader(sstream); - write(writer); - read(reader); -} - - -void BinaryReaderWriterTest::testBigEndian() -{ - std::stringstream sstream; - BinaryWriter writer(sstream, BinaryWriter::BIG_ENDIAN_BYTE_ORDER); - BinaryReader reader(sstream, BinaryReader::UNSPECIFIED_BYTE_ORDER); - assert (writer.byteOrder() == BinaryWriter::BIG_ENDIAN_BYTE_ORDER); - writer.writeBOM(); - write(writer); - reader.readBOM(); - assert (reader.byteOrder() == BinaryReader::BIG_ENDIAN_BYTE_ORDER); - read(reader); -} - - -void BinaryReaderWriterTest::testLittleEndian() -{ - std::stringstream sstream; - BinaryWriter writer(sstream, BinaryWriter::LITTLE_ENDIAN_BYTE_ORDER); - BinaryReader reader(sstream, BinaryReader::UNSPECIFIED_BYTE_ORDER); - assert (writer.byteOrder() == BinaryWriter::LITTLE_ENDIAN_BYTE_ORDER); - writer.writeBOM(); - write(writer); - reader.readBOM(); - assert (reader.byteOrder() == BinaryReader::LITTLE_ENDIAN_BYTE_ORDER); - read(reader); -} - - -void BinaryReaderWriterTest::write(BinaryWriter& writer) -{ - writer << true; - writer << false; - writer << 'a'; - writer << (short) -100; - writer << (unsigned short) 50000; - writer << -123456; - writer << (unsigned) 123456; - writer << (long) -1234567890; - writer << (unsigned long) 1234567890; - -#if defined(POCO_HAVE_INT64) - writer << (Int64) -1234567890; - writer << (UInt64) 1234567890; -#endif - - writer << (float) 1.5; - writer << (double) -1.5; - - writer << "foo"; - writer << ""; - - writer << std::string("bar"); - writer << std::string(); - - writer.write7BitEncoded((UInt32) 100); - writer.write7BitEncoded((UInt32) 1000); - writer.write7BitEncoded((UInt32) 10000); - writer.write7BitEncoded((UInt32) 100000); - writer.write7BitEncoded((UInt32) 1000000); - -#if defined(POCO_HAVE_INT64) - writer.write7BitEncoded((UInt64) 100); - writer.write7BitEncoded((UInt64) 1000); - writer.write7BitEncoded((UInt64) 10000); - writer.write7BitEncoded((UInt64) 100000); - writer.write7BitEncoded((UInt64) 1000000); -#endif - - writer.writeRaw("RAW"); -} - - -void BinaryReaderWriterTest::read(BinaryReader& reader) -{ - bool b; - reader >> b; - assert (b); - reader >> b; - assert (!b); - - char c; - reader >> c; - assert (c == 'a'); - - short shortv; - reader >> shortv; - assert (shortv == -100); - - unsigned short ushortv; - reader >> ushortv; - assert (ushortv == 50000); - - int intv; - reader >> intv; - assert (intv == -123456); - - unsigned uintv; - reader >> uintv; - assert (uintv == 123456); - - long longv; - reader >> longv; - assert (longv == -1234567890); - - unsigned long ulongv; - reader >> ulongv; - assert (ulongv == 1234567890); - -#if defined(POCO_HAVE_INT64) - Int64 int64v; - reader >> int64v; - assert (int64v == -1234567890); - - UInt64 uint64v; - reader >> uint64v; - assert (uint64v == 1234567890); -#endif - - float floatv; - reader >> floatv; - assert (floatv == 1.5); - - double doublev; - reader >> doublev; - assert (doublev == -1.5); - - std::string str; - reader >> str; - assert (str == "foo"); - reader >> str; - assert (str == ""); - reader >> str; - assert (str == "bar"); - reader >> str; - assert (str == ""); - - UInt32 uint32v; - reader.read7BitEncoded(uint32v); - assert (uint32v == 100); - reader.read7BitEncoded(uint32v); - assert (uint32v == 1000); - reader.read7BitEncoded(uint32v); - assert (uint32v == 10000); - reader.read7BitEncoded(uint32v); - assert (uint32v == 100000); - reader.read7BitEncoded(uint32v); - assert (uint32v == 1000000); - -#if defined(POCO_HAVE_INT64) - reader.read7BitEncoded(uint64v); - assert (uint64v == 100); - reader.read7BitEncoded(uint64v); - assert (uint64v == 1000); - reader.read7BitEncoded(uint64v); - assert (uint64v == 10000); - reader.read7BitEncoded(uint64v); - assert (uint64v == 100000); - reader.read7BitEncoded(uint64v); - assert (uint64v == 1000000); -#endif - - reader.readRaw(3, str); - assert (str == "RAW"); -} - - -void BinaryReaderWriterTest::setUp() -{ -} - - -void BinaryReaderWriterTest::tearDown() -{ -} - - -CppUnit::Test* BinaryReaderWriterTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("BinaryReaderWriterTest"); - - CppUnit_addTest(pSuite, BinaryReaderWriterTest, testNative); - CppUnit_addTest(pSuite, BinaryReaderWriterTest, testBigEndian); - CppUnit_addTest(pSuite, BinaryReaderWriterTest, testLittleEndian); - - return pSuite; -} +// +// BinaryReaderWriterTest.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/BinaryReaderWriterTest.cpp#1 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "BinaryReaderWriterTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/BinaryWriter.h" +#include "Poco/BinaryReader.h" +#include + + +using Poco::BinaryWriter; +using Poco::BinaryReader; +using Poco::Int32; +using Poco::UInt32; +using Poco::Int64; +using Poco::UInt64; + + +BinaryReaderWriterTest::BinaryReaderWriterTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +BinaryReaderWriterTest::~BinaryReaderWriterTest() +{ +} + + +void BinaryReaderWriterTest::testNative() +{ + std::stringstream sstream; + BinaryWriter writer(sstream); + BinaryReader reader(sstream); + write(writer); + read(reader); +} + + +void BinaryReaderWriterTest::testBigEndian() +{ + std::stringstream sstream; + BinaryWriter writer(sstream, BinaryWriter::BIG_ENDIAN_BYTE_ORDER); + BinaryReader reader(sstream, BinaryReader::UNSPECIFIED_BYTE_ORDER); + assert (writer.byteOrder() == BinaryWriter::BIG_ENDIAN_BYTE_ORDER); + writer.writeBOM(); + write(writer); + reader.readBOM(); + assert (reader.byteOrder() == BinaryReader::BIG_ENDIAN_BYTE_ORDER); + read(reader); +} + + +void BinaryReaderWriterTest::testLittleEndian() +{ + std::stringstream sstream; + BinaryWriter writer(sstream, BinaryWriter::LITTLE_ENDIAN_BYTE_ORDER); + BinaryReader reader(sstream, BinaryReader::UNSPECIFIED_BYTE_ORDER); + assert (writer.byteOrder() == BinaryWriter::LITTLE_ENDIAN_BYTE_ORDER); + writer.writeBOM(); + write(writer); + reader.readBOM(); + assert (reader.byteOrder() == BinaryReader::LITTLE_ENDIAN_BYTE_ORDER); + read(reader); +} + + +void BinaryReaderWriterTest::write(BinaryWriter& writer) +{ + writer << true; + writer << false; + writer << 'a'; + writer << (short) -100; + writer << (unsigned short) 50000; + writer << -123456; + writer << (unsigned) 123456; + writer << (long) -1234567890; + writer << (unsigned long) 1234567890; + +#if defined(POCO_HAVE_INT64) + writer << (Int64) -1234567890; + writer << (UInt64) 1234567890; +#endif + + writer << (float) 1.5; + writer << (double) -1.5; + + writer << "foo"; + writer << ""; + + writer << std::string("bar"); + writer << std::string(); + + writer.write7BitEncoded((UInt32) 100); + writer.write7BitEncoded((UInt32) 1000); + writer.write7BitEncoded((UInt32) 10000); + writer.write7BitEncoded((UInt32) 100000); + writer.write7BitEncoded((UInt32) 1000000); + +#if defined(POCO_HAVE_INT64) + writer.write7BitEncoded((UInt64) 100); + writer.write7BitEncoded((UInt64) 1000); + writer.write7BitEncoded((UInt64) 10000); + writer.write7BitEncoded((UInt64) 100000); + writer.write7BitEncoded((UInt64) 1000000); +#endif + + writer.writeRaw("RAW"); +} + + +void BinaryReaderWriterTest::read(BinaryReader& reader) +{ + bool b; + reader >> b; + assert (b); + reader >> b; + assert (!b); + + char c; + reader >> c; + assert (c == 'a'); + + short shortv; + reader >> shortv; + assert (shortv == -100); + + unsigned short ushortv; + reader >> ushortv; + assert (ushortv == 50000); + + int intv; + reader >> intv; + assert (intv == -123456); + + unsigned uintv; + reader >> uintv; + assert (uintv == 123456); + + long longv; + reader >> longv; + assert (longv == -1234567890); + + unsigned long ulongv; + reader >> ulongv; + assert (ulongv == 1234567890); + +#if defined(POCO_HAVE_INT64) + Int64 int64v; + reader >> int64v; + assert (int64v == -1234567890); + + UInt64 uint64v; + reader >> uint64v; + assert (uint64v == 1234567890); +#endif + + float floatv; + reader >> floatv; + assert (floatv == 1.5); + + double doublev; + reader >> doublev; + assert (doublev == -1.5); + + std::string str; + reader >> str; + assert (str == "foo"); + reader >> str; + assert (str == ""); + reader >> str; + assert (str == "bar"); + reader >> str; + assert (str == ""); + + UInt32 uint32v; + reader.read7BitEncoded(uint32v); + assert (uint32v == 100); + reader.read7BitEncoded(uint32v); + assert (uint32v == 1000); + reader.read7BitEncoded(uint32v); + assert (uint32v == 10000); + reader.read7BitEncoded(uint32v); + assert (uint32v == 100000); + reader.read7BitEncoded(uint32v); + assert (uint32v == 1000000); + +#if defined(POCO_HAVE_INT64) + reader.read7BitEncoded(uint64v); + assert (uint64v == 100); + reader.read7BitEncoded(uint64v); + assert (uint64v == 1000); + reader.read7BitEncoded(uint64v); + assert (uint64v == 10000); + reader.read7BitEncoded(uint64v); + assert (uint64v == 100000); + reader.read7BitEncoded(uint64v); + assert (uint64v == 1000000); +#endif + + reader.readRaw(3, str); + assert (str == "RAW"); +} + + +void BinaryReaderWriterTest::setUp() +{ +} + + +void BinaryReaderWriterTest::tearDown() +{ +} + + +CppUnit::Test* BinaryReaderWriterTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("BinaryReaderWriterTest"); + + CppUnit_addTest(pSuite, BinaryReaderWriterTest, testNative); + CppUnit_addTest(pSuite, BinaryReaderWriterTest, testBigEndian); + CppUnit_addTest(pSuite, BinaryReaderWriterTest, testLittleEndian); + + return pSuite; +} diff --git a/Foundation/testsuite/src/BinaryReaderWriterTest.h b/Foundation/testsuite/src/BinaryReaderWriterTest.h index d738da99d..9ceb388f7 100644 --- a/Foundation/testsuite/src/BinaryReaderWriterTest.h +++ b/Foundation/testsuite/src/BinaryReaderWriterTest.h @@ -1,66 +1,66 @@ -// -// BinaryReaderWriterTest.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/BinaryReaderWriterTest.h#1 $ -// -// Definition of the BinaryReaderWriterTest class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 BinaryReaderWriterTest_INCLUDED -#define BinaryReaderWriterTest_INCLUDED - - -#include "Poco/Foundation.h" -#include "CppUnit/TestCase.h" -#include "Poco/BinaryReader.h" -#include "Poco/BinaryWriter.h" - - -class BinaryReaderWriterTest: public CppUnit::TestCase -{ -public: - BinaryReaderWriterTest(const std::string& name); - ~BinaryReaderWriterTest(); - - void testNative(); - void testBigEndian(); - void testLittleEndian(); - void write(Poco::BinaryWriter& writer); - void read(Poco::BinaryReader& reader); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // BinaryReaderWriterTest_INCLUDED +// +// BinaryReaderWriterTest.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/BinaryReaderWriterTest.h#1 $ +// +// Definition of the BinaryReaderWriterTest class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 BinaryReaderWriterTest_INCLUDED +#define BinaryReaderWriterTest_INCLUDED + + +#include "Poco/Foundation.h" +#include "CppUnit/TestCase.h" +#include "Poco/BinaryReader.h" +#include "Poco/BinaryWriter.h" + + +class BinaryReaderWriterTest: public CppUnit::TestCase +{ +public: + BinaryReaderWriterTest(const std::string& name); + ~BinaryReaderWriterTest(); + + void testNative(); + void testBigEndian(); + void testLittleEndian(); + void write(Poco::BinaryWriter& writer); + void read(Poco::BinaryReader& reader); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // BinaryReaderWriterTest_INCLUDED diff --git a/Foundation/testsuite/src/ByteOrderTest.cpp b/Foundation/testsuite/src/ByteOrderTest.cpp index a10d8474b..e255772a6 100644 --- a/Foundation/testsuite/src/ByteOrderTest.cpp +++ b/Foundation/testsuite/src/ByteOrderTest.cpp @@ -1,633 +1,633 @@ -// -// ByteOrderTest.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/ByteOrderTest.cpp#1 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "ByteOrderTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/ByteOrder.h" - - -using Poco::ByteOrder; -using Poco::Int16; -using Poco::UInt16; -using Poco::Int32; -using Poco::UInt32; -#if defined(POCO_HAVE_INT64) -using Poco::Int64; -using Poco::UInt64; -#endif - - -ByteOrderTest::ByteOrderTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -ByteOrderTest::~ByteOrderTest() -{ -} - - -void ByteOrderTest::testByteOrderFlip() -{ - { - Int16 norm = (Int16) 0xAABB; - Int16 flip = ByteOrder::flipBytes(norm); - assert (UInt16(flip) == 0xBBAA); - flip = ByteOrder::flipBytes(flip); - assert (flip == norm); - } - { - UInt16 norm = (UInt16) 0xAABB; - UInt16 flip = ByteOrder::flipBytes(norm); - assert (flip == 0xBBAA); - flip = ByteOrder::flipBytes(flip); - assert (flip == norm); - } - { - Int32 norm = 0xAABBCCDD; - Int32 flip = ByteOrder::flipBytes(norm); - assert (UInt32(flip) == 0xDDCCBBAA); - flip = ByteOrder::flipBytes(flip); - assert (flip == norm); - } - { - UInt32 norm = 0xAABBCCDD; - UInt32 flip = ByteOrder::flipBytes(norm); - assert (flip == 0xDDCCBBAA); - flip = ByteOrder::flipBytes(flip); - assert (flip == norm); - } - #if defined(POCO_HAVE_INT64) - { - Int64 norm = (Int64(0x8899AABB) << 32) + 0xCCDDEEFF; - Int64 flip = ByteOrder::flipBytes(norm); - assert (flip == (Int64(0xFFEEDDCC) << 32) + 0xBBAA9988); - flip = ByteOrder::flipBytes(flip); - assert (flip == norm); - } - { - UInt64 norm = (UInt64(0x8899AABB) << 32) + 0xCCDDEEFF; - UInt64 flip = ByteOrder::flipBytes(norm); - assert (flip == (UInt64(0xFFEEDDCC) << 32) + 0xBBAA9988); - flip = ByteOrder::flipBytes(flip); - assert (flip == norm); - } - #endif -} - - -void ByteOrderTest::testByteOrderBigEndian() -{ -#if defined(POCO_ARCH_BIG_ENDIAN) - // - // big-endian systems - // - { - Int16 norm = 4; - Int16 flip = ByteOrder::toBigEndian(norm); - assert (norm == flip); - } - { - UInt16 norm = 4; - UInt16 flip = ByteOrder::toBigEndian(norm); - assert (norm == flip); - } - { - Int32 norm = 4; - Int32 flip = ByteOrder::toBigEndian(norm); - assert (norm == flip); - } - { - UInt32 norm = 4; - UInt32 flip = ByteOrder::toBigEndian(norm); - assert (norm == flip); - } - #if defined(POCO_HAVE_INT64) - { - Int64 norm = 4; - Int64 flip = ByteOrder::toBigEndian(norm); - assert (norm == flip); - } - { - UInt64 norm = 4; - UInt64 flip = ByteOrder::toBigEndian(norm); - assert (norm == flip); - } - #endif - - { - Int16 norm = 4; - Int16 flip = ByteOrder::fromBigEndian(norm); - assert (norm == flip); - } - { - UInt16 norm = 4; - UInt16 flip = ByteOrder::fromBigEndian(norm); - assert (norm == flip); - } - { - Int32 norm = 4; - Int32 flip = ByteOrder::fromBigEndian(norm); - assert (norm == flip); - } - { - UInt32 norm = 4; - UInt32 flip = ByteOrder::fromBigEndian(norm); - assert (norm == flip); - } - #if defined(POCO_HAVE_INT64) - { - Int64 norm = 4; - Int64 flip = ByteOrder::fromBigEndian(norm); - assert (norm == flip); - } - { - UInt64 norm = 4; - UInt64 flip = ByteOrder::fromBigEndian(norm); - assert (norm == flip); - } - #endif -#else - // - // little-endian systems - // - { - Int16 norm = 4; - Int16 flip = ByteOrder::toBigEndian(norm); - assert (norm != flip); - flip = ByteOrder::flipBytes(flip); - assert (norm == flip); - } - { - UInt16 norm = 4; - UInt16 flip = ByteOrder::toBigEndian(norm); - assert (norm != flip); - flip = ByteOrder::flipBytes(flip); - assert (norm == flip); - } - { - Int32 norm = 4; - Int32 flip = ByteOrder::toBigEndian(norm); - assert (norm != flip); - flip = ByteOrder::flipBytes(flip); - assert (norm == flip); - } - { - UInt32 norm = 4; - UInt32 flip = ByteOrder::toBigEndian(norm); - assert (norm != flip); - flip = ByteOrder::flipBytes(flip); - assert (norm == flip); - } - #if defined(POCO_HAVE_INT64) - { - Int64 norm = 4; - Int64 flip = ByteOrder::toBigEndian(norm); - assert (norm != flip); - flip = ByteOrder::flipBytes(flip); - assert (norm == flip); - } - { - UInt64 norm = 4; - UInt64 flip = ByteOrder::toBigEndian(norm); - assert (norm != flip); - flip = ByteOrder::flipBytes(flip); - assert (norm == flip); - } - #endif - - { - Int16 norm = 4; - Int16 flip = ByteOrder::fromBigEndian(norm); - assert (norm != flip); - flip = ByteOrder::flipBytes(flip); - assert (norm == flip); - } - { - UInt16 norm = 4; - UInt16 flip = ByteOrder::fromBigEndian(norm); - assert (norm != flip); - flip = ByteOrder::flipBytes(flip); - assert (norm == flip); - } - { - Int32 norm = 4; - Int32 flip = ByteOrder::fromBigEndian(norm); - assert (norm != flip); - flip = ByteOrder::flipBytes(flip); - assert (norm == flip); - } - { - UInt32 norm = 4; - UInt32 flip = ByteOrder::fromBigEndian(norm); - assert (norm != flip); - flip = ByteOrder::flipBytes(flip); - assert (norm == flip); - } - #if defined(POCO_HAVE_INT64) - { - Int64 norm = 4; - Int64 flip = ByteOrder::fromBigEndian(norm); - assert (norm != flip); - flip = ByteOrder::flipBytes(flip); - assert (norm == flip); - } - { - UInt64 norm = 4; - UInt64 flip = ByteOrder::fromBigEndian(norm); - assert (norm != flip); - flip = ByteOrder::flipBytes(flip); - assert (norm == flip); - } - #endif -#endif -} - - -void ByteOrderTest::testByteOrderLittleEndian() -{ -#if defined(POCO_ARCH_LITTLE_ENDIAN) - // - // big-endian systems - // - { - Int16 norm = 4; - Int16 flip = ByteOrder::toLittleEndian(norm); - assert (norm == flip); - } - { - UInt16 norm = 4; - UInt16 flip = ByteOrder::toLittleEndian(norm); - assert (norm == flip); - } - { - Int32 norm = 4; - Int32 flip = ByteOrder::toLittleEndian(norm); - assert (norm == flip); - } - { - UInt32 norm = 4; - UInt32 flip = ByteOrder::toLittleEndian(norm); - assert (norm == flip); - } - #if defined(POCO_HAVE_INT64) - { - Int64 norm = 4; - Int64 flip = ByteOrder::toLittleEndian(norm); - assert (norm == flip); - } - { - UInt64 norm = 4; - UInt64 flip = ByteOrder::toLittleEndian(norm); - assert (norm == flip); - } - #endif - - { - Int16 norm = 4; - Int16 flip = ByteOrder::toLittleEndian(norm); - assert (norm == flip); - } - { - UInt16 norm = 4; - UInt16 flip = ByteOrder::toLittleEndian(norm); - assert (norm == flip); - } - { - Int32 norm = 4; - Int32 flip = ByteOrder::toLittleEndian(norm); - assert (norm == flip); - } - { - UInt32 norm = 4; - UInt32 flip = ByteOrder::toLittleEndian(norm); - assert (norm == flip); - } - #if defined(POCO_HAVE_INT64) - { - Int64 norm = 4; - Int64 flip = ByteOrder::toLittleEndian(norm); - assert (norm == flip); - } - { - UInt64 norm = 4; - UInt64 flip = ByteOrder::toLittleEndian(norm); - assert (norm == flip); - } - #endif -#else - // - // little-endian systems - // - { - Int16 norm = 4; - Int16 flip = ByteOrder::toLittleEndian(norm); - assert (norm != flip); - flip = ByteOrder::flipBytes(flip); - assert (norm == flip); - } - { - UInt16 norm = 4; - UInt16 flip = ByteOrder::toLittleEndian(norm); - assert (norm != flip); - flip = ByteOrder::flipBytes(flip); - assert (norm == flip); - } - { - Int32 norm = 4; - Int32 flip = ByteOrder::toLittleEndian(norm); - assert (norm != flip); - flip = ByteOrder::flipBytes(flip); - assert (norm == flip); - } - { - UInt32 norm = 4; - UInt32 flip = ByteOrder::toLittleEndian(norm); - assert (norm != flip); - flip = ByteOrder::flipBytes(flip); - assert (norm == flip); - } - #if defined(POCO_HAVE_INT64) - { - Int64 norm = 4; - Int64 flip = ByteOrder::toLittleEndian(norm); - assert (norm != flip); - flip = ByteOrder::flipBytes(flip); - assert (norm == flip); - } - { - UInt64 norm = 4; - UInt64 flip = ByteOrder::toLittleEndian(norm); - assert (norm != flip); - flip = ByteOrder::flipBytes(flip); - assert (norm == flip); - } - #endif - - { - Int16 norm = 4; - Int16 flip = ByteOrder::fromLittleEndian(norm); - assert (norm != flip); - flip = ByteOrder::flipBytes(flip); - assert (norm == flip); - } - { - UInt16 norm = 4; - UInt16 flip = ByteOrder::fromLittleEndian(norm); - assert (norm != flip); - flip = ByteOrder::flipBytes(flip); - assert (norm == flip); - } - { - Int32 norm = 4; - Int32 flip = ByteOrder::fromLittleEndian(norm); - assert (norm != flip); - flip = ByteOrder::flipBytes(flip); - assert (norm == flip); - } - { - UInt32 norm = 4; - UInt32 flip = ByteOrder::fromLittleEndian(norm); - assert (norm != flip); - flip = ByteOrder::flipBytes(flip); - assert (norm == flip); - } - #if defined(POCO_HAVE_INT64) - { - Int64 norm = 4; - Int64 flip = ByteOrder::fromLittleEndian(norm); - assert (norm != flip); - flip = ByteOrder::flipBytes(flip); - assert (norm == flip); - } - { - UInt64 norm = 4; - UInt64 flip = ByteOrder::fromLittleEndian(norm); - assert (norm != flip); - flip = ByteOrder::flipBytes(flip); - assert (norm == flip); - } - #endif -#endif -} - - -void ByteOrderTest::testByteOrderNetwork() -{ -#if defined(POCO_ARCH_BIG_ENDIAN) - // - // big-endian systems - // - { - Int16 norm = 4; - Int16 flip = ByteOrder::toNetwork(norm); - assert (norm == flip); - } - { - UInt16 norm = 4; - UInt16 flip = ByteOrder::toNetwork(norm); - assert (norm == flip); - } - { - Int32 norm = 4; - Int32 flip = ByteOrder::toNetwork(norm); - assert (norm == flip); - } - { - UInt32 norm = 4; - UInt32 flip = ByteOrder::toNetwork(norm); - assert (norm == flip); - } - #if defined(POCO_HAVE_INT64) - { - Int64 norm = 4; - Int64 flip = ByteOrder::toNetwork(norm); - assert (norm == flip); - } - { - UInt64 norm = 4; - UInt64 flip = ByteOrder::toNetwork(norm); - assert (norm == flip); - } - #endif - - { - Int16 norm = 4; - Int16 flip = ByteOrder::fromNetwork(norm); - assert (norm == flip); - } - { - UInt16 norm = 4; - UInt16 flip = ByteOrder::fromNetwork(norm); - assert (norm == flip); - } - { - Int32 norm = 4; - Int32 flip = ByteOrder::fromNetwork(norm); - assert (norm == flip); - } - { - UInt32 norm = 4; - UInt32 flip = ByteOrder::fromNetwork(norm); - assert (norm == flip); - } - #if defined(POCO_HAVE_INT64) - { - Int64 norm = 4; - Int64 flip = ByteOrder::fromNetwork(norm); - assert (norm == flip); - } - { - UInt64 norm = 4; - UInt64 flip = ByteOrder::fromNetwork(norm); - assert (norm == flip); - } - #endif -#else - // - // little-endian systems - // - { - Int16 norm = 4; - Int16 flip = ByteOrder::toNetwork(norm); - assert (norm != flip); - flip = ByteOrder::flipBytes(flip); - assert (norm == flip); - } - { - UInt16 norm = 4; - UInt16 flip = ByteOrder::toNetwork(norm); - assert (norm != flip); - flip = ByteOrder::flipBytes(flip); - assert (norm == flip); - } - { - Int32 norm = 4; - Int32 flip = ByteOrder::toNetwork(norm); - assert (norm != flip); - flip = ByteOrder::flipBytes(flip); - assert (norm == flip); - } - { - UInt32 norm = 4; - UInt32 flip = ByteOrder::toNetwork(norm); - assert (norm != flip); - flip = ByteOrder::flipBytes(flip); - assert (norm == flip); - } - #if defined(POCO_HAVE_INT64) - { - Int64 norm = 4; - Int64 flip = ByteOrder::toNetwork(norm); - assert (norm != flip); - flip = ByteOrder::flipBytes(flip); - assert (norm == flip); - } - { - UInt64 norm = 4; - UInt64 flip = ByteOrder::toNetwork(norm); - assert (norm != flip); - flip = ByteOrder::flipBytes(flip); - assert (norm == flip); - } - #endif - - { - Int16 norm = 4; - Int16 flip = ByteOrder::fromNetwork(norm); - assert (norm != flip); - flip = ByteOrder::flipBytes(flip); - assert (norm == flip); - } - { - UInt16 norm = 4; - UInt16 flip = ByteOrder::fromNetwork(norm); - assert (norm != flip); - flip = ByteOrder::flipBytes(flip); - assert (norm == flip); - } - { - Int32 norm = 4; - Int32 flip = ByteOrder::fromNetwork(norm); - assert (norm != flip); - flip = ByteOrder::flipBytes(flip); - assert (norm == flip); - } - { - UInt32 norm = 4; - UInt32 flip = ByteOrder::fromNetwork(norm); - assert (norm != flip); - flip = ByteOrder::flipBytes(flip); - assert (norm == flip); - } - #if defined(POCO_HAVE_INT64) - { - Int64 norm = 4; - Int64 flip = ByteOrder::fromNetwork(norm); - assert (norm != flip); - flip = ByteOrder::flipBytes(flip); - assert (norm == flip); - } - { - UInt64 norm = 4; - UInt64 flip = ByteOrder::fromNetwork(norm); - assert (norm != flip); - flip = ByteOrder::flipBytes(flip); - assert (norm == flip); - } - #endif -#endif -} - - -void ByteOrderTest::setUp() -{ -} - - -void ByteOrderTest::tearDown() -{ -} - - -CppUnit::Test* ByteOrderTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("ByteOrderTest"); - - CppUnit_addTest(pSuite, ByteOrderTest, testByteOrderFlip); - CppUnit_addTest(pSuite, ByteOrderTest, testByteOrderBigEndian); - CppUnit_addTest(pSuite, ByteOrderTest, testByteOrderLittleEndian); - CppUnit_addTest(pSuite, ByteOrderTest, testByteOrderNetwork); - - return pSuite; -} +// +// ByteOrderTest.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/ByteOrderTest.cpp#1 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "ByteOrderTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/ByteOrder.h" + + +using Poco::ByteOrder; +using Poco::Int16; +using Poco::UInt16; +using Poco::Int32; +using Poco::UInt32; +#if defined(POCO_HAVE_INT64) +using Poco::Int64; +using Poco::UInt64; +#endif + + +ByteOrderTest::ByteOrderTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +ByteOrderTest::~ByteOrderTest() +{ +} + + +void ByteOrderTest::testByteOrderFlip() +{ + { + Int16 norm = (Int16) 0xAABB; + Int16 flip = ByteOrder::flipBytes(norm); + assert (UInt16(flip) == 0xBBAA); + flip = ByteOrder::flipBytes(flip); + assert (flip == norm); + } + { + UInt16 norm = (UInt16) 0xAABB; + UInt16 flip = ByteOrder::flipBytes(norm); + assert (flip == 0xBBAA); + flip = ByteOrder::flipBytes(flip); + assert (flip == norm); + } + { + Int32 norm = 0xAABBCCDD; + Int32 flip = ByteOrder::flipBytes(norm); + assert (UInt32(flip) == 0xDDCCBBAA); + flip = ByteOrder::flipBytes(flip); + assert (flip == norm); + } + { + UInt32 norm = 0xAABBCCDD; + UInt32 flip = ByteOrder::flipBytes(norm); + assert (flip == 0xDDCCBBAA); + flip = ByteOrder::flipBytes(flip); + assert (flip == norm); + } + #if defined(POCO_HAVE_INT64) + { + Int64 norm = (Int64(0x8899AABB) << 32) + 0xCCDDEEFF; + Int64 flip = ByteOrder::flipBytes(norm); + assert (flip == (Int64(0xFFEEDDCC) << 32) + 0xBBAA9988); + flip = ByteOrder::flipBytes(flip); + assert (flip == norm); + } + { + UInt64 norm = (UInt64(0x8899AABB) << 32) + 0xCCDDEEFF; + UInt64 flip = ByteOrder::flipBytes(norm); + assert (flip == (UInt64(0xFFEEDDCC) << 32) + 0xBBAA9988); + flip = ByteOrder::flipBytes(flip); + assert (flip == norm); + } + #endif +} + + +void ByteOrderTest::testByteOrderBigEndian() +{ +#if defined(POCO_ARCH_BIG_ENDIAN) + // + // big-endian systems + // + { + Int16 norm = 4; + Int16 flip = ByteOrder::toBigEndian(norm); + assert (norm == flip); + } + { + UInt16 norm = 4; + UInt16 flip = ByteOrder::toBigEndian(norm); + assert (norm == flip); + } + { + Int32 norm = 4; + Int32 flip = ByteOrder::toBigEndian(norm); + assert (norm == flip); + } + { + UInt32 norm = 4; + UInt32 flip = ByteOrder::toBigEndian(norm); + assert (norm == flip); + } + #if defined(POCO_HAVE_INT64) + { + Int64 norm = 4; + Int64 flip = ByteOrder::toBigEndian(norm); + assert (norm == flip); + } + { + UInt64 norm = 4; + UInt64 flip = ByteOrder::toBigEndian(norm); + assert (norm == flip); + } + #endif + + { + Int16 norm = 4; + Int16 flip = ByteOrder::fromBigEndian(norm); + assert (norm == flip); + } + { + UInt16 norm = 4; + UInt16 flip = ByteOrder::fromBigEndian(norm); + assert (norm == flip); + } + { + Int32 norm = 4; + Int32 flip = ByteOrder::fromBigEndian(norm); + assert (norm == flip); + } + { + UInt32 norm = 4; + UInt32 flip = ByteOrder::fromBigEndian(norm); + assert (norm == flip); + } + #if defined(POCO_HAVE_INT64) + { + Int64 norm = 4; + Int64 flip = ByteOrder::fromBigEndian(norm); + assert (norm == flip); + } + { + UInt64 norm = 4; + UInt64 flip = ByteOrder::fromBigEndian(norm); + assert (norm == flip); + } + #endif +#else + // + // little-endian systems + // + { + Int16 norm = 4; + Int16 flip = ByteOrder::toBigEndian(norm); + assert (norm != flip); + flip = ByteOrder::flipBytes(flip); + assert (norm == flip); + } + { + UInt16 norm = 4; + UInt16 flip = ByteOrder::toBigEndian(norm); + assert (norm != flip); + flip = ByteOrder::flipBytes(flip); + assert (norm == flip); + } + { + Int32 norm = 4; + Int32 flip = ByteOrder::toBigEndian(norm); + assert (norm != flip); + flip = ByteOrder::flipBytes(flip); + assert (norm == flip); + } + { + UInt32 norm = 4; + UInt32 flip = ByteOrder::toBigEndian(norm); + assert (norm != flip); + flip = ByteOrder::flipBytes(flip); + assert (norm == flip); + } + #if defined(POCO_HAVE_INT64) + { + Int64 norm = 4; + Int64 flip = ByteOrder::toBigEndian(norm); + assert (norm != flip); + flip = ByteOrder::flipBytes(flip); + assert (norm == flip); + } + { + UInt64 norm = 4; + UInt64 flip = ByteOrder::toBigEndian(norm); + assert (norm != flip); + flip = ByteOrder::flipBytes(flip); + assert (norm == flip); + } + #endif + + { + Int16 norm = 4; + Int16 flip = ByteOrder::fromBigEndian(norm); + assert (norm != flip); + flip = ByteOrder::flipBytes(flip); + assert (norm == flip); + } + { + UInt16 norm = 4; + UInt16 flip = ByteOrder::fromBigEndian(norm); + assert (norm != flip); + flip = ByteOrder::flipBytes(flip); + assert (norm == flip); + } + { + Int32 norm = 4; + Int32 flip = ByteOrder::fromBigEndian(norm); + assert (norm != flip); + flip = ByteOrder::flipBytes(flip); + assert (norm == flip); + } + { + UInt32 norm = 4; + UInt32 flip = ByteOrder::fromBigEndian(norm); + assert (norm != flip); + flip = ByteOrder::flipBytes(flip); + assert (norm == flip); + } + #if defined(POCO_HAVE_INT64) + { + Int64 norm = 4; + Int64 flip = ByteOrder::fromBigEndian(norm); + assert (norm != flip); + flip = ByteOrder::flipBytes(flip); + assert (norm == flip); + } + { + UInt64 norm = 4; + UInt64 flip = ByteOrder::fromBigEndian(norm); + assert (norm != flip); + flip = ByteOrder::flipBytes(flip); + assert (norm == flip); + } + #endif +#endif +} + + +void ByteOrderTest::testByteOrderLittleEndian() +{ +#if defined(POCO_ARCH_LITTLE_ENDIAN) + // + // big-endian systems + // + { + Int16 norm = 4; + Int16 flip = ByteOrder::toLittleEndian(norm); + assert (norm == flip); + } + { + UInt16 norm = 4; + UInt16 flip = ByteOrder::toLittleEndian(norm); + assert (norm == flip); + } + { + Int32 norm = 4; + Int32 flip = ByteOrder::toLittleEndian(norm); + assert (norm == flip); + } + { + UInt32 norm = 4; + UInt32 flip = ByteOrder::toLittleEndian(norm); + assert (norm == flip); + } + #if defined(POCO_HAVE_INT64) + { + Int64 norm = 4; + Int64 flip = ByteOrder::toLittleEndian(norm); + assert (norm == flip); + } + { + UInt64 norm = 4; + UInt64 flip = ByteOrder::toLittleEndian(norm); + assert (norm == flip); + } + #endif + + { + Int16 norm = 4; + Int16 flip = ByteOrder::toLittleEndian(norm); + assert (norm == flip); + } + { + UInt16 norm = 4; + UInt16 flip = ByteOrder::toLittleEndian(norm); + assert (norm == flip); + } + { + Int32 norm = 4; + Int32 flip = ByteOrder::toLittleEndian(norm); + assert (norm == flip); + } + { + UInt32 norm = 4; + UInt32 flip = ByteOrder::toLittleEndian(norm); + assert (norm == flip); + } + #if defined(POCO_HAVE_INT64) + { + Int64 norm = 4; + Int64 flip = ByteOrder::toLittleEndian(norm); + assert (norm == flip); + } + { + UInt64 norm = 4; + UInt64 flip = ByteOrder::toLittleEndian(norm); + assert (norm == flip); + } + #endif +#else + // + // little-endian systems + // + { + Int16 norm = 4; + Int16 flip = ByteOrder::toLittleEndian(norm); + assert (norm != flip); + flip = ByteOrder::flipBytes(flip); + assert (norm == flip); + } + { + UInt16 norm = 4; + UInt16 flip = ByteOrder::toLittleEndian(norm); + assert (norm != flip); + flip = ByteOrder::flipBytes(flip); + assert (norm == flip); + } + { + Int32 norm = 4; + Int32 flip = ByteOrder::toLittleEndian(norm); + assert (norm != flip); + flip = ByteOrder::flipBytes(flip); + assert (norm == flip); + } + { + UInt32 norm = 4; + UInt32 flip = ByteOrder::toLittleEndian(norm); + assert (norm != flip); + flip = ByteOrder::flipBytes(flip); + assert (norm == flip); + } + #if defined(POCO_HAVE_INT64) + { + Int64 norm = 4; + Int64 flip = ByteOrder::toLittleEndian(norm); + assert (norm != flip); + flip = ByteOrder::flipBytes(flip); + assert (norm == flip); + } + { + UInt64 norm = 4; + UInt64 flip = ByteOrder::toLittleEndian(norm); + assert (norm != flip); + flip = ByteOrder::flipBytes(flip); + assert (norm == flip); + } + #endif + + { + Int16 norm = 4; + Int16 flip = ByteOrder::fromLittleEndian(norm); + assert (norm != flip); + flip = ByteOrder::flipBytes(flip); + assert (norm == flip); + } + { + UInt16 norm = 4; + UInt16 flip = ByteOrder::fromLittleEndian(norm); + assert (norm != flip); + flip = ByteOrder::flipBytes(flip); + assert (norm == flip); + } + { + Int32 norm = 4; + Int32 flip = ByteOrder::fromLittleEndian(norm); + assert (norm != flip); + flip = ByteOrder::flipBytes(flip); + assert (norm == flip); + } + { + UInt32 norm = 4; + UInt32 flip = ByteOrder::fromLittleEndian(norm); + assert (norm != flip); + flip = ByteOrder::flipBytes(flip); + assert (norm == flip); + } + #if defined(POCO_HAVE_INT64) + { + Int64 norm = 4; + Int64 flip = ByteOrder::fromLittleEndian(norm); + assert (norm != flip); + flip = ByteOrder::flipBytes(flip); + assert (norm == flip); + } + { + UInt64 norm = 4; + UInt64 flip = ByteOrder::fromLittleEndian(norm); + assert (norm != flip); + flip = ByteOrder::flipBytes(flip); + assert (norm == flip); + } + #endif +#endif +} + + +void ByteOrderTest::testByteOrderNetwork() +{ +#if defined(POCO_ARCH_BIG_ENDIAN) + // + // big-endian systems + // + { + Int16 norm = 4; + Int16 flip = ByteOrder::toNetwork(norm); + assert (norm == flip); + } + { + UInt16 norm = 4; + UInt16 flip = ByteOrder::toNetwork(norm); + assert (norm == flip); + } + { + Int32 norm = 4; + Int32 flip = ByteOrder::toNetwork(norm); + assert (norm == flip); + } + { + UInt32 norm = 4; + UInt32 flip = ByteOrder::toNetwork(norm); + assert (norm == flip); + } + #if defined(POCO_HAVE_INT64) + { + Int64 norm = 4; + Int64 flip = ByteOrder::toNetwork(norm); + assert (norm == flip); + } + { + UInt64 norm = 4; + UInt64 flip = ByteOrder::toNetwork(norm); + assert (norm == flip); + } + #endif + + { + Int16 norm = 4; + Int16 flip = ByteOrder::fromNetwork(norm); + assert (norm == flip); + } + { + UInt16 norm = 4; + UInt16 flip = ByteOrder::fromNetwork(norm); + assert (norm == flip); + } + { + Int32 norm = 4; + Int32 flip = ByteOrder::fromNetwork(norm); + assert (norm == flip); + } + { + UInt32 norm = 4; + UInt32 flip = ByteOrder::fromNetwork(norm); + assert (norm == flip); + } + #if defined(POCO_HAVE_INT64) + { + Int64 norm = 4; + Int64 flip = ByteOrder::fromNetwork(norm); + assert (norm == flip); + } + { + UInt64 norm = 4; + UInt64 flip = ByteOrder::fromNetwork(norm); + assert (norm == flip); + } + #endif +#else + // + // little-endian systems + // + { + Int16 norm = 4; + Int16 flip = ByteOrder::toNetwork(norm); + assert (norm != flip); + flip = ByteOrder::flipBytes(flip); + assert (norm == flip); + } + { + UInt16 norm = 4; + UInt16 flip = ByteOrder::toNetwork(norm); + assert (norm != flip); + flip = ByteOrder::flipBytes(flip); + assert (norm == flip); + } + { + Int32 norm = 4; + Int32 flip = ByteOrder::toNetwork(norm); + assert (norm != flip); + flip = ByteOrder::flipBytes(flip); + assert (norm == flip); + } + { + UInt32 norm = 4; + UInt32 flip = ByteOrder::toNetwork(norm); + assert (norm != flip); + flip = ByteOrder::flipBytes(flip); + assert (norm == flip); + } + #if defined(POCO_HAVE_INT64) + { + Int64 norm = 4; + Int64 flip = ByteOrder::toNetwork(norm); + assert (norm != flip); + flip = ByteOrder::flipBytes(flip); + assert (norm == flip); + } + { + UInt64 norm = 4; + UInt64 flip = ByteOrder::toNetwork(norm); + assert (norm != flip); + flip = ByteOrder::flipBytes(flip); + assert (norm == flip); + } + #endif + + { + Int16 norm = 4; + Int16 flip = ByteOrder::fromNetwork(norm); + assert (norm != flip); + flip = ByteOrder::flipBytes(flip); + assert (norm == flip); + } + { + UInt16 norm = 4; + UInt16 flip = ByteOrder::fromNetwork(norm); + assert (norm != flip); + flip = ByteOrder::flipBytes(flip); + assert (norm == flip); + } + { + Int32 norm = 4; + Int32 flip = ByteOrder::fromNetwork(norm); + assert (norm != flip); + flip = ByteOrder::flipBytes(flip); + assert (norm == flip); + } + { + UInt32 norm = 4; + UInt32 flip = ByteOrder::fromNetwork(norm); + assert (norm != flip); + flip = ByteOrder::flipBytes(flip); + assert (norm == flip); + } + #if defined(POCO_HAVE_INT64) + { + Int64 norm = 4; + Int64 flip = ByteOrder::fromNetwork(norm); + assert (norm != flip); + flip = ByteOrder::flipBytes(flip); + assert (norm == flip); + } + { + UInt64 norm = 4; + UInt64 flip = ByteOrder::fromNetwork(norm); + assert (norm != flip); + flip = ByteOrder::flipBytes(flip); + assert (norm == flip); + } + #endif +#endif +} + + +void ByteOrderTest::setUp() +{ +} + + +void ByteOrderTest::tearDown() +{ +} + + +CppUnit::Test* ByteOrderTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("ByteOrderTest"); + + CppUnit_addTest(pSuite, ByteOrderTest, testByteOrderFlip); + CppUnit_addTest(pSuite, ByteOrderTest, testByteOrderBigEndian); + CppUnit_addTest(pSuite, ByteOrderTest, testByteOrderLittleEndian); + CppUnit_addTest(pSuite, ByteOrderTest, testByteOrderNetwork); + + return pSuite; +} diff --git a/Foundation/testsuite/src/ByteOrderTest.h b/Foundation/testsuite/src/ByteOrderTest.h index 5df138c61..1ddc08efe 100644 --- a/Foundation/testsuite/src/ByteOrderTest.h +++ b/Foundation/testsuite/src/ByteOrderTest.h @@ -1,63 +1,63 @@ -// -// ByteOrderTest.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/ByteOrderTest.h#1 $ -// -// Definition of the ByteOrderTest class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 ByteOrderTest_INCLUDED -#define ByteOrderTest_INCLUDED - - -#include "Poco/Foundation.h" -#include "CppUnit/TestCase.h" - - -class ByteOrderTest: public CppUnit::TestCase -{ -public: - ByteOrderTest(const std::string& name); - ~ByteOrderTest(); - - void testByteOrderFlip(); - void testByteOrderBigEndian(); - void testByteOrderLittleEndian(); - void testByteOrderNetwork(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // ByteOrderTest_INCLUDED +// +// ByteOrderTest.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/ByteOrderTest.h#1 $ +// +// Definition of the ByteOrderTest class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 ByteOrderTest_INCLUDED +#define ByteOrderTest_INCLUDED + + +#include "Poco/Foundation.h" +#include "CppUnit/TestCase.h" + + +class ByteOrderTest: public CppUnit::TestCase +{ +public: + ByteOrderTest(const std::string& name); + ~ByteOrderTest(); + + void testByteOrderFlip(); + void testByteOrderBigEndian(); + void testByteOrderLittleEndian(); + void testByteOrderNetwork(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // ByteOrderTest_INCLUDED diff --git a/Foundation/testsuite/src/CacheTestSuite.cpp b/Foundation/testsuite/src/CacheTestSuite.cpp index 65f9b824f..a77fe1a8f 100644 --- a/Foundation/testsuite/src/CacheTestSuite.cpp +++ b/Foundation/testsuite/src/CacheTestSuite.cpp @@ -1,47 +1,47 @@ -// -// CacheTestSuite.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/CacheTestSuite.cpp#1 $ -// -// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "CacheTestSuite.h" -#include "LRUCacheTest.h" -#include "ExpireCacheTest.h" -#include "ExpireLRUCacheTest.h" - -CppUnit::Test* CacheTestSuite::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("CacheTestSuite"); - - pSuite->addTest(LRUCacheTest::suite()); - pSuite->addTest(ExpireCacheTest::suite()); - pSuite->addTest(ExpireLRUCacheTest::suite()); - - return pSuite; -} +// +// CacheTestSuite.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/CacheTestSuite.cpp#1 $ +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "CacheTestSuite.h" +#include "LRUCacheTest.h" +#include "ExpireCacheTest.h" +#include "ExpireLRUCacheTest.h" + +CppUnit::Test* CacheTestSuite::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("CacheTestSuite"); + + pSuite->addTest(LRUCacheTest::suite()); + pSuite->addTest(ExpireCacheTest::suite()); + pSuite->addTest(ExpireLRUCacheTest::suite()); + + return pSuite; +} diff --git a/Foundation/testsuite/src/CacheTestSuite.h b/Foundation/testsuite/src/CacheTestSuite.h index 11f85f76c..835c4eca3 100644 --- a/Foundation/testsuite/src/CacheTestSuite.h +++ b/Foundation/testsuite/src/CacheTestSuite.h @@ -1,49 +1,49 @@ -// -// CacheTestSuite.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/CacheTestSuite.h#1 $ -// -// Definition of the CacheTestSuite class. -// -// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 CacheTestSuite_INCLUDED -#define CacheTestSuite_INCLUDED - - -#include "CppUnit/TestSuite.h" - - -class CacheTestSuite -{ -public: - static CppUnit::Test* suite(); -}; - - -#endif // CacheTestSuite_INCLUDED +// +// CacheTestSuite.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/CacheTestSuite.h#1 $ +// +// Definition of the CacheTestSuite class. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 CacheTestSuite_INCLUDED +#define CacheTestSuite_INCLUDED + + +#include "CppUnit/TestSuite.h" + + +class CacheTestSuite +{ +public: + static CppUnit::Test* suite(); +}; + + +#endif // CacheTestSuite_INCLUDED diff --git a/Foundation/testsuite/src/ChannelTest.cpp b/Foundation/testsuite/src/ChannelTest.cpp index cd5cd2dcf..72474cbc4 100644 --- a/Foundation/testsuite/src/ChannelTest.cpp +++ b/Foundation/testsuite/src/ChannelTest.cpp @@ -1,160 +1,160 @@ -// -// ChannelTest.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/ChannelTest.cpp#1 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "ChannelTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/SplitterChannel.h" -#include "Poco/AsyncChannel.h" -#include "Poco/AutoPtr.h" -#include "Poco/Message.h" -#include "Poco/Formatter.h" -#include "Poco/FormattingChannel.h" -#include "Poco/ConsoleChannel.h" -#include "Poco/StreamChannel.h" -#include "TestChannel.h" -#include - - -using Poco::SplitterChannel; -using Poco::AsyncChannel; -using Poco::FormattingChannel; -using Poco::ConsoleChannel; -using Poco::StreamChannel; -using Poco::Formatter; -using Poco::Message; -using Poco::AutoPtr; - - -class SimpleFormatter: public Formatter -{ -public: - void format(const Message& msg, std::string& text) - { - text = msg.getSource(); - text.append(": "); - text.append(msg.getText()); - } -}; - - -ChannelTest::ChannelTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -ChannelTest::~ChannelTest() -{ -} - - -void ChannelTest::testSplitter() -{ - AutoPtr pChannel = new TestChannel; - AutoPtr pSplitter = new SplitterChannel; - pSplitter->addChannel(pChannel.get()); - pSplitter->addChannel(pChannel.get()); - Message msg; - pSplitter->log(msg); - assert (pChannel->list().size() == 2); -} - - -void ChannelTest::testAsync() -{ - AutoPtr pChannel = new TestChannel; - AutoPtr pAsync = new AsyncChannel(pChannel.get()); - pAsync->open(); - Message msg; - pAsync->log(msg); - pAsync->log(msg); - pAsync->close(); - assert (pChannel->list().size() == 2); -} - - -void ChannelTest::testFormatting() -{ - AutoPtr pChannel = new TestChannel; - AutoPtr pFormatter = new SimpleFormatter; - AutoPtr pFormatterChannel = new FormattingChannel(pFormatter, pChannel.get()); - Message msg("Source", "Text", Message::PRIO_INFORMATION); - pFormatterChannel->log(msg); - assert (pChannel->list().size() == 1); - assert (pChannel->list().begin()->getText() == "Source: Text"); -} - - -void ChannelTest::testConsole() -{ - AutoPtr pChannel = new ConsoleChannel; - AutoPtr pFormatter = new SimpleFormatter; - AutoPtr pFormatterChannel = new FormattingChannel(pFormatter, pChannel.get()); - Message msg("Source", "Text", Message::PRIO_INFORMATION); - pFormatterChannel->log(msg); -} - - -void ChannelTest::testStream() -{ - std::ostringstream str; - AutoPtr pChannel = new StreamChannel(str); - AutoPtr pFormatter = new SimpleFormatter; - AutoPtr pFormatterChannel = new FormattingChannel(pFormatter, pChannel.get()); - Message msg("Source", "Text", Message::PRIO_INFORMATION); - pFormatterChannel->log(msg); - assert (str.str().find("Source: Text") == 0); -} - - -void ChannelTest::setUp() -{ -} - - -void ChannelTest::tearDown() -{ -} - - -CppUnit::Test* ChannelTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("ChannelTest"); - - CppUnit_addTest(pSuite, ChannelTest, testSplitter); - CppUnit_addTest(pSuite, ChannelTest, testAsync); - CppUnit_addTest(pSuite, ChannelTest, testFormatting); - CppUnit_addTest(pSuite, ChannelTest, testConsole); - CppUnit_addTest(pSuite, ChannelTest, testStream); - - return pSuite; -} +// +// ChannelTest.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/ChannelTest.cpp#1 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "ChannelTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/SplitterChannel.h" +#include "Poco/AsyncChannel.h" +#include "Poco/AutoPtr.h" +#include "Poco/Message.h" +#include "Poco/Formatter.h" +#include "Poco/FormattingChannel.h" +#include "Poco/ConsoleChannel.h" +#include "Poco/StreamChannel.h" +#include "TestChannel.h" +#include + + +using Poco::SplitterChannel; +using Poco::AsyncChannel; +using Poco::FormattingChannel; +using Poco::ConsoleChannel; +using Poco::StreamChannel; +using Poco::Formatter; +using Poco::Message; +using Poco::AutoPtr; + + +class SimpleFormatter: public Formatter +{ +public: + void format(const Message& msg, std::string& text) + { + text = msg.getSource(); + text.append(": "); + text.append(msg.getText()); + } +}; + + +ChannelTest::ChannelTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +ChannelTest::~ChannelTest() +{ +} + + +void ChannelTest::testSplitter() +{ + AutoPtr pChannel = new TestChannel; + AutoPtr pSplitter = new SplitterChannel; + pSplitter->addChannel(pChannel.get()); + pSplitter->addChannel(pChannel.get()); + Message msg; + pSplitter->log(msg); + assert (pChannel->list().size() == 2); +} + + +void ChannelTest::testAsync() +{ + AutoPtr pChannel = new TestChannel; + AutoPtr pAsync = new AsyncChannel(pChannel.get()); + pAsync->open(); + Message msg; + pAsync->log(msg); + pAsync->log(msg); + pAsync->close(); + assert (pChannel->list().size() == 2); +} + + +void ChannelTest::testFormatting() +{ + AutoPtr pChannel = new TestChannel; + AutoPtr pFormatter = new SimpleFormatter; + AutoPtr pFormatterChannel = new FormattingChannel(pFormatter, pChannel.get()); + Message msg("Source", "Text", Message::PRIO_INFORMATION); + pFormatterChannel->log(msg); + assert (pChannel->list().size() == 1); + assert (pChannel->list().begin()->getText() == "Source: Text"); +} + + +void ChannelTest::testConsole() +{ + AutoPtr pChannel = new ConsoleChannel; + AutoPtr pFormatter = new SimpleFormatter; + AutoPtr pFormatterChannel = new FormattingChannel(pFormatter, pChannel.get()); + Message msg("Source", "Text", Message::PRIO_INFORMATION); + pFormatterChannel->log(msg); +} + + +void ChannelTest::testStream() +{ + std::ostringstream str; + AutoPtr pChannel = new StreamChannel(str); + AutoPtr pFormatter = new SimpleFormatter; + AutoPtr pFormatterChannel = new FormattingChannel(pFormatter, pChannel.get()); + Message msg("Source", "Text", Message::PRIO_INFORMATION); + pFormatterChannel->log(msg); + assert (str.str().find("Source: Text") == 0); +} + + +void ChannelTest::setUp() +{ +} + + +void ChannelTest::tearDown() +{ +} + + +CppUnit::Test* ChannelTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("ChannelTest"); + + CppUnit_addTest(pSuite, ChannelTest, testSplitter); + CppUnit_addTest(pSuite, ChannelTest, testAsync); + CppUnit_addTest(pSuite, ChannelTest, testFormatting); + CppUnit_addTest(pSuite, ChannelTest, testConsole); + CppUnit_addTest(pSuite, ChannelTest, testStream); + + return pSuite; +} diff --git a/Foundation/testsuite/src/ChannelTest.h b/Foundation/testsuite/src/ChannelTest.h index e1b35b9d1..535cb952d 100644 --- a/Foundation/testsuite/src/ChannelTest.h +++ b/Foundation/testsuite/src/ChannelTest.h @@ -1,64 +1,64 @@ -// -// ChannelTest.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/ChannelTest.h#1 $ -// -// Definition of the ChannelTest class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 ChannelTest_INCLUDED -#define ChannelTest_INCLUDED - - -#include "Poco/Foundation.h" -#include "CppUnit/TestCase.h" - - -class ChannelTest: public CppUnit::TestCase -{ -public: - ChannelTest(const std::string& name); - ~ChannelTest(); - - void testSplitter(); - void testAsync(); - void testFormatting(); - void testConsole(); - void testStream(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // ChannelTest_INCLUDED +// +// ChannelTest.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/ChannelTest.h#1 $ +// +// Definition of the ChannelTest class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 ChannelTest_INCLUDED +#define ChannelTest_INCLUDED + + +#include "Poco/Foundation.h" +#include "CppUnit/TestCase.h" + + +class ChannelTest: public CppUnit::TestCase +{ +public: + ChannelTest(const std::string& name); + ~ChannelTest(); + + void testSplitter(); + void testAsync(); + void testFormatting(); + void testConsole(); + void testStream(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // ChannelTest_INCLUDED diff --git a/Foundation/testsuite/src/ClassLoaderTest.cpp b/Foundation/testsuite/src/ClassLoaderTest.cpp index c255cbee9..fd3bf1225 100644 --- a/Foundation/testsuite/src/ClassLoaderTest.cpp +++ b/Foundation/testsuite/src/ClassLoaderTest.cpp @@ -1,234 +1,234 @@ -// -// ClassLoaderTest.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/ClassLoaderTest.cpp#2 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "ClassLoaderTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/ClassLoader.h" -#include "Poco/Manifest.h" -#include "Poco/Exception.h" -#include "TestPlugin.h" - - -using Poco::ClassLoader; -using Poco::Manifest; -using Poco::SharedLibrary; -using Poco::AbstractMetaObject; -using Poco::NotFoundException; -using Poco::InvalidAccessException; - - -ClassLoaderTest::ClassLoaderTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -ClassLoaderTest::~ClassLoaderTest() -{ -} - - -void ClassLoaderTest::testClassLoader1() -{ - std::string path = "TestLibrary"; - path.append(SharedLibrary::suffix()); - - ClassLoader cl; - - assert (cl.begin() == cl.end()); - assertNullPtr (cl.findClass("PluginA")); - assertNullPtr (cl.findManifest(path)); - - assert (!cl.isLibraryLoaded(path)); - - try - { - const ClassLoader::Meta& meta = cl.classFor("PluginA"); - fail("not found - must throw exception"); - } - catch (NotFoundException&) - { - } - catch (...) - { - failmsg("wrong exception"); - } - - try - { - const ClassLoader::Manif& manif = cl.manifestFor(path); - fail("not found - must throw exception"); - } - catch (NotFoundException&) - { - } - catch (...) - { - failmsg("wrong exception"); - } -} - - -void ClassLoaderTest::testClassLoader2() -{ - std::string path = "TestLibrary"; - path.append(SharedLibrary::suffix()); - - ClassLoader cl; - cl.loadLibrary(path); - - assert (cl.begin() != cl.end()); - assertNotNullPtr (cl.findClass("PluginA")); - assertNotNullPtr (cl.findClass("PluginB")); - assertNotNullPtr (cl.findClass("PluginC")); - assertNotNullPtr (cl.findManifest(path)); - - assert (cl.isLibraryLoaded(path)); - assert (cl.manifestFor(path).size() == 3); - - ClassLoader::Iterator it = cl.begin(); - assert (it != cl.end()); - assert (it->first == path); - assert (it->second->size() == 3); - ++it; - assert (it == cl.end()); - - TestPlugin* pPluginA = cl.classFor("PluginA").create(); - assert (pPluginA->name() == "PluginA"); - assert (!cl.classFor("PluginA").isAutoDelete(pPluginA)); - delete pPluginA; - - TestPlugin* pPluginB = cl.classFor("PluginB").create(); - assert (pPluginB->name() == "PluginB"); - delete pPluginB; - - pPluginB = cl.create("PluginB"); - assert (pPluginB->name() == "PluginB"); - delete pPluginB; - - assert (cl.canCreate("PluginA")); - assert (cl.canCreate("PluginB")); - assert (!cl.canCreate("PluginC")); - - TestPlugin& pluginC = cl.instance("PluginC"); - assert (pluginC.name() == "PluginC"); - - try - { - TestPlugin& plgB = cl.instance("PluginB"); - fail("not a singleton - must throw"); - } - catch (InvalidAccessException&) - { - } - - try - { - TestPlugin* pPluginC = cl.create("PluginC"); - fail("cannot create a singleton - must throw"); - } - catch (InvalidAccessException&) - { - } - - try - { - const AbstractMetaObject& meta = cl.classFor("PluginC"); - meta.autoDelete(&(meta.instance())); - fail("cannot take ownership of a singleton - must throw"); - } - catch (InvalidAccessException&) - { - } - - const AbstractMetaObject& meta1 = cl.classFor("PluginC"); - assert (meta1.isAutoDelete(&(meta1.instance()))); - - // the following must not produce memory leaks - const AbstractMetaObject& meta2 = cl.classFor("PluginA"); - meta2.autoDelete(meta2.create()); - meta2.autoDelete(meta2.create()); - - TestPlugin* pPlugin = meta2.create(); - meta2.autoDelete(pPlugin); - assert (meta2.isAutoDelete(pPlugin)); - meta2.destroy(pPlugin); - assert (!meta2.isAutoDelete(pPlugin)); - - cl.unloadLibrary(path); -} - - -void ClassLoaderTest::testClassLoader3() -{ - std::string path = "TestLibrary"; - path.append(SharedLibrary::suffix()); - - ClassLoader cl; - cl.loadLibrary(path); - cl.loadLibrary(path); - cl.unloadLibrary(path); - - assert (cl.manifestFor(path).size() == 3); - - ClassLoader::Iterator it = cl.begin(); - assert (it != cl.end()); - assert (it->first == path); - assert (it->second->size() == 3); - ++it; - assert (it == cl.end()); - - cl.unloadLibrary(path); - assertNullPtr (cl.findManifest(path)); -} - - -void ClassLoaderTest::setUp() -{ -} - - -void ClassLoaderTest::tearDown() -{ -} - - -CppUnit::Test* ClassLoaderTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("ClassLoaderTest"); - - CppUnit_addTest(pSuite, ClassLoaderTest, testClassLoader1); - CppUnit_addTest(pSuite, ClassLoaderTest, testClassLoader2); - CppUnit_addTest(pSuite, ClassLoaderTest, testClassLoader3); - - return pSuite; -} +// +// ClassLoaderTest.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/ClassLoaderTest.cpp#2 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "ClassLoaderTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/ClassLoader.h" +#include "Poco/Manifest.h" +#include "Poco/Exception.h" +#include "TestPlugin.h" + + +using Poco::ClassLoader; +using Poco::Manifest; +using Poco::SharedLibrary; +using Poco::AbstractMetaObject; +using Poco::NotFoundException; +using Poco::InvalidAccessException; + + +ClassLoaderTest::ClassLoaderTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +ClassLoaderTest::~ClassLoaderTest() +{ +} + + +void ClassLoaderTest::testClassLoader1() +{ + std::string path = "TestLibrary"; + path.append(SharedLibrary::suffix()); + + ClassLoader cl; + + assert (cl.begin() == cl.end()); + assertNullPtr (cl.findClass("PluginA")); + assertNullPtr (cl.findManifest(path)); + + assert (!cl.isLibraryLoaded(path)); + + try + { + const ClassLoader::Meta& meta = cl.classFor("PluginA"); + fail("not found - must throw exception"); + } + catch (NotFoundException&) + { + } + catch (...) + { + failmsg("wrong exception"); + } + + try + { + const ClassLoader::Manif& manif = cl.manifestFor(path); + fail("not found - must throw exception"); + } + catch (NotFoundException&) + { + } + catch (...) + { + failmsg("wrong exception"); + } +} + + +void ClassLoaderTest::testClassLoader2() +{ + std::string path = "TestLibrary"; + path.append(SharedLibrary::suffix()); + + ClassLoader cl; + cl.loadLibrary(path); + + assert (cl.begin() != cl.end()); + assertNotNullPtr (cl.findClass("PluginA")); + assertNotNullPtr (cl.findClass("PluginB")); + assertNotNullPtr (cl.findClass("PluginC")); + assertNotNullPtr (cl.findManifest(path)); + + assert (cl.isLibraryLoaded(path)); + assert (cl.manifestFor(path).size() == 3); + + ClassLoader::Iterator it = cl.begin(); + assert (it != cl.end()); + assert (it->first == path); + assert (it->second->size() == 3); + ++it; + assert (it == cl.end()); + + TestPlugin* pPluginA = cl.classFor("PluginA").create(); + assert (pPluginA->name() == "PluginA"); + assert (!cl.classFor("PluginA").isAutoDelete(pPluginA)); + delete pPluginA; + + TestPlugin* pPluginB = cl.classFor("PluginB").create(); + assert (pPluginB->name() == "PluginB"); + delete pPluginB; + + pPluginB = cl.create("PluginB"); + assert (pPluginB->name() == "PluginB"); + delete pPluginB; + + assert (cl.canCreate("PluginA")); + assert (cl.canCreate("PluginB")); + assert (!cl.canCreate("PluginC")); + + TestPlugin& pluginC = cl.instance("PluginC"); + assert (pluginC.name() == "PluginC"); + + try + { + TestPlugin& plgB = cl.instance("PluginB"); + fail("not a singleton - must throw"); + } + catch (InvalidAccessException&) + { + } + + try + { + TestPlugin* pPluginC = cl.create("PluginC"); + fail("cannot create a singleton - must throw"); + } + catch (InvalidAccessException&) + { + } + + try + { + const AbstractMetaObject& meta = cl.classFor("PluginC"); + meta.autoDelete(&(meta.instance())); + fail("cannot take ownership of a singleton - must throw"); + } + catch (InvalidAccessException&) + { + } + + const AbstractMetaObject& meta1 = cl.classFor("PluginC"); + assert (meta1.isAutoDelete(&(meta1.instance()))); + + // the following must not produce memory leaks + const AbstractMetaObject& meta2 = cl.classFor("PluginA"); + meta2.autoDelete(meta2.create()); + meta2.autoDelete(meta2.create()); + + TestPlugin* pPlugin = meta2.create(); + meta2.autoDelete(pPlugin); + assert (meta2.isAutoDelete(pPlugin)); + meta2.destroy(pPlugin); + assert (!meta2.isAutoDelete(pPlugin)); + + cl.unloadLibrary(path); +} + + +void ClassLoaderTest::testClassLoader3() +{ + std::string path = "TestLibrary"; + path.append(SharedLibrary::suffix()); + + ClassLoader cl; + cl.loadLibrary(path); + cl.loadLibrary(path); + cl.unloadLibrary(path); + + assert (cl.manifestFor(path).size() == 3); + + ClassLoader::Iterator it = cl.begin(); + assert (it != cl.end()); + assert (it->first == path); + assert (it->second->size() == 3); + ++it; + assert (it == cl.end()); + + cl.unloadLibrary(path); + assertNullPtr (cl.findManifest(path)); +} + + +void ClassLoaderTest::setUp() +{ +} + + +void ClassLoaderTest::tearDown() +{ +} + + +CppUnit::Test* ClassLoaderTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("ClassLoaderTest"); + + CppUnit_addTest(pSuite, ClassLoaderTest, testClassLoader1); + CppUnit_addTest(pSuite, ClassLoaderTest, testClassLoader2); + CppUnit_addTest(pSuite, ClassLoaderTest, testClassLoader3); + + return pSuite; +} diff --git a/Foundation/testsuite/src/ClassLoaderTest.h b/Foundation/testsuite/src/ClassLoaderTest.h index fa8eec904..0cf98c99e 100644 --- a/Foundation/testsuite/src/ClassLoaderTest.h +++ b/Foundation/testsuite/src/ClassLoaderTest.h @@ -1,62 +1,62 @@ -// -// ClassLoaderTest.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/ClassLoaderTest.h#1 $ -// -// Definition of the ClassLoaderTest class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 ClassLoaderTest_INCLUDED -#define ClassLoaderTest_INCLUDED - - -#include "Poco/Foundation.h" -#include "CppUnit/TestCase.h" - - -class ClassLoaderTest: public CppUnit::TestCase -{ -public: - ClassLoaderTest(const std::string& name); - ~ClassLoaderTest(); - - void testClassLoader1(); - void testClassLoader2(); - void testClassLoader3(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // ClassLoaderTest_INCLUDED +// +// ClassLoaderTest.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/ClassLoaderTest.h#1 $ +// +// Definition of the ClassLoaderTest class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 ClassLoaderTest_INCLUDED +#define ClassLoaderTest_INCLUDED + + +#include "Poco/Foundation.h" +#include "CppUnit/TestCase.h" + + +class ClassLoaderTest: public CppUnit::TestCase +{ +public: + ClassLoaderTest(const std::string& name); + ~ClassLoaderTest(); + + void testClassLoader1(); + void testClassLoader2(); + void testClassLoader3(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // ClassLoaderTest_INCLUDED diff --git a/Foundation/testsuite/src/CoreTest.cpp b/Foundation/testsuite/src/CoreTest.cpp index 074705fd8..f3290a234 100644 --- a/Foundation/testsuite/src/CoreTest.cpp +++ b/Foundation/testsuite/src/CoreTest.cpp @@ -1,165 +1,165 @@ -// -// CoreTest.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/CoreTest.cpp#1 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "CoreTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/Bugcheck.h" -#include "Poco/Exception.h" -#include "Poco/Environment.h" -#include "Poco/Thread.h" -#include - - -using Poco::Bugcheck; -using Poco::Exception; -using Poco::Environment; -using Poco::Thread; - - -// -// The bugcheck test is normally disabled, as it -// causes a break into the debugger. -// -#define ENABLE_BUGCHECK_TEST 0 - - -CoreTest::CoreTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -CoreTest::~CoreTest() -{ -} - - -void CoreTest::testPlatform() -{ - std::cout << "POCO_OS: " << POCO_OS << std::endl; - std::cout << "POCO_ARCH: " << POCO_ARCH << std::endl; -} - - -void CoreTest::testFixedLength() -{ - assert (sizeof(Poco::Int8) == 1); - assert (sizeof(Poco::UInt8) == 1); - assert (sizeof(Poco::Int16) == 2); - assert (sizeof(Poco::UInt16) == 2); - assert (sizeof(Poco::Int32) == 4); - assert (sizeof(Poco::UInt32) == 4); - #if defined(POCO_HAVE_INT64) - assert (sizeof(Poco::Int64) == 8); - assert (sizeof(Poco::UInt64) == 8); - #endif - assert (sizeof(Poco::IntPtr) == sizeof(void*)); - assert (sizeof(Poco::UIntPtr) == sizeof(void*)); -} - - -void CoreTest::testBugcheck() -{ -#if ENABLE_BUGCHECK_TEST - try - { - Bugcheck::assertion("test", __FILE__, __LINE__); - failmsg("must throw exception"); - } - catch (Exception&) - { - } - - try - { - Bugcheck::nullPointer("test", __FILE__, __LINE__); - failmsg("must throw exception"); - } - catch (Exception&) - { - } - - try - { - Bugcheck::bugcheck("test", __FILE__, __LINE__); - failmsg("must throw exception"); - } - catch (Exception&) - { - } -#endif -} - - -void CoreTest::testEnvironment() -{ - Environment::set("FOO", "BAR"); - assert (Environment::has("FOO")); - assert (Environment::get("FOO") == "BAR"); - assert (!Environment::has("THISONEDOESNOTEXIST123")); - try - { - std::string v = Environment::get("THISONEDOESNOTEXIST123"); - failmsg("Environment variable does not exist - must throw exception"); - } - catch (Exception&) - { - } - - std::cout << "OS Name: " << Environment::osName() << std::endl; - std::cout << "OS Version: " << Environment::osVersion() << std::endl; - std::cout << "OS Architecture: " << Environment::osArchitecture() << std::endl; - std::cout << "Node Name: " << Environment::nodeName() << std::endl; -} - - -void CoreTest::setUp() -{ -} - - -void CoreTest::tearDown() -{ -} - - -CppUnit::Test* CoreTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("CoreTest"); - - CppUnit_addTest(pSuite, CoreTest, testPlatform); - CppUnit_addTest(pSuite, CoreTest, testFixedLength); - CppUnit_addTest(pSuite, CoreTest, testBugcheck); - CppUnit_addTest(pSuite, CoreTest, testEnvironment); - - return pSuite; -} +// +// CoreTest.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/CoreTest.cpp#1 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "CoreTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/Bugcheck.h" +#include "Poco/Exception.h" +#include "Poco/Environment.h" +#include "Poco/Thread.h" +#include + + +using Poco::Bugcheck; +using Poco::Exception; +using Poco::Environment; +using Poco::Thread; + + +// +// The bugcheck test is normally disabled, as it +// causes a break into the debugger. +// +#define ENABLE_BUGCHECK_TEST 0 + + +CoreTest::CoreTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +CoreTest::~CoreTest() +{ +} + + +void CoreTest::testPlatform() +{ + std::cout << "POCO_OS: " << POCO_OS << std::endl; + std::cout << "POCO_ARCH: " << POCO_ARCH << std::endl; +} + + +void CoreTest::testFixedLength() +{ + assert (sizeof(Poco::Int8) == 1); + assert (sizeof(Poco::UInt8) == 1); + assert (sizeof(Poco::Int16) == 2); + assert (sizeof(Poco::UInt16) == 2); + assert (sizeof(Poco::Int32) == 4); + assert (sizeof(Poco::UInt32) == 4); + #if defined(POCO_HAVE_INT64) + assert (sizeof(Poco::Int64) == 8); + assert (sizeof(Poco::UInt64) == 8); + #endif + assert (sizeof(Poco::IntPtr) == sizeof(void*)); + assert (sizeof(Poco::UIntPtr) == sizeof(void*)); +} + + +void CoreTest::testBugcheck() +{ +#if ENABLE_BUGCHECK_TEST + try + { + Bugcheck::assertion("test", __FILE__, __LINE__); + failmsg("must throw exception"); + } + catch (Exception&) + { + } + + try + { + Bugcheck::nullPointer("test", __FILE__, __LINE__); + failmsg("must throw exception"); + } + catch (Exception&) + { + } + + try + { + Bugcheck::bugcheck("test", __FILE__, __LINE__); + failmsg("must throw exception"); + } + catch (Exception&) + { + } +#endif +} + + +void CoreTest::testEnvironment() +{ + Environment::set("FOO", "BAR"); + assert (Environment::has("FOO")); + assert (Environment::get("FOO") == "BAR"); + assert (!Environment::has("THISONEDOESNOTEXIST123")); + try + { + std::string v = Environment::get("THISONEDOESNOTEXIST123"); + failmsg("Environment variable does not exist - must throw exception"); + } + catch (Exception&) + { + } + + std::cout << "OS Name: " << Environment::osName() << std::endl; + std::cout << "OS Version: " << Environment::osVersion() << std::endl; + std::cout << "OS Architecture: " << Environment::osArchitecture() << std::endl; + std::cout << "Node Name: " << Environment::nodeName() << std::endl; +} + + +void CoreTest::setUp() +{ +} + + +void CoreTest::tearDown() +{ +} + + +CppUnit::Test* CoreTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("CoreTest"); + + CppUnit_addTest(pSuite, CoreTest, testPlatform); + CppUnit_addTest(pSuite, CoreTest, testFixedLength); + CppUnit_addTest(pSuite, CoreTest, testBugcheck); + CppUnit_addTest(pSuite, CoreTest, testEnvironment); + + return pSuite; +} diff --git a/Foundation/testsuite/src/CoreTest.h b/Foundation/testsuite/src/CoreTest.h index 81e2e4250..2654eba73 100644 --- a/Foundation/testsuite/src/CoreTest.h +++ b/Foundation/testsuite/src/CoreTest.h @@ -1,64 +1,64 @@ -// -// CoreTest.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/CoreTest.h#1 $ -// -// Definition of the CoreTest class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 CoreTest_INCLUDED -#define CoreTest_INCLUDED - - -#include "Poco/Foundation.h" -#include "CppUnit/TestCase.h" - - -class CoreTest: public CppUnit::TestCase -{ -public: - CoreTest(const std::string& name); - ~CoreTest(); - - void testPlatform(); - void testFixedLength(); - void testBugcheck(); - void testFPE(); - void testEnvironment(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // CoreTest_INCLUDED +// +// CoreTest.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/CoreTest.h#1 $ +// +// Definition of the CoreTest class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 CoreTest_INCLUDED +#define CoreTest_INCLUDED + + +#include "Poco/Foundation.h" +#include "CppUnit/TestCase.h" + + +class CoreTest: public CppUnit::TestCase +{ +public: + CoreTest(const std::string& name); + ~CoreTest(); + + void testPlatform(); + void testFixedLength(); + void testBugcheck(); + void testFPE(); + void testEnvironment(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // CoreTest_INCLUDED diff --git a/Foundation/testsuite/src/CoreTestSuite.cpp b/Foundation/testsuite/src/CoreTestSuite.cpp index 136fa9652..5b12394af 100644 --- a/Foundation/testsuite/src/CoreTestSuite.cpp +++ b/Foundation/testsuite/src/CoreTestSuite.cpp @@ -1,76 +1,76 @@ -// -// CoreTestSuite.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/CoreTestSuite.cpp#1 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "CoreTestSuite.h" -#include "CoreTest.h" -#include "AutoPtrTest.h" -#include "SharedPtrTest.h" -#include "AutoReleasePoolTest.h" -#include "ByteOrderTest.h" -#include "StringTest.h" -#include "StringTokenizerTest.h" -#include "FPETest.h" -#include "RegularExpressionTest.h" -#include "NDCTest.h" -#include "NumberFormatterTest.h" -#include "NumberParserTest.h" -#include "DynamicFactoryTest.h" -#include "MemoryPoolTest.h" -#include "AnyTest.h" -#include "HashTest.h" -#include "FormatTest.h" - - -CppUnit::Test* CoreTestSuite::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("CoreTestSuite"); - - pSuite->addTest(CoreTest::suite()); - pSuite->addTest(AutoPtrTest::suite()); - pSuite->addTest(SharedPtrTest::suite()); - pSuite->addTest(AutoReleasePoolTest::suite()); - pSuite->addTest(ByteOrderTest::suite()); - pSuite->addTest(StringTest::suite()); - pSuite->addTest(StringTokenizerTest::suite()); - pSuite->addTest(FPETest::suite()); - pSuite->addTest(RegularExpressionTest::suite()); - pSuite->addTest(NDCTest::suite()); - pSuite->addTest(NumberFormatterTest::suite()); - pSuite->addTest(NumberParserTest::suite()); - pSuite->addTest(DynamicFactoryTest::suite()); - pSuite->addTest(MemoryPoolTest::suite()); - pSuite->addTest(AnyTest::suite()); - pSuite->addTest(HashTest::suite()); - pSuite->addTest(FormatTest::suite()); - - return pSuite; -} +// +// CoreTestSuite.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/CoreTestSuite.cpp#1 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "CoreTestSuite.h" +#include "CoreTest.h" +#include "AutoPtrTest.h" +#include "SharedPtrTest.h" +#include "AutoReleasePoolTest.h" +#include "ByteOrderTest.h" +#include "StringTest.h" +#include "StringTokenizerTest.h" +#include "FPETest.h" +#include "RegularExpressionTest.h" +#include "NDCTest.h" +#include "NumberFormatterTest.h" +#include "NumberParserTest.h" +#include "DynamicFactoryTest.h" +#include "MemoryPoolTest.h" +#include "AnyTest.h" +#include "HashTest.h" +#include "FormatTest.h" + + +CppUnit::Test* CoreTestSuite::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("CoreTestSuite"); + + pSuite->addTest(CoreTest::suite()); + pSuite->addTest(AutoPtrTest::suite()); + pSuite->addTest(SharedPtrTest::suite()); + pSuite->addTest(AutoReleasePoolTest::suite()); + pSuite->addTest(ByteOrderTest::suite()); + pSuite->addTest(StringTest::suite()); + pSuite->addTest(StringTokenizerTest::suite()); + pSuite->addTest(FPETest::suite()); + pSuite->addTest(RegularExpressionTest::suite()); + pSuite->addTest(NDCTest::suite()); + pSuite->addTest(NumberFormatterTest::suite()); + pSuite->addTest(NumberParserTest::suite()); + pSuite->addTest(DynamicFactoryTest::suite()); + pSuite->addTest(MemoryPoolTest::suite()); + pSuite->addTest(AnyTest::suite()); + pSuite->addTest(HashTest::suite()); + pSuite->addTest(FormatTest::suite()); + + return pSuite; +} diff --git a/Foundation/testsuite/src/CoreTestSuite.h b/Foundation/testsuite/src/CoreTestSuite.h index 773596c3e..15ba20691 100644 --- a/Foundation/testsuite/src/CoreTestSuite.h +++ b/Foundation/testsuite/src/CoreTestSuite.h @@ -1,49 +1,49 @@ -// -// CoreTestSuite.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/CoreTestSuite.h#1 $ -// -// Definition of the CoreTestSuite class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 CoreTestSuite_INCLUDED -#define CoreTestSuite_INCLUDED - - -#include "CppUnit/TestSuite.h" - - -class CoreTestSuite -{ -public: - static CppUnit::Test* suite(); -}; - - -#endif // CoreTestSuite_INCLUDED +// +// CoreTestSuite.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/CoreTestSuite.h#1 $ +// +// Definition of the CoreTestSuite class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 CoreTestSuite_INCLUDED +#define CoreTestSuite_INCLUDED + + +#include "CppUnit/TestSuite.h" + + +class CoreTestSuite +{ +public: + static CppUnit::Test* suite(); +}; + + +#endif // CoreTestSuite_INCLUDED diff --git a/Foundation/testsuite/src/CountingStreamTest.cpp b/Foundation/testsuite/src/CountingStreamTest.cpp index 950551e04..8a2f95dda 100644 --- a/Foundation/testsuite/src/CountingStreamTest.cpp +++ b/Foundation/testsuite/src/CountingStreamTest.cpp @@ -1,124 +1,124 @@ -// -// CountingStreamTest.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/CountingStreamTest.cpp#1 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "CountingStreamTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/CountingStream.h" -#include - - -using Poco::CountingInputStream; -using Poco::CountingOutputStream; - - -CountingStreamTest::CountingStreamTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -CountingStreamTest::~CountingStreamTest() -{ -} - - -void CountingStreamTest::testInput() -{ - char c; - std::istringstream istr1("foo"); - CountingInputStream ci1(istr1); - while (ci1.good()) ci1.get(c); - assert (ci1.lines() == 1); - assert (ci1.chars() == 3); - assert (ci1.pos() == 3); - - std::istringstream istr2("foo\nbar"); - CountingInputStream ci2(istr2); - while (ci2.good()) ci2.get(c); - assert (ci2.lines() == 2); - assert (ci2.chars() == 7); - assert (ci2.pos() == 3); - - std::istringstream istr3("foo\nbar\n"); - CountingInputStream ci3(istr3); - while (ci3.good()) ci3.get(c); - assert (ci3.lines() == 2); - assert (ci3.chars() == 8); - assert (ci3.pos() == 0); -} - - -void CountingStreamTest::testOutput() -{ - std::ostringstream ostr1; - CountingOutputStream co1(ostr1); - co1 << "foo"; - assert (ostr1.str() == "foo"); - assert (co1.lines() == 1); - assert (co1.chars() == 3); - assert (co1.pos() == 3); - - std::ostringstream ostr2; - CountingOutputStream co2(ostr2); - co2 << "foo\nbar"; - assert (ostr2.str() == "foo\nbar"); - assert (co2.lines() == 2); - assert (co2.chars() == 7); - assert (co2.pos() == 3); - - CountingOutputStream co3; - co3 << "foo\nbar\n"; - assert (co3.lines() == 2); - assert (co3.chars() == 8); - assert (co3.pos() == 0); -} - - -void CountingStreamTest::setUp() -{ -} - - -void CountingStreamTest::tearDown() -{ -} - - -CppUnit::Test* CountingStreamTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("CountingStreamTest"); - - CppUnit_addTest(pSuite, CountingStreamTest, testInput); - CppUnit_addTest(pSuite, CountingStreamTest, testOutput); - - return pSuite; -} +// +// CountingStreamTest.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/CountingStreamTest.cpp#1 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "CountingStreamTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/CountingStream.h" +#include + + +using Poco::CountingInputStream; +using Poco::CountingOutputStream; + + +CountingStreamTest::CountingStreamTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +CountingStreamTest::~CountingStreamTest() +{ +} + + +void CountingStreamTest::testInput() +{ + char c; + std::istringstream istr1("foo"); + CountingInputStream ci1(istr1); + while (ci1.good()) ci1.get(c); + assert (ci1.lines() == 1); + assert (ci1.chars() == 3); + assert (ci1.pos() == 3); + + std::istringstream istr2("foo\nbar"); + CountingInputStream ci2(istr2); + while (ci2.good()) ci2.get(c); + assert (ci2.lines() == 2); + assert (ci2.chars() == 7); + assert (ci2.pos() == 3); + + std::istringstream istr3("foo\nbar\n"); + CountingInputStream ci3(istr3); + while (ci3.good()) ci3.get(c); + assert (ci3.lines() == 2); + assert (ci3.chars() == 8); + assert (ci3.pos() == 0); +} + + +void CountingStreamTest::testOutput() +{ + std::ostringstream ostr1; + CountingOutputStream co1(ostr1); + co1 << "foo"; + assert (ostr1.str() == "foo"); + assert (co1.lines() == 1); + assert (co1.chars() == 3); + assert (co1.pos() == 3); + + std::ostringstream ostr2; + CountingOutputStream co2(ostr2); + co2 << "foo\nbar"; + assert (ostr2.str() == "foo\nbar"); + assert (co2.lines() == 2); + assert (co2.chars() == 7); + assert (co2.pos() == 3); + + CountingOutputStream co3; + co3 << "foo\nbar\n"; + assert (co3.lines() == 2); + assert (co3.chars() == 8); + assert (co3.pos() == 0); +} + + +void CountingStreamTest::setUp() +{ +} + + +void CountingStreamTest::tearDown() +{ +} + + +CppUnit::Test* CountingStreamTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("CountingStreamTest"); + + CppUnit_addTest(pSuite, CountingStreamTest, testInput); + CppUnit_addTest(pSuite, CountingStreamTest, testOutput); + + return pSuite; +} diff --git a/Foundation/testsuite/src/CountingStreamTest.h b/Foundation/testsuite/src/CountingStreamTest.h index 1c0484443..c4ebf4be8 100644 --- a/Foundation/testsuite/src/CountingStreamTest.h +++ b/Foundation/testsuite/src/CountingStreamTest.h @@ -1,61 +1,61 @@ -// -// CountingStreamTest.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/CountingStreamTest.h#1 $ -// -// Definition of the CountingStreamTest class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 CountingStreamTest_INCLUDED -#define CountingStreamTest_INCLUDED - - -#include "Poco/Foundation.h" -#include "CppUnit/TestCase.h" - - -class CountingStreamTest: public CppUnit::TestCase -{ -public: - CountingStreamTest(const std::string& name); - ~CountingStreamTest(); - - void testInput(); - void testOutput(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // CountingStreamTest_INCLUDED +// +// CountingStreamTest.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/CountingStreamTest.h#1 $ +// +// Definition of the CountingStreamTest class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 CountingStreamTest_INCLUDED +#define CountingStreamTest_INCLUDED + + +#include "Poco/Foundation.h" +#include "CppUnit/TestCase.h" + + +class CountingStreamTest: public CppUnit::TestCase +{ +public: + CountingStreamTest(const std::string& name); + ~CountingStreamTest(); + + void testInput(); + void testOutput(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // CountingStreamTest_INCLUDED diff --git a/Foundation/testsuite/src/CryptTestSuite.cpp b/Foundation/testsuite/src/CryptTestSuite.cpp index be5f4c105..7458d3afa 100644 --- a/Foundation/testsuite/src/CryptTestSuite.cpp +++ b/Foundation/testsuite/src/CryptTestSuite.cpp @@ -1,58 +1,58 @@ -// -// CryptTestSuite.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/CryptTestSuite.cpp#1 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "CryptTestSuite.h" -#include "MD2EngineTest.h" -#include "MD4EngineTest.h" -#include "MD5EngineTest.h" -#include "SHA1EngineTest.h" -#include "HMACEngineTest.h" -#include "DigestStreamTest.h" -#include "RandomTest.h" -#include "RandomStreamTest.h" - - -CppUnit::Test* CryptTestSuite::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("CryptTestTestSuite"); - - pSuite->addTest(MD2EngineTest::suite()); - pSuite->addTest(MD4EngineTest::suite()); - pSuite->addTest(MD5EngineTest::suite()); - pSuite->addTest(SHA1EngineTest::suite()); - pSuite->addTest(HMACEngineTest::suite()); - pSuite->addTest(DigestStreamTest::suite()); - pSuite->addTest(RandomTest::suite()); - pSuite->addTest(RandomStreamTest::suite()); - - return pSuite; -} +// +// CryptTestSuite.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/CryptTestSuite.cpp#1 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "CryptTestSuite.h" +#include "MD2EngineTest.h" +#include "MD4EngineTest.h" +#include "MD5EngineTest.h" +#include "SHA1EngineTest.h" +#include "HMACEngineTest.h" +#include "DigestStreamTest.h" +#include "RandomTest.h" +#include "RandomStreamTest.h" + + +CppUnit::Test* CryptTestSuite::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("CryptTestTestSuite"); + + pSuite->addTest(MD2EngineTest::suite()); + pSuite->addTest(MD4EngineTest::suite()); + pSuite->addTest(MD5EngineTest::suite()); + pSuite->addTest(SHA1EngineTest::suite()); + pSuite->addTest(HMACEngineTest::suite()); + pSuite->addTest(DigestStreamTest::suite()); + pSuite->addTest(RandomTest::suite()); + pSuite->addTest(RandomStreamTest::suite()); + + return pSuite; +} diff --git a/Foundation/testsuite/src/CryptTestSuite.h b/Foundation/testsuite/src/CryptTestSuite.h index b8b4739bc..0d9e49c9a 100644 --- a/Foundation/testsuite/src/CryptTestSuite.h +++ b/Foundation/testsuite/src/CryptTestSuite.h @@ -1,49 +1,49 @@ -// -// CryptTestSuite.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/CryptTestSuite.h#1 $ -// -// Definition of the CryptTestSuite class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 CryptTestSuite_INCLUDED -#define CryptTestSuite_INCLUDED - - -#include "CppUnit/TestSuite.h" - - -class CryptTestSuite -{ -public: - static CppUnit::Test* suite(); -}; - - -#endif // CryptTestSuite_INCLUDED +// +// CryptTestSuite.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/CryptTestSuite.h#1 $ +// +// Definition of the CryptTestSuite class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 CryptTestSuite_INCLUDED +#define CryptTestSuite_INCLUDED + + +#include "CppUnit/TestSuite.h" + + +class CryptTestSuite +{ +public: + static CppUnit::Test* suite(); +}; + + +#endif // CryptTestSuite_INCLUDED diff --git a/Foundation/testsuite/src/DateTimeFormatterTest.cpp b/Foundation/testsuite/src/DateTimeFormatterTest.cpp index 59fe6aa9e..80ca3ee9c 100644 --- a/Foundation/testsuite/src/DateTimeFormatterTest.cpp +++ b/Foundation/testsuite/src/DateTimeFormatterTest.cpp @@ -1,229 +1,229 @@ -// -// DateTimeFormatterTest.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/DateTimeFormatterTest.cpp#1 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "DateTimeFormatterTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/DateTimeFormatter.h" -#include "Poco/DateTimeFormat.h" -#include "Poco/DateTime.h" -#include "Poco/Timespan.h" - - -using Poco::DateTime; -using Poco::Timespan; -using Poco::DateTimeFormat; -using Poco::DateTimeFormatter; - - -DateTimeFormatterTest::DateTimeFormatterTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -DateTimeFormatterTest::~DateTimeFormatterTest() -{ -} - - -void DateTimeFormatterTest::testISO8601() -{ - DateTime dt(2005, 1, 8, 12, 30, 00); - - std::string str = DateTimeFormatter::format(dt, DateTimeFormat::ISO8601_FORMAT); - assert (str == "2005-01-08T12:30:00Z"); - - str = DateTimeFormatter::format(dt, DateTimeFormat::ISO8601_FORMAT, 3600); - assert (str == "2005-01-08T12:30:00+01:00"); - - str = DateTimeFormatter::format(dt, DateTimeFormat::ISO8601_FORMAT, -3600); - assert (str == "2005-01-08T12:30:00-01:00"); -} - - -void DateTimeFormatterTest::testRFC822() -{ - DateTime dt(2005, 1, 8, 12, 30, 00); - - std::string str = DateTimeFormatter::format(dt, DateTimeFormat::RFC822_FORMAT); - assert (str == "Sat, 8 Jan 05 12:30:00 GMT"); - - str = DateTimeFormatter::format(dt, DateTimeFormat::RFC822_FORMAT, 3600); - assert (str == "Sat, 8 Jan 05 12:30:00 +0100"); - - str = DateTimeFormatter::format(dt, DateTimeFormat::RFC822_FORMAT, -3600); - assert (str == "Sat, 8 Jan 05 12:30:00 -0100"); -} - - -void DateTimeFormatterTest::testRFC1123() -{ - DateTime dt(2005, 1, 8, 12, 30, 00); - - std::string str = DateTimeFormatter::format(dt, DateTimeFormat::RFC1123_FORMAT); - assert (str == "Sat, 8 Jan 2005 12:30:00 GMT"); - - str = DateTimeFormatter::format(dt, DateTimeFormat::RFC1123_FORMAT, 3600); - assert (str == "Sat, 8 Jan 2005 12:30:00 +0100"); - - str = DateTimeFormatter::format(dt, DateTimeFormat::RFC1123_FORMAT, -3600); - assert (str == "Sat, 8 Jan 2005 12:30:00 -0100"); -} - - -void DateTimeFormatterTest::testHTTP() -{ - DateTime dt(2005, 1, 8, 12, 30, 00); - - std::string str = DateTimeFormatter::format(dt, DateTimeFormat::HTTP_FORMAT); - assert (str == "Sat, 08 Jan 2005 12:30:00 GMT"); - - str = DateTimeFormatter::format(dt, DateTimeFormat::HTTP_FORMAT, 3600); - assert (str == "Sat, 08 Jan 2005 12:30:00 +0100"); - - str = DateTimeFormatter::format(dt, DateTimeFormat::HTTP_FORMAT, -3600); - assert (str == "Sat, 08 Jan 2005 12:30:00 -0100"); -} - - -void DateTimeFormatterTest::testRFC850() -{ - DateTime dt(2005, 1, 8, 12, 30, 00); - - std::string str = DateTimeFormatter::format(dt, DateTimeFormat::RFC850_FORMAT); - assert (str == "Saturday, 8-Jan-05 12:30:00 GMT"); - - str = DateTimeFormatter::format(dt, DateTimeFormat::RFC850_FORMAT, 3600); - assert (str == "Saturday, 8-Jan-05 12:30:00 +0100"); - - str = DateTimeFormatter::format(dt, DateTimeFormat::RFC850_FORMAT, -3600); - assert (str == "Saturday, 8-Jan-05 12:30:00 -0100"); -} - - -void DateTimeFormatterTest::testRFC1036() -{ - DateTime dt(2005, 1, 8, 12, 30, 00); - - std::string str = DateTimeFormatter::format(dt, DateTimeFormat::RFC1036_FORMAT); - assert (str == "Saturday, 8 Jan 05 12:30:00 GMT"); - - str = DateTimeFormatter::format(dt, DateTimeFormat::RFC1036_FORMAT, 3600); - assert (str == "Saturday, 8 Jan 05 12:30:00 +0100"); - - str = DateTimeFormatter::format(dt, DateTimeFormat::RFC1036_FORMAT, -3600); - assert (str == "Saturday, 8 Jan 05 12:30:00 -0100"); -} - - -void DateTimeFormatterTest::testASCTIME() -{ - DateTime dt(2005, 1, 8, 12, 30, 00); - - std::string str = DateTimeFormatter::format(dt, DateTimeFormat::ASCTIME_FORMAT); - assert (str == "Sat Jan 8 12:30:00 2005"); -} - - -void DateTimeFormatterTest::testSORTABLE() -{ - DateTime dt(2005, 1, 8, 12, 30, 00); - - std::string str = DateTimeFormatter::format(dt, DateTimeFormat::SORTABLE_FORMAT); - assert (str == "2005-01-08 12:30:00"); -} - - -void DateTimeFormatterTest::testCustom() -{ - DateTime dt(2005, 1, 8, 12, 30, 00, 250); - - std::string str = DateTimeFormatter::format(dt, "%w/%W/%b/%B/%d/%e/%f/%m/%n/%o/%y/%Y/%H/%h/%a/%A/%M/%S/%i/%c/%z/%Z/%%"); - assert (str == "Sat/Saturday/Jan/January/08/8/ 8/01/1/ 1/05/2005/12/12/pm/PM/30/00/250/2/Z/GMT/%"); -} - - -void DateTimeFormatterTest::testTimespan() -{ - Timespan ts(1, 1, 1, 1, 1000); - std::string str = DateTimeFormatter::format(ts); - assert (str == "1d 01:01:01.001"); - - Timespan ts1(1, 24, 1, 1, 1000); - str = DateTimeFormatter::format(ts1); - assert (str == "2d 00:01:01.001"); - - Timespan ts2(1, 25, 1, 1, 1000); - str = DateTimeFormatter::format(ts2); - assert (str == "2d 01:01:01.001"); - - Timespan ts3(5, 4, 3, 2, 1000); - str = DateTimeFormatter::format(ts3, "%i.%S:%M:%H d%d %%"); - assert (str == "001.02:03:04 d5 %"); - - Timespan ts4(0, 24, 60, 60, 1001000); - str = DateTimeFormatter::format(ts4); - assert (str == "1d 01:01:01.001"); - - Timespan ts5(2, 11, 30, 20, 0); - str = DateTimeFormatter::format(ts5, "%h %m %s"); - assert (str == "59 3570 214220"); -} - - -void DateTimeFormatterTest::setUp() -{ -} - - -void DateTimeFormatterTest::tearDown() -{ -} - - -CppUnit::Test* DateTimeFormatterTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("DateTimeFormatterTest"); - - CppUnit_addTest(pSuite, DateTimeFormatterTest, testISO8601); - CppUnit_addTest(pSuite, DateTimeFormatterTest, testRFC822); - CppUnit_addTest(pSuite, DateTimeFormatterTest, testRFC1123); - CppUnit_addTest(pSuite, DateTimeFormatterTest, testHTTP); - CppUnit_addTest(pSuite, DateTimeFormatterTest, testRFC850); - CppUnit_addTest(pSuite, DateTimeFormatterTest, testRFC1036); - CppUnit_addTest(pSuite, DateTimeFormatterTest, testASCTIME); - CppUnit_addTest(pSuite, DateTimeFormatterTest, testSORTABLE); - CppUnit_addTest(pSuite, DateTimeFormatterTest, testCustom); - CppUnit_addTest(pSuite, DateTimeFormatterTest, testTimespan); - - return pSuite; -} +// +// DateTimeFormatterTest.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/DateTimeFormatterTest.cpp#1 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "DateTimeFormatterTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/DateTimeFormatter.h" +#include "Poco/DateTimeFormat.h" +#include "Poco/DateTime.h" +#include "Poco/Timespan.h" + + +using Poco::DateTime; +using Poco::Timespan; +using Poco::DateTimeFormat; +using Poco::DateTimeFormatter; + + +DateTimeFormatterTest::DateTimeFormatterTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +DateTimeFormatterTest::~DateTimeFormatterTest() +{ +} + + +void DateTimeFormatterTest::testISO8601() +{ + DateTime dt(2005, 1, 8, 12, 30, 00); + + std::string str = DateTimeFormatter::format(dt, DateTimeFormat::ISO8601_FORMAT); + assert (str == "2005-01-08T12:30:00Z"); + + str = DateTimeFormatter::format(dt, DateTimeFormat::ISO8601_FORMAT, 3600); + assert (str == "2005-01-08T12:30:00+01:00"); + + str = DateTimeFormatter::format(dt, DateTimeFormat::ISO8601_FORMAT, -3600); + assert (str == "2005-01-08T12:30:00-01:00"); +} + + +void DateTimeFormatterTest::testRFC822() +{ + DateTime dt(2005, 1, 8, 12, 30, 00); + + std::string str = DateTimeFormatter::format(dt, DateTimeFormat::RFC822_FORMAT); + assert (str == "Sat, 8 Jan 05 12:30:00 GMT"); + + str = DateTimeFormatter::format(dt, DateTimeFormat::RFC822_FORMAT, 3600); + assert (str == "Sat, 8 Jan 05 12:30:00 +0100"); + + str = DateTimeFormatter::format(dt, DateTimeFormat::RFC822_FORMAT, -3600); + assert (str == "Sat, 8 Jan 05 12:30:00 -0100"); +} + + +void DateTimeFormatterTest::testRFC1123() +{ + DateTime dt(2005, 1, 8, 12, 30, 00); + + std::string str = DateTimeFormatter::format(dt, DateTimeFormat::RFC1123_FORMAT); + assert (str == "Sat, 8 Jan 2005 12:30:00 GMT"); + + str = DateTimeFormatter::format(dt, DateTimeFormat::RFC1123_FORMAT, 3600); + assert (str == "Sat, 8 Jan 2005 12:30:00 +0100"); + + str = DateTimeFormatter::format(dt, DateTimeFormat::RFC1123_FORMAT, -3600); + assert (str == "Sat, 8 Jan 2005 12:30:00 -0100"); +} + + +void DateTimeFormatterTest::testHTTP() +{ + DateTime dt(2005, 1, 8, 12, 30, 00); + + std::string str = DateTimeFormatter::format(dt, DateTimeFormat::HTTP_FORMAT); + assert (str == "Sat, 08 Jan 2005 12:30:00 GMT"); + + str = DateTimeFormatter::format(dt, DateTimeFormat::HTTP_FORMAT, 3600); + assert (str == "Sat, 08 Jan 2005 12:30:00 +0100"); + + str = DateTimeFormatter::format(dt, DateTimeFormat::HTTP_FORMAT, -3600); + assert (str == "Sat, 08 Jan 2005 12:30:00 -0100"); +} + + +void DateTimeFormatterTest::testRFC850() +{ + DateTime dt(2005, 1, 8, 12, 30, 00); + + std::string str = DateTimeFormatter::format(dt, DateTimeFormat::RFC850_FORMAT); + assert (str == "Saturday, 8-Jan-05 12:30:00 GMT"); + + str = DateTimeFormatter::format(dt, DateTimeFormat::RFC850_FORMAT, 3600); + assert (str == "Saturday, 8-Jan-05 12:30:00 +0100"); + + str = DateTimeFormatter::format(dt, DateTimeFormat::RFC850_FORMAT, -3600); + assert (str == "Saturday, 8-Jan-05 12:30:00 -0100"); +} + + +void DateTimeFormatterTest::testRFC1036() +{ + DateTime dt(2005, 1, 8, 12, 30, 00); + + std::string str = DateTimeFormatter::format(dt, DateTimeFormat::RFC1036_FORMAT); + assert (str == "Saturday, 8 Jan 05 12:30:00 GMT"); + + str = DateTimeFormatter::format(dt, DateTimeFormat::RFC1036_FORMAT, 3600); + assert (str == "Saturday, 8 Jan 05 12:30:00 +0100"); + + str = DateTimeFormatter::format(dt, DateTimeFormat::RFC1036_FORMAT, -3600); + assert (str == "Saturday, 8 Jan 05 12:30:00 -0100"); +} + + +void DateTimeFormatterTest::testASCTIME() +{ + DateTime dt(2005, 1, 8, 12, 30, 00); + + std::string str = DateTimeFormatter::format(dt, DateTimeFormat::ASCTIME_FORMAT); + assert (str == "Sat Jan 8 12:30:00 2005"); +} + + +void DateTimeFormatterTest::testSORTABLE() +{ + DateTime dt(2005, 1, 8, 12, 30, 00); + + std::string str = DateTimeFormatter::format(dt, DateTimeFormat::SORTABLE_FORMAT); + assert (str == "2005-01-08 12:30:00"); +} + + +void DateTimeFormatterTest::testCustom() +{ + DateTime dt(2005, 1, 8, 12, 30, 00, 250); + + std::string str = DateTimeFormatter::format(dt, "%w/%W/%b/%B/%d/%e/%f/%m/%n/%o/%y/%Y/%H/%h/%a/%A/%M/%S/%i/%c/%z/%Z/%%"); + assert (str == "Sat/Saturday/Jan/January/08/8/ 8/01/1/ 1/05/2005/12/12/pm/PM/30/00/250/2/Z/GMT/%"); +} + + +void DateTimeFormatterTest::testTimespan() +{ + Timespan ts(1, 1, 1, 1, 1000); + std::string str = DateTimeFormatter::format(ts); + assert (str == "1d 01:01:01.001"); + + Timespan ts1(1, 24, 1, 1, 1000); + str = DateTimeFormatter::format(ts1); + assert (str == "2d 00:01:01.001"); + + Timespan ts2(1, 25, 1, 1, 1000); + str = DateTimeFormatter::format(ts2); + assert (str == "2d 01:01:01.001"); + + Timespan ts3(5, 4, 3, 2, 1000); + str = DateTimeFormatter::format(ts3, "%i.%S:%M:%H d%d %%"); + assert (str == "001.02:03:04 d5 %"); + + Timespan ts4(0, 24, 60, 60, 1001000); + str = DateTimeFormatter::format(ts4); + assert (str == "1d 01:01:01.001"); + + Timespan ts5(2, 11, 30, 20, 0); + str = DateTimeFormatter::format(ts5, "%h %m %s"); + assert (str == "59 3570 214220"); +} + + +void DateTimeFormatterTest::setUp() +{ +} + + +void DateTimeFormatterTest::tearDown() +{ +} + + +CppUnit::Test* DateTimeFormatterTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("DateTimeFormatterTest"); + + CppUnit_addTest(pSuite, DateTimeFormatterTest, testISO8601); + CppUnit_addTest(pSuite, DateTimeFormatterTest, testRFC822); + CppUnit_addTest(pSuite, DateTimeFormatterTest, testRFC1123); + CppUnit_addTest(pSuite, DateTimeFormatterTest, testHTTP); + CppUnit_addTest(pSuite, DateTimeFormatterTest, testRFC850); + CppUnit_addTest(pSuite, DateTimeFormatterTest, testRFC1036); + CppUnit_addTest(pSuite, DateTimeFormatterTest, testASCTIME); + CppUnit_addTest(pSuite, DateTimeFormatterTest, testSORTABLE); + CppUnit_addTest(pSuite, DateTimeFormatterTest, testCustom); + CppUnit_addTest(pSuite, DateTimeFormatterTest, testTimespan); + + return pSuite; +} diff --git a/Foundation/testsuite/src/DateTimeFormatterTest.h b/Foundation/testsuite/src/DateTimeFormatterTest.h index 35f6680cc..fdedfeedd 100644 --- a/Foundation/testsuite/src/DateTimeFormatterTest.h +++ b/Foundation/testsuite/src/DateTimeFormatterTest.h @@ -1,69 +1,69 @@ -// -// DateTimeFormatterTest.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/DateTimeFormatterTest.h#1 $ -// -// Definition of the DateTimeFormatterTest class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 DateTimeFormatterTest_INCLUDED -#define DateTimeFormatterTest_INCLUDED - - -#include "Poco/Foundation.h" -#include "CppUnit/TestCase.h" - - -class DateTimeFormatterTest: public CppUnit::TestCase -{ -public: - DateTimeFormatterTest(const std::string& name); - ~DateTimeFormatterTest(); - - void testISO8601(); - void testRFC822(); - void testRFC1123(); - void testHTTP(); - void testRFC850(); - void testRFC1036(); - void testASCTIME(); - void testSORTABLE(); - void testCustom(); - void testTimespan(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // DateTimeFormatterTest_INCLUDED +// +// DateTimeFormatterTest.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/DateTimeFormatterTest.h#1 $ +// +// Definition of the DateTimeFormatterTest class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 DateTimeFormatterTest_INCLUDED +#define DateTimeFormatterTest_INCLUDED + + +#include "Poco/Foundation.h" +#include "CppUnit/TestCase.h" + + +class DateTimeFormatterTest: public CppUnit::TestCase +{ +public: + DateTimeFormatterTest(const std::string& name); + ~DateTimeFormatterTest(); + + void testISO8601(); + void testRFC822(); + void testRFC1123(); + void testHTTP(); + void testRFC850(); + void testRFC1036(); + void testASCTIME(); + void testSORTABLE(); + void testCustom(); + void testTimespan(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // DateTimeFormatterTest_INCLUDED diff --git a/Foundation/testsuite/src/DateTimeParserTest.cpp b/Foundation/testsuite/src/DateTimeParserTest.cpp index 580986b45..bc49c50c4 100644 --- a/Foundation/testsuite/src/DateTimeParserTest.cpp +++ b/Foundation/testsuite/src/DateTimeParserTest.cpp @@ -1,551 +1,551 @@ -// -// DateTimeParserTest.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/DateTimeParserTest.cpp#1 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "DateTimeParserTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/DateTimeParser.h" -#include "Poco/DateTimeFormat.h" -#include "Poco/DateTime.h" -#include "Poco/Timestamp.h" -#include "Poco/Exception.h" - - -using Poco::DateTime; -using Poco::DateTimeFormat; -using Poco::DateTimeParser; -using Poco::Timestamp; -using Poco::SyntaxException; - - -DateTimeParserTest::DateTimeParserTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -DateTimeParserTest::~DateTimeParserTest() -{ -} - - -void DateTimeParserTest::testISO8601() -{ - int tzd; - DateTime dt = DateTimeParser::parse(DateTimeFormat::ISO8601_FORMAT, "2005-01-08T12:30:00Z", tzd); - assert (dt.year() == 2005); - assert (dt.month() == 1); - assert (dt.day() == 8); - assert (dt.hour() == 12); - assert (dt.minute() == 30); - assert (dt.second() == 0); - assert (tzd == 0); - - dt = DateTimeParser::parse(DateTimeFormat::ISO8601_FORMAT, "2005-01-08T12:30:00+01:00", tzd); - assert (dt.year() == 2005); - assert (dt.month() == 1); - assert (dt.day() == 8); - assert (dt.hour() == 12); - assert (dt.minute() == 30); - assert (dt.second() == 0); - assert (tzd == 3600); - - dt = DateTimeParser::parse(DateTimeFormat::ISO8601_FORMAT, "2005-01-08T12:30:00-01:00", tzd); - assert (dt.year() == 2005); - assert (dt.month() == 1); - assert (dt.day() == 8); - assert (dt.hour() == 12); - assert (dt.minute() == 30); - assert (dt.second() == 0); - assert (tzd == -3600); - - dt = DateTimeParser::parse(DateTimeFormat::ISO8601_FORMAT, "2005-01-08T12:30:00", tzd); - assert (dt.year() == 2005); - assert (dt.month() == 1); - assert (dt.day() == 8); - assert (dt.hour() == 12); - assert (dt.minute() == 30); - assert (dt.second() == 0); - assert (tzd == 0); - - dt = DateTimeParser::parse(DateTimeFormat::ISO8601_FORMAT, "2005-01-08", tzd); - assert (dt.year() == 2005); - assert (dt.month() == 1); - assert (dt.day() == 8); - assert (dt.hour() == 0); - assert (dt.minute() == 0); - assert (dt.second() == 0); - assert (tzd == 0); -} - - -void DateTimeParserTest::testRFC822() -{ - int tzd; - DateTime dt = DateTimeParser::parse(DateTimeFormat::RFC822_FORMAT, "Sat, 8 Jan 05 12:30:00 GMT", tzd); - assert (dt.year() == 2005); - assert (dt.month() == 1); - assert (dt.day() == 8); - assert (dt.hour() == 12); - assert (dt.minute() == 30); - assert (dt.second() == 0); - assert (tzd == 0); - - dt = DateTimeParser::parse(DateTimeFormat::RFC822_FORMAT, "Sat, 8 Jan 05 12:30:00 +0100", tzd); - assert (dt.year() == 2005); - assert (dt.month() == 1); - assert (dt.day() == 8); - assert (dt.hour() == 12); - assert (dt.minute() == 30); - assert (dt.second() == 0); - assert (tzd == 3600); - - dt = DateTimeParser::parse(DateTimeFormat::RFC822_FORMAT, "Sat, 8 Jan 05 12:30:00 -0100", tzd); - assert (dt.year() == 2005); - assert (dt.month() == 1); - assert (dt.day() == 8); - assert (dt.hour() == 12); - assert (dt.minute() == 30); - assert (dt.second() == 0); - assert (tzd == -3600); - - dt = DateTimeParser::parse(DateTimeFormat::RFC822_FORMAT, "Tue, 18 Jan 05 12:30:00 CET", tzd); - assert (dt.year() == 2005); - assert (dt.month() == 1); - assert (dt.day() == 18); - assert (dt.hour() == 12); - assert (dt.minute() == 30); - assert (dt.second() == 0); - assert (tzd == 3600); - - dt = DateTimeParser::parse(DateTimeFormat::RFC822_FORMAT, "Wed, 12 Sep 73 02:01:12 CEST", tzd); - assert (dt.year() == 1973); - assert (dt.month() == 9); - assert (dt.day() == 12); - assert (dt.hour() == 2); - assert (dt.minute() == 1); - assert (dt.second() == 12); - assert (tzd == 7200); - - dt = DateTimeParser::parse(DateTimeFormat::RFC822_FORMAT, "12 Sep 73 02:01:12 CEST", tzd); - assert (dt.year() == 1973); - assert (dt.month() == 9); - assert (dt.day() == 12); - assert (dt.hour() == 2); - assert (dt.minute() == 1); - assert (dt.second() == 12); - assert (tzd == 7200); -} - - -void DateTimeParserTest::testRFC1123() -{ - int tzd; - DateTime dt = DateTimeParser::parse(DateTimeFormat::RFC1123_FORMAT, "Sat, 8 Jan 2005 12:30:00 GMT", tzd); - assert (dt.year() == 2005); - assert (dt.month() == 1); - assert (dt.day() == 8); - assert (dt.hour() == 12); - assert (dt.minute() == 30); - assert (dt.second() == 0); - assert (tzd == 0); - - dt = DateTimeParser::parse(DateTimeFormat::RFC1123_FORMAT, "Sat, 8 Jan 2005 12:30:00 +0100", tzd); - assert (dt.year() == 2005); - assert (dt.month() == 1); - assert (dt.day() == 8); - assert (dt.hour() == 12); - assert (dt.minute() == 30); - assert (dt.second() == 0); - assert (tzd == 3600); - - dt = DateTimeParser::parse(DateTimeFormat::RFC1123_FORMAT, "Sat, 8 Jan 2005 12:30:00 -0100", tzd); - assert (dt.year() == 2005); - assert (dt.month() == 1); - assert (dt.day() == 8); - assert (dt.hour() == 12); - assert (dt.minute() == 30); - assert (dt.second() == 0); - assert (tzd == -3600); - - dt = DateTimeParser::parse(DateTimeFormat::RFC1123_FORMAT, "Sun, 20 Jul 1969 16:17:30 EDT", tzd); - assert (dt.year() == 1969); - assert (dt.month() == 7); - assert (dt.day() == 20); - assert (dt.hour() == 16); - assert (dt.minute() == 17); - assert (dt.second() == 30); - assert (tzd == -14400); -} - - -void DateTimeParserTest::testHTTP() -{ - int tzd; - DateTime dt = DateTimeParser::parse(DateTimeFormat::HTTP_FORMAT, "Sat, 08 Jan 2005 12:30:00 GMT", tzd); - assert (dt.year() == 2005); - assert (dt.month() == 1); - assert (dt.day() == 8); - assert (dt.hour() == 12); - assert (dt.minute() == 30); - assert (dt.second() == 0); - assert (tzd == 0); - - dt = DateTimeParser::parse(DateTimeFormat::HTTP_FORMAT, "Sat, 08 Jan 2005 12:30:00 +0100", tzd); - assert (dt.year() == 2005); - assert (dt.month() == 1); - assert (dt.day() == 8); - assert (dt.hour() == 12); - assert (dt.minute() == 30); - assert (dt.second() == 0); - assert (tzd == 3600); - - dt = DateTimeParser::parse(DateTimeFormat::HTTP_FORMAT, "Sat, 08 Jan 2005 12:30:00 -0100", tzd); - assert (dt.year() == 2005); - assert (dt.month() == 1); - assert (dt.day() == 8); - assert (dt.hour() == 12); - assert (dt.minute() == 30); - assert (dt.second() == 0); - assert (tzd == -3600); -} - - -void DateTimeParserTest::testRFC850() -{ - int tzd; - DateTime dt = DateTimeParser::parse(DateTimeFormat::RFC850_FORMAT, "Saturday, 8-Jan-05 12:30:00 GMT", tzd); - assert (dt.year() == 2005); - assert (dt.month() == 1); - assert (dt.day() == 8); - assert (dt.hour() == 12); - assert (dt.minute() == 30); - assert (dt.second() == 0); - assert (tzd == 0); - - dt = DateTimeParser::parse(DateTimeFormat::RFC850_FORMAT, "Saturday, 8-Jan-05 12:30:00 +0100", tzd); - assert (dt.year() == 2005); - assert (dt.month() == 1); - assert (dt.day() == 8); - assert (dt.hour() == 12); - assert (dt.minute() == 30); - assert (dt.second() == 0); - assert (tzd == 3600); - - dt = DateTimeParser::parse(DateTimeFormat::RFC850_FORMAT, "Saturday, 8-Jan-05 12:30:00 -0100", tzd); - assert (dt.year() == 2005); - assert (dt.month() == 1); - assert (dt.day() == 8); - assert (dt.hour() == 12); - assert (dt.minute() == 30); - assert (dt.second() == 0); - assert (tzd == -3600); - - dt = DateTimeParser::parse(DateTimeFormat::RFC850_FORMAT, "Wed, 12-Sep-73 02:01:12 CEST", tzd); - assert (dt.year() == 1973); - assert (dt.month() == 9); - assert (dt.day() == 12); - assert (dt.hour() == 2); - assert (dt.minute() == 1); - assert (dt.second() == 12); - assert (tzd == 7200); -} - - -void DateTimeParserTest::testRFC1036() -{ - int tzd; - DateTime dt = DateTimeParser::parse(DateTimeFormat::RFC1036_FORMAT, "Saturday, 8 Jan 05 12:30:00 GMT", tzd); - assert (dt.year() == 2005); - assert (dt.month() == 1); - assert (dt.day() == 8); - assert (dt.hour() == 12); - assert (dt.minute() == 30); - assert (dt.second() == 0); - assert (tzd == 0); - - dt = DateTimeParser::parse(DateTimeFormat::RFC1036_FORMAT, "Saturday, 8 Jan 05 12:30:00 +0100", tzd); - assert (dt.year() == 2005); - assert (dt.month() == 1); - assert (dt.day() == 8); - assert (dt.hour() == 12); - assert (dt.minute() == 30); - assert (dt.second() == 0); - assert (tzd == 3600); - - dt = DateTimeParser::parse(DateTimeFormat::RFC1036_FORMAT, "Saturday, 8 Jan 05 12:30:00 -0100", tzd); - assert (dt.year() == 2005); - assert (dt.month() == 1); - assert (dt.day() == 8); - assert (dt.hour() == 12); - assert (dt.minute() == 30); - assert (dt.second() == 0); - assert (tzd == -3600); -} - - -void DateTimeParserTest::testASCTIME() -{ - int tzd; - DateTime dt = DateTimeParser::parse(DateTimeFormat::ASCTIME_FORMAT, "Sat Jan 8 12:30:00 2005", tzd); - assert (dt.year() == 2005); - assert (dt.month() == 1); - assert (dt.day() == 8); - assert (dt.hour() == 12); - assert (dt.minute() == 30); - assert (dt.second() == 0); - assert (tzd == 0); -} - - -void DateTimeParserTest::testSORTABLE() -{ - int tzd; - DateTime dt = DateTimeParser::parse(DateTimeFormat::SORTABLE_FORMAT, "2005-01-08 12:30:00", tzd); - assert (dt.year() == 2005); - assert (dt.month() == 1); - assert (dt.day() == 8); - assert (dt.hour() == 12); - assert (dt.minute() == 30); - assert (dt.second() == 0); - assert (tzd == 0); - - dt = DateTimeParser::parse(DateTimeFormat::SORTABLE_FORMAT, "2005-01-08", tzd); - assert (dt.year() == 2005); - assert (dt.month() == 1); - assert (dt.day() == 8); - assert (dt.hour() == 0); - assert (dt.minute() == 0); - assert (dt.second() == 0); - assert (tzd == 0); -} - - -void DateTimeParserTest::testCustom() -{ - int tzd; - DateTime dt = DateTimeParser::parse("%d-%b-%Y", "18-Jan-2005", tzd); - assert (dt.year() == 2005); - assert (dt.month() == 1); - assert (dt.day() == 18); - assert (dt.hour() == 0); - assert (dt.minute() == 0); - assert (dt.second() == 0); - assert (tzd == 0); - - dt = DateTimeParser::parse("%m/%d/%y", "01/18/05", tzd); - assert (dt.year() == 2005); - assert (dt.month() == 1); - assert (dt.day() == 18); - assert (dt.hour() == 0); - assert (dt.minute() == 0); - assert (dt.second() == 0); - assert (tzd == 0); - - dt = DateTimeParser::parse("%h:%M %a", "12:30 am", tzd); - assert (dt.hour() == 0); - assert (dt.minute() == 30); - assert (dt.second() == 0); - - dt = DateTimeParser::parse("%h:%M %a", "12:30 PM", tzd); - assert (dt.hour() == 12); - assert (dt.minute() == 30); - assert (dt.second() == 0); -} - - -void DateTimeParserTest::testGuess() -{ - int tzd; - DateTime dt = DateTimeParser::parse("2005-01-08T12:30:00Z", tzd); - assert (dt.year() == 2005); - assert (dt.month() == 1); - assert (dt.day() == 8); - assert (dt.hour() == 12); - assert (dt.minute() == 30); - assert (dt.second() == 0); - assert (tzd == 0); - - dt = DateTimeParser::parse("Sat, 8 Jan 05 12:30:00 +0100", tzd); - assert (dt.year() == 2005); - assert (dt.month() == 1); - assert (dt.day() == 8); - assert (dt.hour() == 12); - assert (dt.minute() == 30); - assert (dt.second() == 0); - assert (tzd == 3600); - - dt = DateTimeParser::parse("Sat Jan 8 12:30:00 2005", tzd); - assert (dt.year() == 2005); - assert (dt.month() == 1); - assert (dt.day() == 8); - assert (dt.hour() == 12); - assert (dt.minute() == 30); - assert (dt.second() == 0); - assert (tzd == 0); - - dt = DateTimeParser::parse("2005-01-08 12:30:00", tzd); - assert (dt.year() == 2005); - assert (dt.month() == 1); - assert (dt.day() == 8); - assert (dt.hour() == 12); - assert (dt.minute() == 30); - assert (dt.second() == 0); - assert (tzd == 0); - - dt = DateTimeParser::parse("2005-01-08", tzd); - assert (dt.year() == 2005); - assert (dt.month() == 1); - assert (dt.day() == 8); - assert (dt.hour() == 0); - assert (dt.minute() == 0); - assert (dt.second() == 0); - assert (tzd == 0); -} - - -void DateTimeParserTest::testParseMonth() -{ - std::string str = "January"; - std::string::const_iterator it = str.begin(); - int month = DateTimeParser::parseMonth(it, str.end()); - assert (month == 1); - str = "February"; - it = str.begin(); - month = DateTimeParser::parseMonth(it, str.end()); - assert (month == 2); - str = "December"; - it = str.begin(); - month = DateTimeParser::parseMonth(it, str.end()); - assert (month == 12); - str = "Jan"; - it = str.begin(); - month = DateTimeParser::parseMonth(it, str.end()); - assert (month == 1); - str = "Feb"; - it = str.begin(); - month = DateTimeParser::parseMonth(it, str.end()); - assert (month == 2); - str = "jan"; - it = str.begin(); - month = DateTimeParser::parseMonth(it, str.end()); - assert (month == 1); - str = "feb"; - it = str.begin(); - month = DateTimeParser::parseMonth(it, str.end()); - assert (month == 2); - - try - { - str = "ja"; - it = str.begin(); - month = DateTimeParser::parseMonth(it, str.end()); - fail("Not a valid month name - must throw"); - } - catch (SyntaxException&) - { - } -} - - -void DateTimeParserTest::testParseDayOfWeek() -{ - std::string str = "Sunday"; - std::string::const_iterator it = str.begin(); - int dow = DateTimeParser::parseDayOfWeek(it, str.end()); - assert (dow == 0); - str = "Monday"; - it = str.begin(); - dow = DateTimeParser::parseDayOfWeek(it, str.end()); - assert (dow == 1); - str = "Saturday"; - it = str.begin(); - dow = DateTimeParser::parseDayOfWeek(it, str.end()); - assert (dow == 6); - str = "Sun"; - it = str.begin(); - dow = DateTimeParser::parseDayOfWeek(it, str.end()); - assert (dow == 0); - str = "Mon"; - it = str.begin(); - dow = DateTimeParser::parseDayOfWeek(it, str.end()); - assert (dow == 1); - str = "sun"; - it = str.begin(); - dow = DateTimeParser::parseDayOfWeek(it, str.end()); - assert (dow == 0); - str = "mon"; - it = str.begin(); - dow = DateTimeParser::parseDayOfWeek(it, str.end()); - assert (dow == 1); - - try - { - str = "su"; - it = str.begin(); - dow = DateTimeParser::parseDayOfWeek(it, str.end()); - fail("Not a valid weekday name - must throw"); - } - catch (SyntaxException&) - { - } -} - - -void DateTimeParserTest::setUp() -{ -} - - -void DateTimeParserTest::tearDown() -{ -} - - -CppUnit::Test* DateTimeParserTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("DateTimeParserTest"); - - CppUnit_addTest(pSuite, DateTimeParserTest, testISO8601); - CppUnit_addTest(pSuite, DateTimeParserTest, testRFC822); - CppUnit_addTest(pSuite, DateTimeParserTest, testRFC1123); - CppUnit_addTest(pSuite, DateTimeParserTest, testHTTP); - CppUnit_addTest(pSuite, DateTimeParserTest, testRFC850); - CppUnit_addTest(pSuite, DateTimeParserTest, testRFC1036); - CppUnit_addTest(pSuite, DateTimeParserTest, testASCTIME); - CppUnit_addTest(pSuite, DateTimeParserTest, testSORTABLE); - CppUnit_addTest(pSuite, DateTimeParserTest, testCustom); - CppUnit_addTest(pSuite, DateTimeParserTest, testGuess); - CppUnit_addTest(pSuite, DateTimeParserTest, testParseMonth); - CppUnit_addTest(pSuite, DateTimeParserTest, testParseDayOfWeek); - - return pSuite; -} +// +// DateTimeParserTest.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/DateTimeParserTest.cpp#1 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "DateTimeParserTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/DateTimeParser.h" +#include "Poco/DateTimeFormat.h" +#include "Poco/DateTime.h" +#include "Poco/Timestamp.h" +#include "Poco/Exception.h" + + +using Poco::DateTime; +using Poco::DateTimeFormat; +using Poco::DateTimeParser; +using Poco::Timestamp; +using Poco::SyntaxException; + + +DateTimeParserTest::DateTimeParserTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +DateTimeParserTest::~DateTimeParserTest() +{ +} + + +void DateTimeParserTest::testISO8601() +{ + int tzd; + DateTime dt = DateTimeParser::parse(DateTimeFormat::ISO8601_FORMAT, "2005-01-08T12:30:00Z", tzd); + assert (dt.year() == 2005); + assert (dt.month() == 1); + assert (dt.day() == 8); + assert (dt.hour() == 12); + assert (dt.minute() == 30); + assert (dt.second() == 0); + assert (tzd == 0); + + dt = DateTimeParser::parse(DateTimeFormat::ISO8601_FORMAT, "2005-01-08T12:30:00+01:00", tzd); + assert (dt.year() == 2005); + assert (dt.month() == 1); + assert (dt.day() == 8); + assert (dt.hour() == 12); + assert (dt.minute() == 30); + assert (dt.second() == 0); + assert (tzd == 3600); + + dt = DateTimeParser::parse(DateTimeFormat::ISO8601_FORMAT, "2005-01-08T12:30:00-01:00", tzd); + assert (dt.year() == 2005); + assert (dt.month() == 1); + assert (dt.day() == 8); + assert (dt.hour() == 12); + assert (dt.minute() == 30); + assert (dt.second() == 0); + assert (tzd == -3600); + + dt = DateTimeParser::parse(DateTimeFormat::ISO8601_FORMAT, "2005-01-08T12:30:00", tzd); + assert (dt.year() == 2005); + assert (dt.month() == 1); + assert (dt.day() == 8); + assert (dt.hour() == 12); + assert (dt.minute() == 30); + assert (dt.second() == 0); + assert (tzd == 0); + + dt = DateTimeParser::parse(DateTimeFormat::ISO8601_FORMAT, "2005-01-08", tzd); + assert (dt.year() == 2005); + assert (dt.month() == 1); + assert (dt.day() == 8); + assert (dt.hour() == 0); + assert (dt.minute() == 0); + assert (dt.second() == 0); + assert (tzd == 0); +} + + +void DateTimeParserTest::testRFC822() +{ + int tzd; + DateTime dt = DateTimeParser::parse(DateTimeFormat::RFC822_FORMAT, "Sat, 8 Jan 05 12:30:00 GMT", tzd); + assert (dt.year() == 2005); + assert (dt.month() == 1); + assert (dt.day() == 8); + assert (dt.hour() == 12); + assert (dt.minute() == 30); + assert (dt.second() == 0); + assert (tzd == 0); + + dt = DateTimeParser::parse(DateTimeFormat::RFC822_FORMAT, "Sat, 8 Jan 05 12:30:00 +0100", tzd); + assert (dt.year() == 2005); + assert (dt.month() == 1); + assert (dt.day() == 8); + assert (dt.hour() == 12); + assert (dt.minute() == 30); + assert (dt.second() == 0); + assert (tzd == 3600); + + dt = DateTimeParser::parse(DateTimeFormat::RFC822_FORMAT, "Sat, 8 Jan 05 12:30:00 -0100", tzd); + assert (dt.year() == 2005); + assert (dt.month() == 1); + assert (dt.day() == 8); + assert (dt.hour() == 12); + assert (dt.minute() == 30); + assert (dt.second() == 0); + assert (tzd == -3600); + + dt = DateTimeParser::parse(DateTimeFormat::RFC822_FORMAT, "Tue, 18 Jan 05 12:30:00 CET", tzd); + assert (dt.year() == 2005); + assert (dt.month() == 1); + assert (dt.day() == 18); + assert (dt.hour() == 12); + assert (dt.minute() == 30); + assert (dt.second() == 0); + assert (tzd == 3600); + + dt = DateTimeParser::parse(DateTimeFormat::RFC822_FORMAT, "Wed, 12 Sep 73 02:01:12 CEST", tzd); + assert (dt.year() == 1973); + assert (dt.month() == 9); + assert (dt.day() == 12); + assert (dt.hour() == 2); + assert (dt.minute() == 1); + assert (dt.second() == 12); + assert (tzd == 7200); + + dt = DateTimeParser::parse(DateTimeFormat::RFC822_FORMAT, "12 Sep 73 02:01:12 CEST", tzd); + assert (dt.year() == 1973); + assert (dt.month() == 9); + assert (dt.day() == 12); + assert (dt.hour() == 2); + assert (dt.minute() == 1); + assert (dt.second() == 12); + assert (tzd == 7200); +} + + +void DateTimeParserTest::testRFC1123() +{ + int tzd; + DateTime dt = DateTimeParser::parse(DateTimeFormat::RFC1123_FORMAT, "Sat, 8 Jan 2005 12:30:00 GMT", tzd); + assert (dt.year() == 2005); + assert (dt.month() == 1); + assert (dt.day() == 8); + assert (dt.hour() == 12); + assert (dt.minute() == 30); + assert (dt.second() == 0); + assert (tzd == 0); + + dt = DateTimeParser::parse(DateTimeFormat::RFC1123_FORMAT, "Sat, 8 Jan 2005 12:30:00 +0100", tzd); + assert (dt.year() == 2005); + assert (dt.month() == 1); + assert (dt.day() == 8); + assert (dt.hour() == 12); + assert (dt.minute() == 30); + assert (dt.second() == 0); + assert (tzd == 3600); + + dt = DateTimeParser::parse(DateTimeFormat::RFC1123_FORMAT, "Sat, 8 Jan 2005 12:30:00 -0100", tzd); + assert (dt.year() == 2005); + assert (dt.month() == 1); + assert (dt.day() == 8); + assert (dt.hour() == 12); + assert (dt.minute() == 30); + assert (dt.second() == 0); + assert (tzd == -3600); + + dt = DateTimeParser::parse(DateTimeFormat::RFC1123_FORMAT, "Sun, 20 Jul 1969 16:17:30 EDT", tzd); + assert (dt.year() == 1969); + assert (dt.month() == 7); + assert (dt.day() == 20); + assert (dt.hour() == 16); + assert (dt.minute() == 17); + assert (dt.second() == 30); + assert (tzd == -14400); +} + + +void DateTimeParserTest::testHTTP() +{ + int tzd; + DateTime dt = DateTimeParser::parse(DateTimeFormat::HTTP_FORMAT, "Sat, 08 Jan 2005 12:30:00 GMT", tzd); + assert (dt.year() == 2005); + assert (dt.month() == 1); + assert (dt.day() == 8); + assert (dt.hour() == 12); + assert (dt.minute() == 30); + assert (dt.second() == 0); + assert (tzd == 0); + + dt = DateTimeParser::parse(DateTimeFormat::HTTP_FORMAT, "Sat, 08 Jan 2005 12:30:00 +0100", tzd); + assert (dt.year() == 2005); + assert (dt.month() == 1); + assert (dt.day() == 8); + assert (dt.hour() == 12); + assert (dt.minute() == 30); + assert (dt.second() == 0); + assert (tzd == 3600); + + dt = DateTimeParser::parse(DateTimeFormat::HTTP_FORMAT, "Sat, 08 Jan 2005 12:30:00 -0100", tzd); + assert (dt.year() == 2005); + assert (dt.month() == 1); + assert (dt.day() == 8); + assert (dt.hour() == 12); + assert (dt.minute() == 30); + assert (dt.second() == 0); + assert (tzd == -3600); +} + + +void DateTimeParserTest::testRFC850() +{ + int tzd; + DateTime dt = DateTimeParser::parse(DateTimeFormat::RFC850_FORMAT, "Saturday, 8-Jan-05 12:30:00 GMT", tzd); + assert (dt.year() == 2005); + assert (dt.month() == 1); + assert (dt.day() == 8); + assert (dt.hour() == 12); + assert (dt.minute() == 30); + assert (dt.second() == 0); + assert (tzd == 0); + + dt = DateTimeParser::parse(DateTimeFormat::RFC850_FORMAT, "Saturday, 8-Jan-05 12:30:00 +0100", tzd); + assert (dt.year() == 2005); + assert (dt.month() == 1); + assert (dt.day() == 8); + assert (dt.hour() == 12); + assert (dt.minute() == 30); + assert (dt.second() == 0); + assert (tzd == 3600); + + dt = DateTimeParser::parse(DateTimeFormat::RFC850_FORMAT, "Saturday, 8-Jan-05 12:30:00 -0100", tzd); + assert (dt.year() == 2005); + assert (dt.month() == 1); + assert (dt.day() == 8); + assert (dt.hour() == 12); + assert (dt.minute() == 30); + assert (dt.second() == 0); + assert (tzd == -3600); + + dt = DateTimeParser::parse(DateTimeFormat::RFC850_FORMAT, "Wed, 12-Sep-73 02:01:12 CEST", tzd); + assert (dt.year() == 1973); + assert (dt.month() == 9); + assert (dt.day() == 12); + assert (dt.hour() == 2); + assert (dt.minute() == 1); + assert (dt.second() == 12); + assert (tzd == 7200); +} + + +void DateTimeParserTest::testRFC1036() +{ + int tzd; + DateTime dt = DateTimeParser::parse(DateTimeFormat::RFC1036_FORMAT, "Saturday, 8 Jan 05 12:30:00 GMT", tzd); + assert (dt.year() == 2005); + assert (dt.month() == 1); + assert (dt.day() == 8); + assert (dt.hour() == 12); + assert (dt.minute() == 30); + assert (dt.second() == 0); + assert (tzd == 0); + + dt = DateTimeParser::parse(DateTimeFormat::RFC1036_FORMAT, "Saturday, 8 Jan 05 12:30:00 +0100", tzd); + assert (dt.year() == 2005); + assert (dt.month() == 1); + assert (dt.day() == 8); + assert (dt.hour() == 12); + assert (dt.minute() == 30); + assert (dt.second() == 0); + assert (tzd == 3600); + + dt = DateTimeParser::parse(DateTimeFormat::RFC1036_FORMAT, "Saturday, 8 Jan 05 12:30:00 -0100", tzd); + assert (dt.year() == 2005); + assert (dt.month() == 1); + assert (dt.day() == 8); + assert (dt.hour() == 12); + assert (dt.minute() == 30); + assert (dt.second() == 0); + assert (tzd == -3600); +} + + +void DateTimeParserTest::testASCTIME() +{ + int tzd; + DateTime dt = DateTimeParser::parse(DateTimeFormat::ASCTIME_FORMAT, "Sat Jan 8 12:30:00 2005", tzd); + assert (dt.year() == 2005); + assert (dt.month() == 1); + assert (dt.day() == 8); + assert (dt.hour() == 12); + assert (dt.minute() == 30); + assert (dt.second() == 0); + assert (tzd == 0); +} + + +void DateTimeParserTest::testSORTABLE() +{ + int tzd; + DateTime dt = DateTimeParser::parse(DateTimeFormat::SORTABLE_FORMAT, "2005-01-08 12:30:00", tzd); + assert (dt.year() == 2005); + assert (dt.month() == 1); + assert (dt.day() == 8); + assert (dt.hour() == 12); + assert (dt.minute() == 30); + assert (dt.second() == 0); + assert (tzd == 0); + + dt = DateTimeParser::parse(DateTimeFormat::SORTABLE_FORMAT, "2005-01-08", tzd); + assert (dt.year() == 2005); + assert (dt.month() == 1); + assert (dt.day() == 8); + assert (dt.hour() == 0); + assert (dt.minute() == 0); + assert (dt.second() == 0); + assert (tzd == 0); +} + + +void DateTimeParserTest::testCustom() +{ + int tzd; + DateTime dt = DateTimeParser::parse("%d-%b-%Y", "18-Jan-2005", tzd); + assert (dt.year() == 2005); + assert (dt.month() == 1); + assert (dt.day() == 18); + assert (dt.hour() == 0); + assert (dt.minute() == 0); + assert (dt.second() == 0); + assert (tzd == 0); + + dt = DateTimeParser::parse("%m/%d/%y", "01/18/05", tzd); + assert (dt.year() == 2005); + assert (dt.month() == 1); + assert (dt.day() == 18); + assert (dt.hour() == 0); + assert (dt.minute() == 0); + assert (dt.second() == 0); + assert (tzd == 0); + + dt = DateTimeParser::parse("%h:%M %a", "12:30 am", tzd); + assert (dt.hour() == 0); + assert (dt.minute() == 30); + assert (dt.second() == 0); + + dt = DateTimeParser::parse("%h:%M %a", "12:30 PM", tzd); + assert (dt.hour() == 12); + assert (dt.minute() == 30); + assert (dt.second() == 0); +} + + +void DateTimeParserTest::testGuess() +{ + int tzd; + DateTime dt = DateTimeParser::parse("2005-01-08T12:30:00Z", tzd); + assert (dt.year() == 2005); + assert (dt.month() == 1); + assert (dt.day() == 8); + assert (dt.hour() == 12); + assert (dt.minute() == 30); + assert (dt.second() == 0); + assert (tzd == 0); + + dt = DateTimeParser::parse("Sat, 8 Jan 05 12:30:00 +0100", tzd); + assert (dt.year() == 2005); + assert (dt.month() == 1); + assert (dt.day() == 8); + assert (dt.hour() == 12); + assert (dt.minute() == 30); + assert (dt.second() == 0); + assert (tzd == 3600); + + dt = DateTimeParser::parse("Sat Jan 8 12:30:00 2005", tzd); + assert (dt.year() == 2005); + assert (dt.month() == 1); + assert (dt.day() == 8); + assert (dt.hour() == 12); + assert (dt.minute() == 30); + assert (dt.second() == 0); + assert (tzd == 0); + + dt = DateTimeParser::parse("2005-01-08 12:30:00", tzd); + assert (dt.year() == 2005); + assert (dt.month() == 1); + assert (dt.day() == 8); + assert (dt.hour() == 12); + assert (dt.minute() == 30); + assert (dt.second() == 0); + assert (tzd == 0); + + dt = DateTimeParser::parse("2005-01-08", tzd); + assert (dt.year() == 2005); + assert (dt.month() == 1); + assert (dt.day() == 8); + assert (dt.hour() == 0); + assert (dt.minute() == 0); + assert (dt.second() == 0); + assert (tzd == 0); +} + + +void DateTimeParserTest::testParseMonth() +{ + std::string str = "January"; + std::string::const_iterator it = str.begin(); + int month = DateTimeParser::parseMonth(it, str.end()); + assert (month == 1); + str = "February"; + it = str.begin(); + month = DateTimeParser::parseMonth(it, str.end()); + assert (month == 2); + str = "December"; + it = str.begin(); + month = DateTimeParser::parseMonth(it, str.end()); + assert (month == 12); + str = "Jan"; + it = str.begin(); + month = DateTimeParser::parseMonth(it, str.end()); + assert (month == 1); + str = "Feb"; + it = str.begin(); + month = DateTimeParser::parseMonth(it, str.end()); + assert (month == 2); + str = "jan"; + it = str.begin(); + month = DateTimeParser::parseMonth(it, str.end()); + assert (month == 1); + str = "feb"; + it = str.begin(); + month = DateTimeParser::parseMonth(it, str.end()); + assert (month == 2); + + try + { + str = "ja"; + it = str.begin(); + month = DateTimeParser::parseMonth(it, str.end()); + fail("Not a valid month name - must throw"); + } + catch (SyntaxException&) + { + } +} + + +void DateTimeParserTest::testParseDayOfWeek() +{ + std::string str = "Sunday"; + std::string::const_iterator it = str.begin(); + int dow = DateTimeParser::parseDayOfWeek(it, str.end()); + assert (dow == 0); + str = "Monday"; + it = str.begin(); + dow = DateTimeParser::parseDayOfWeek(it, str.end()); + assert (dow == 1); + str = "Saturday"; + it = str.begin(); + dow = DateTimeParser::parseDayOfWeek(it, str.end()); + assert (dow == 6); + str = "Sun"; + it = str.begin(); + dow = DateTimeParser::parseDayOfWeek(it, str.end()); + assert (dow == 0); + str = "Mon"; + it = str.begin(); + dow = DateTimeParser::parseDayOfWeek(it, str.end()); + assert (dow == 1); + str = "sun"; + it = str.begin(); + dow = DateTimeParser::parseDayOfWeek(it, str.end()); + assert (dow == 0); + str = "mon"; + it = str.begin(); + dow = DateTimeParser::parseDayOfWeek(it, str.end()); + assert (dow == 1); + + try + { + str = "su"; + it = str.begin(); + dow = DateTimeParser::parseDayOfWeek(it, str.end()); + fail("Not a valid weekday name - must throw"); + } + catch (SyntaxException&) + { + } +} + + +void DateTimeParserTest::setUp() +{ +} + + +void DateTimeParserTest::tearDown() +{ +} + + +CppUnit::Test* DateTimeParserTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("DateTimeParserTest"); + + CppUnit_addTest(pSuite, DateTimeParserTest, testISO8601); + CppUnit_addTest(pSuite, DateTimeParserTest, testRFC822); + CppUnit_addTest(pSuite, DateTimeParserTest, testRFC1123); + CppUnit_addTest(pSuite, DateTimeParserTest, testHTTP); + CppUnit_addTest(pSuite, DateTimeParserTest, testRFC850); + CppUnit_addTest(pSuite, DateTimeParserTest, testRFC1036); + CppUnit_addTest(pSuite, DateTimeParserTest, testASCTIME); + CppUnit_addTest(pSuite, DateTimeParserTest, testSORTABLE); + CppUnit_addTest(pSuite, DateTimeParserTest, testCustom); + CppUnit_addTest(pSuite, DateTimeParserTest, testGuess); + CppUnit_addTest(pSuite, DateTimeParserTest, testParseMonth); + CppUnit_addTest(pSuite, DateTimeParserTest, testParseDayOfWeek); + + return pSuite; +} diff --git a/Foundation/testsuite/src/DateTimeParserTest.h b/Foundation/testsuite/src/DateTimeParserTest.h index c7a1ad731..80459d9c0 100644 --- a/Foundation/testsuite/src/DateTimeParserTest.h +++ b/Foundation/testsuite/src/DateTimeParserTest.h @@ -1,71 +1,71 @@ -// -// DateTimeParserTest.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/DateTimeParserTest.h#1 $ -// -// Definition of the DateTimeParserTest class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 DateTimeParserTest_INCLUDED -#define DateTimeParserTest_INCLUDED - - -#include "Poco/Foundation.h" -#include "CppUnit/TestCase.h" - - -class DateTimeParserTest: public CppUnit::TestCase -{ -public: - DateTimeParserTest(const std::string& name); - ~DateTimeParserTest(); - - void testISO8601(); - void testRFC822(); - void testRFC1123(); - void testHTTP(); - void testRFC850(); - void testRFC1036(); - void testASCTIME(); - void testSORTABLE(); - void testCustom(); - void testGuess(); - void testParseMonth(); - void testParseDayOfWeek(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // DateTimeParserTest_INCLUDED +// +// DateTimeParserTest.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/DateTimeParserTest.h#1 $ +// +// Definition of the DateTimeParserTest class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 DateTimeParserTest_INCLUDED +#define DateTimeParserTest_INCLUDED + + +#include "Poco/Foundation.h" +#include "CppUnit/TestCase.h" + + +class DateTimeParserTest: public CppUnit::TestCase +{ +public: + DateTimeParserTest(const std::string& name); + ~DateTimeParserTest(); + + void testISO8601(); + void testRFC822(); + void testRFC1123(); + void testHTTP(); + void testRFC850(); + void testRFC1036(); + void testASCTIME(); + void testSORTABLE(); + void testCustom(); + void testGuess(); + void testParseMonth(); + void testParseDayOfWeek(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // DateTimeParserTest_INCLUDED diff --git a/Foundation/testsuite/src/DateTimeTest.cpp b/Foundation/testsuite/src/DateTimeTest.cpp index e0e7ab204..7d37cab31 100644 --- a/Foundation/testsuite/src/DateTimeTest.cpp +++ b/Foundation/testsuite/src/DateTimeTest.cpp @@ -1,868 +1,868 @@ -// -// DateTimeTest.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/DateTimeTest.cpp#2 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "DateTimeTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/DateTime.h" -#include "Poco/Timestamp.h" -#include "Poco/Timespan.h" -#include "Poco/Exception.h" - - -using Poco::Timestamp; -using Poco::DateTime; -using Poco::Timespan; -using Poco::AssertionViolationException; - - -DateTimeTest::DateTimeTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -DateTimeTest::~DateTimeTest() -{ -} - - -void DateTimeTest::testTimestamp() -{ - Timestamp ts(0); // Unix epoch 1970-01-01 00:00:00 Thursday - DateTime dt(ts); - assert (dt.year() == 1970); - assert (dt.month() == 1); - assert (dt.day() == 1); - assert (dt.hour() == 0); - assert (dt.minute() == 0); - assert (dt.second() == 0); - assert (dt.millisecond() == 0); - assert (dt.dayOfWeek() == 4); - assert (dt.julianDay() == 2440587.5); - assert (dt.timestamp() == 0); - - ts = Timestamp::fromEpochTime(1000000000); - dt = ts; // 2001-09-09 01:46:40 Sunday - assert (dt.year() == 2001); - assert (dt.month() == 9); - assert (dt.day() == 9); - assert (dt.hour() == 1); - assert (dt.minute() == 46); - assert (dt.second() == 40); - assert (dt.millisecond() == 0); - assert (dt.dayOfWeek() == 0); - assert (dt.timestamp().epochTime() == 1000000000); - assertEqualDelta (dt.julianDay(), 2452161.574074, 0.000001); -} - - -void DateTimeTest::testJulian() -{ - DateTime dt(2440587.5); // unix epoch as Julian day - assert (dt.year() == 1970); - assert (dt.month() == 1); - assert (dt.day() == 1); - assert (dt.hour() == 0); - assert (dt.minute() == 0); - assert (dt.second() == 0); - assert (dt.millisecond() == 0); - assert (dt.dayOfWeek() == 4); - assert (dt.julianDay() == 2440587.5); - assert (dt.timestamp() == 0); - - dt = 2299160.5; // 1582-10-15 00:00:00 (first day of Gregorian reform, UTC base) - assert (dt.year() == 1582); - assert (dt.month() == 10); - assert (dt.day() == 15); - assert (dt.hour() == 0); - assert (dt.minute() == 0); - assert (dt.second() == 0); - assert (dt.millisecond() == 0); - assert (dt.dayOfWeek() == 5); - assert (dt.julianDay() == 2299160.5); - - dt = 0.0; // -4713-11-24 12:00:00 (Gregorian date of Julian day reference) - assert (dt.year() == -4713); - assert (dt.month() == 11); - assert (dt.day() == 24); - assert (dt.hour() == 12); - assert (dt.minute() == 0); - assert (dt.second() == 0); - assert (dt.millisecond() == 0); - assert (dt.dayOfWeek() == 1); - assert (dt.julianDay() == 0); - - // Test that we can represent down to the microsecond. - dt = DateTime(2010, 1, 31, 17, 30, 15, 800, 3); - - assert (dt.year() == 2010); - assert (dt.month() == 1); - assert (dt.day() == 31); - assert (dt.hour() == 17); - assert (dt.minute() == 30); - assert (dt.second() == 15); - assert (dt.millisecond() == 800); - assert (dt.microsecond() == 3); -} - - -void DateTimeTest::testGregorian() -{ - DateTime dt(1970, 1, 1); - assert (dt.year() == 1970); - assert (dt.month() == 1); - assert (dt.day() == 1); - assert (dt.hour() == 0); - assert (dt.minute() == 0); - assert (dt.second() == 0); - assert (dt.millisecond() == 0); - assert (dt.dayOfWeek() == 4); - assert (dt.julianDay() == 2440587.5); - assert (dt.timestamp() == 0); - - dt.assign(2001, 9, 9, 1, 46, 40); - assert (dt.year() == 2001); - assert (dt.month() == 9); - assert (dt.day() == 9); - assert (dt.hour() == 1); - assert (dt.minute() == 46); - assert (dt.second() == 40); - assert (dt.millisecond() == 0); - assert (dt.dayOfWeek() == 0); - assert (dt.timestamp().epochTime() == 1000000000); - assertEqualDelta (dt.julianDay(), 2452161.574074, 0.000001); -} - - -void DateTimeTest::testConversions() -{ - DateTime dt1(2005, 1, 28, 14, 24, 44, 234); - Timestamp ts1 = dt1.timestamp(); - DateTime dt2(ts1); - Timestamp ts2 = dt2.timestamp(); - DateTime dt3; - dt3 = dt1; - Timestamp ts3 = dt3.timestamp(); - DateTime dt4(dt2); - Timestamp ts4 = dt4.timestamp(); - - assert (ts1 == ts2); - assert (ts2 == ts3); - assert (ts3 == ts4); - - assert (dt2.year() == 2005); - assert (dt2.month() == 1); - assert (dt2.day() == 28); - assert (dt2.hour() == 14); - assert (dt2.minute() == 24); - assert (dt2.second() == 44); - assert (dt2.millisecond() == 234); - assert (dt2.dayOfWeek() == 5); -} - - -void DateTimeTest::testStatics() -{ - assert (DateTime::isLeapYear(1984)); - assert (DateTime::isLeapYear(1988)); - assert (DateTime::isLeapYear(1992)); - assert (DateTime::isLeapYear(1996)); - assert (DateTime::isLeapYear(2000)); - assert (DateTime::isLeapYear(2400)); - assert (!DateTime::isLeapYear(1995)); - assert (!DateTime::isLeapYear(1998)); - assert (!DateTime::isLeapYear(2001)); - assert (!DateTime::isLeapYear(1800)); - assert (!DateTime::isLeapYear(1900)); - - assert (DateTime::daysOfMonth(2000, 1) == 31); - assert (DateTime::daysOfMonth(2000, 2) == 29); - assert (DateTime::daysOfMonth(1999, 2) == 28); -} - - -void DateTimeTest::testCalcs() -{ - DateTime dt1(2005, 1, 1); - assert (dt1.dayOfYear() == 1); - assert (dt1.week(DateTime::MONDAY) == 0); - dt1.assign(2005, 1, 3); - assert (dt1.dayOfYear() == 3); - assert (dt1.week(DateTime::MONDAY) == 1); - dt1.assign(2005, 1, 9); - assert (dt1.dayOfYear() == 9); - assert (dt1.week(DateTime::MONDAY) == 1); - dt1.assign(2005, 1, 10); - assert (dt1.dayOfYear() == 10); - assert (dt1.week(DateTime::MONDAY) == 2); - dt1.assign(2005, 2, 1); - assert (dt1.dayOfYear() == 32); - assert (dt1.week(DateTime::MONDAY) == 5); - dt1.assign(2005, 12, 31); - assert (dt1.week(DateTime::MONDAY) == 52); - dt1.assign(2007, 1, 1); - assert (dt1.week(DateTime::MONDAY) == 1); - dt1.assign(2007, 12, 31); - assert (dt1.week(DateTime::MONDAY) == 53); - - // Jan 1 is Mon - dt1.assign(2001, 1, 1); - assert (dt1.week() == 1); - dt1.assign(2001, 1, 7); - assert (dt1.week() == 1); - dt1.assign(2001, 1, 8); - assert (dt1.week() == 2); - dt1.assign(2001, 1, 21); - assert (dt1.week() == 3); - dt1.assign(2001, 1, 22); - assert (dt1.week() == 4); - - // Jan 1 is Tue - dt1.assign(2002, 1, 1); - assert (dt1.week() == 1); - dt1.assign(2002, 1, 6); - assert (dt1.week() == 1); - dt1.assign(2002, 1, 7); - assert (dt1.week() == 2); - dt1.assign(2002, 1, 20); - assert (dt1.week() == 3); - dt1.assign(2002, 1, 21); - assert (dt1.week() == 4); - - // Jan 1 is Wed - dt1.assign(2003, 1, 1); - assert (dt1.week() == 1); - dt1.assign(2003, 1, 5); - assert (dt1.week() == 1); - dt1.assign(2003, 1, 6); - assert (dt1.week() == 2); - dt1.assign(2003, 1, 19); - assert (dt1.week() == 3); - dt1.assign(2003, 1, 20); - assert (dt1.week() == 4); - - // Jan 1 is Thu - dt1.assign(2004, 1, 1); - assert (dt1.week() == 1); - dt1.assign(2004, 1, 4); - assert (dt1.week() == 1); - dt1.assign(2004, 1, 5); - assert (dt1.week() == 2); - dt1.assign(2004, 1, 18); - assert (dt1.week() == 3); - dt1.assign(2004, 1, 19); - assert (dt1.week() == 4); - - // Jan 1 is Fri - dt1.assign(1999, 1, 1); - assert (dt1.week() == 0); - dt1.assign(1999, 1, 3); - assert (dt1.week() == 0); - dt1.assign(1999, 1, 4); - assert (dt1.week() == 1); - dt1.assign(1999, 1, 17); - assert (dt1.week() == 2); - dt1.assign(1999, 1, 18); - assert (dt1.week() == 3); - - // Jan 1 is Sat - dt1.assign(2000, 1, 1); - assert (dt1.week() == 0); - dt1.assign(2000, 1, 2); - assert (dt1.week() == 0); - dt1.assign(2000, 1, 3); - assert (dt1.week() == 1); - dt1.assign(2000, 1, 16); - assert (dt1.week() == 2); - dt1.assign(2000, 1, 17); - assert (dt1.week() == 3); - - // Jan 1 is Sun - dt1.assign(1995, 1, 1); - assert (dt1.week() == 0); - dt1.assign(1995, 1, 2); - assert (dt1.week() == 1); - dt1.assign(1995, 1, 3); - assert (dt1.week() == 1); - dt1.assign(1995, 1, 15); - assert (dt1.week() == 2); - dt1.assign(1995, 1, 16); - assert (dt1.week() == 3); -} - - -void DateTimeTest::testAMPM() -{ - DateTime dt1(2005, 1, 1, 0, 15, 30); - assert (dt1.isAM()); - assert (!dt1.isPM()); - assert (dt1.hourAMPM() == 12); - - dt1.assign(2005, 1, 1, 12, 15, 30); - assert (!dt1.isAM()); - assert (dt1.isPM()); - assert (dt1.hourAMPM() == 12); - - dt1.assign(2005, 1, 1, 13, 15, 30); - assert (!dt1.isAM()); - assert (dt1.isPM()); - assert (dt1.hourAMPM() == 1); -} - - -void DateTimeTest::testRelational() -{ - DateTime dt1(2005, 1, 1, 0, 15, 30); - DateTime dt2(2005, 1, 2, 0, 15, 30); - DateTime dt3(dt1); - - assert (dt1 < dt2); - assert (dt1 <= dt2); - assert (dt2 > dt1); - assert (dt2 >= dt1); - assert (dt1 != dt2); - assert (!(dt1 == dt2)); - - assert (dt1 == dt3); - assert (!(dt1 != dt3)); - assert (dt1 >= dt3); - assert (dt1 <= dt3); - assert (!(dt1 > dt3)); - assert (!(dt1 < dt3)); - - static const struct - { - int year; - int month; - int day; - } values[] = - { - { 1, 1, 1 }, - { 10, 4, 5 }, - { 100, 6, 7 }, - { 1000, 8, 9 }, - { 2000, 1, 31 }, - { 2002, 7, 4 }, - { 2002, 12, 31 }, - { 2003, 1, 1 }, - { 2003, 1, 2 }, - { 2003, 8, 5 }, - { 2003, 8, 6 }, - { 2003, 8, 7 }, - { 2004, 9, 3 }, - { 2004, 9, 4 }, - }; - - const int num_values = sizeof values / sizeof *values; - for (int i = 0; i < num_values; ++i) - { - DateTime v; - const DateTime& V = v; - v.assign(values[i].year, values[i].month, values[i].day); - for (int j = 0; j < num_values; ++j) - { - DateTime u; - const DateTime& U = u; - u.assign(values[j].year, values[j].month, values[j].day); - - loop_2_assert(i, j, j < i == U < V); - loop_2_assert(i, j, j <= i == U <= V); - loop_2_assert(i, j, j >= i == U >= V); - loop_2_assert(i, j, j > i == U > V); - } - } -} - - -void DateTimeTest::testArithmetics() -{ - DateTime dt1(2005, 1, 1, 0, 15, 30); - DateTime dt2(2005, 1, 2, 0, 15, 30); - - Timespan s = dt2 - dt1; - assert (s.days() == 1); - - DateTime dt3 = dt1 + s; - assert (dt3 == dt2); - - dt3 -= s; - assert (dt3 == dt1); - dt1 += s; - assert (dt1 == dt2); - - static const struct - { - int lineNum; // source line number - int year1; // operand/result date1 year - int month1; // operand/result date1 month - unsigned int day1; // operand/result date1 day - int numDays; // operand/result 'int' number of days - int year2; // operand/result date2 year - int month2; // operand/result date2 month - unsigned int day2; // operand/result date2 day - } data[] = - { - // - - - -first- - - - - - - second - - - - //line no. year month day numDays year month day - //------- ----- ----- ----- ------- ----- ----- ----- - { __LINE__, 1, 1, 1, 1, 1, 1, 2 }, - { __LINE__, 10, 2, 28, 1, 10, 3, 1 }, - { __LINE__, 100, 3, 31, 2, 100, 4, 2 }, - { __LINE__, 1000, 4, 30, 4, 1000, 5, 4 }, - { __LINE__, 1000, 6, 1, -31, 1000, 5, 1 }, - { __LINE__, 1001, 1, 1, -365, 1000, 1, 1 }, - { __LINE__, 1100, 5, 31, 30, 1100, 6, 30 }, - { __LINE__, 1200, 6, 30, 32, 1200, 8, 1 }, - { __LINE__, 1996, 2, 28, 367, 1997, 3, 1 }, - { __LINE__, 1997, 2, 28, 366, 1998, 3, 1 }, - { __LINE__, 1998, 2, 28, 365, 1999, 2, 28 }, - { __LINE__, 1999, 2, 28, 364, 2000, 2, 27 }, - { __LINE__, 1999, 2, 28, 1096, 2002, 2, 28 }, - { __LINE__, 2002, 2, 28, -1096, 1999, 2, 28 }, - }; - - const int num_data = sizeof data / sizeof *data; - for (int di = 0; di < num_data; ++di) - { - const int line = data[di].lineNum; - const int num_days = data[di].numDays; - DateTime x = DateTime(data[di].year1, data[di].month1, data[di].day1); - const DateTime& X = x; - x += Timespan(num_days, 0, 0, 0, 0); - loop_1_assert(line, data[di].year2 == X.year()); - loop_1_assert(line, data[di].month2 == X.month()); - loop_1_assert(line, data[di].day2 == X.day()); - } -} - -void DateTimeTest::testIncrementDecrement() -{ - static const struct - { - int lineNum; // source line number - int year1; // (first) date year - int month1; // (first) date month - unsigned int day1; // (first) date day - int year2; // (second) date year - int month2; // (second) date month - unsigned int day2; // (second) date day - } data[] = - { - // - - - -first- - - - - - - second - - - - //line no. year month day year month day - //------- ----- ----- ----- ----- ----- ----- - { __LINE__, 1, 1, 1, 1, 1, 2 }, - { __LINE__, 10, 2, 28, 10, 3, 1 }, - { __LINE__, 100, 3, 31, 100, 4, 1 }, - { __LINE__, 1000, 4, 30, 1000, 5, 1 }, - { __LINE__, 1100, 5, 31, 1100, 6, 1 }, - { __LINE__, 1200, 6, 30, 1200, 7, 1 }, - { __LINE__, 1300, 7, 31, 1300, 8, 1 }, - { __LINE__, 1400, 8, 31, 1400, 9, 1 }, - { __LINE__, 1500, 9, 30, 1500, 10, 1 }, - { __LINE__, 1600, 10, 31, 1600, 11, 1 }, - { __LINE__, 1700, 11, 30, 1700, 12, 1 }, - { __LINE__, 1800, 12, 31, 1801, 1, 1 }, - { __LINE__, 1996, 2, 28, 1996, 2, 29 }, - { __LINE__, 1997, 2, 28, 1997, 3, 1 }, - { __LINE__, 1998, 2, 28, 1998, 3, 1 }, - { __LINE__, 1999, 2, 28, 1999, 3, 1 }, - { __LINE__, 2000, 2, 28, 2000, 2, 29 }, - { __LINE__, 2001, 2, 28, 2001, 3, 1 }, - { __LINE__, 2004, 2, 28, 2004, 2, 29 }, - { __LINE__, 2100, 2, 28, 2100, 3, 1 }, - { __LINE__, 2400, 2, 28, 2400, 2, 29 }, - }; - - const int num_data = sizeof data / sizeof *data; - int di; - - for (di = 0; di < num_data; ++di) - { - const int line = data[di].lineNum; - DateTime x = DateTime(data[di].year1, data[di].month1, - data[di].day1); - // Would do pre-increment of x here. - const DateTime& X = x; - x = x + Timespan(1,0,0,0,0); - DateTime y = x; const DateTime& Y = y; - - loop_1_assert(line, data[di].year2 == X.year()); - loop_1_assert(line, data[di].month2 == X.month()); - loop_1_assert(line, data[di].day2 == X.day()); - - loop_1_assert(line, data[di].year2 == Y.year()); - loop_1_assert(line, data[di].month2 == Y.month()); - loop_1_assert(line, data[di].day2 == Y.day()); - } - - for (di = 0; di < num_data; ++di) - { - const int line = data[di].lineNum; - DateTime x = DateTime(data[di].year1, data[di].month1, data[di].day1); - DateTime x1 = DateTime(data[di].year1, data[di].month1, data[di].day1); - DateTime x2 = DateTime(data[di].year2, data[di].month2, data[di].day2); - DateTime y = x; const DateTime& Y = y; - - // Would do post increment of x here. - const DateTime& X = x; - x = x + Timespan(1,0,0,0,0); - - loop_1_assert(line, data[di].year2 == X.year()); - loop_1_assert(line, data[di].month2 == X.month()); - loop_1_assert(line, data[di].day2 == X.day()); - loop_1_assert(line, data[di].year1 == Y.year()); - loop_1_assert(line, data[di].month1 == Y.month()); - loop_1_assert(line, data[di].day1 == Y.day()); - } - - for (di = 0; di < num_data; ++di) - { - const int line = data[di].lineNum; - DateTime x = DateTime(data[di].year2, data[di].month2, data[di].day2); - const DateTime& X = x; - x = x - Timespan(1,0,0,0,0); - DateTime y = x; DateTime Y = y; - - loop_1_assert(line, data[di].year1 == X.year()); - loop_1_assert(line, data[di].month1 == X.month()); - loop_1_assert(line, data[di].day1 == X.day()); - - loop_1_assert(line, data[di].year1 == Y.year()); - loop_1_assert(line, data[di].month1 == Y.month()); - loop_1_assert(line, data[di].day1 == Y.day()); - } - - for (di = 0; di < num_data; ++di) - { - const int line = data[di].lineNum; - DateTime x1 = DateTime(data[di].year1, data[di].month1, data[di].day1); - DateTime x = DateTime(data[di].year2, data[di].month2, data[di].day2); - DateTime y = x; DateTime Y = y; - const DateTime& X = x; - // would post-decrement x here. - x = x - Timespan(1,0,0,0,0); - - loop_1_assert(line, data[di].year1 == X.year()); - loop_1_assert(line, data[di].month1 == X.month()); - loop_1_assert(line, data[di].day1 == X.day()); - - loop_1_assert(line, data[di].year2 == Y.year()); - loop_1_assert(line, data[di].month2 == Y.month()); - loop_1_assert(line, data[di].day2 == Y.day()); - } -} - - -void DateTimeTest::testSwap() -{ - DateTime dt1(2005, 1, 1, 0, 15, 30); - DateTime dt2(2005, 1, 2, 0, 15, 30); - DateTime dt3(2005, 1, 1, 0, 15, 30); - DateTime dt4(2005, 1, 2, 0, 15, 30); - - dt1.swap(dt2); - assert (dt2 == dt3); - assert (dt1 == dt4); -} - - -void DateTimeTest::testUsage() -{ - DateTime dt1(1776, 7, 4); - assert (dt1.year() == 1776); - assert (dt1.month() == 7); - assert (dt1.day() == 4); - - DateTime dt2(dt1); - dt2 += Timespan(6, 0, 0, 0, 0); - assert (dt2.year() == 1776); - assert (dt2.month() == 7); - assert (dt2.day() == 10); - - Timespan span = dt2 - dt1; - assert (span.days() == 6); - - // TODO - When adding months and years we need to be - // able to specify the end-end convention. - // We cannot do this in POCO at the moment. -} - - -void DateTimeTest::testSetYearDay() -{ - static const struct - { - int d_lineNum; // source line number - int d_year; // year under test - unsigned int d_day; // day-of-year under test - int d_expMonth; // expected month - unsigned int d_expDay; // expected day - } data[] = - { - //line no. year dayOfYr exp. month exp. day - //------- ----- ------- ---------- -------- - { __LINE__, 1, 1, 1, 1 }, - { __LINE__, 1, 2, 1, 2 }, - { __LINE__, 1, 365, 12, 31 }, - { __LINE__, 1996, 1, 1, 1 }, - { __LINE__, 1996, 2, 1, 2 }, - { __LINE__, 1996, 365, 12, 30 }, - { __LINE__, 1996, 366, 12, 31 } - }; - - const int num_data = sizeof data / sizeof *data; - for (int di = 0; di < num_data; ++di) - { - const int line = data[di].d_lineNum; - const int year = data[di].d_year; - const unsigned int day = data[di].d_day; - - const int exp_month = data[di].d_expMonth; - const unsigned int exp_day = data[di].d_expDay; - const DateTime r(year, exp_month, exp_day); - DateTime x; - const DateTime& X = x; - -#if 0 - // TODO - need to be able to assign a day number in the year - // but POCO is not able to do this. - - x.assign(year, day); - - // TODO - need to be able to assert with the loop counter - // but cppUnit is not able to do this. - - assert (r == x); - assert (day == X.dayOfYear()); -#endif - } - - static const struct - { - int d_lineNum; // source line number - int d_year; // year under test - int d_day; // day-of-year under test - int d_exp; // expected status - } data2[] = - { - //line no. year dayOfYr expected value - //------- ----- ------- -------------- - { __LINE__, 1, 1, 1 }, - { __LINE__, 1, -1, 0 }, - { __LINE__, 1, 0, 0 }, - { __LINE__, 1, 365, 1 }, - { __LINE__, 1, 366, 0 }, - { __LINE__, 1, 367, 0 }, - { __LINE__, 0, 0, 0 }, - { __LINE__, -1, -1, 0 }, - { __LINE__, 1996, 1, 1 }, - { __LINE__, 1996, 2, 1 }, - { __LINE__, 1996, 32, 1 }, - { __LINE__, 1996, 365, 1 }, - { __LINE__, 1996, 366, 1 }, - { __LINE__, 1996, 367, 0 }, - }; - - const int num_data2 = sizeof data2 / sizeof *data2; - for (int di = 0; di < num_data2; ++di) - { - const int line = data2[di].d_lineNum; - const int year = data2[di].d_year; - const int day = data2[di].d_day; - const int exp = data2[di].d_exp; - DateTime x; - const DateTime& X = x; - if (1 == exp) - { - DateTime r; - const DateTime& r2 = r; -#if 0 - r.set(year, day); -#endif - } - } -} - - -void DateTimeTest::testIsValid() -{ - static const struct - { - int d_lineNum; // source line number - int d_year; // year under test - int d_month; // month under test - int d_day; // day under test - bool d_exp; // expected value - } data[] = - { - //line no. year month day expected value - //------- ----- ----- ----- -------------- - { __LINE__, 0, 0, 0, false }, - { __LINE__, 1, 1, 0, false }, - { __LINE__, 1, 0, 1, false }, - { __LINE__, 0, 1, 1, true }, - { __LINE__, 1, 1, -1, false }, - { __LINE__, 1, -1, 1, false }, - { __LINE__, 2004, 1, 32, false }, - { __LINE__, 2004, 2, 30, false }, - { __LINE__, 2004, 3, 32, false }, - { __LINE__, 2004, 4, 31, false }, - { __LINE__, 2004, 5, 32, false }, - { __LINE__, 2004, 6, 31, false }, - { __LINE__, 2004, 7, 32, false }, - { __LINE__, 2004, 8, 32, false }, - { __LINE__, 2004, 9, 31, false }, - { __LINE__, 2004, 10, 32, false }, - { __LINE__, 2004, 11, 31, false }, - { __LINE__, 2004, 12, 32, false }, - { __LINE__, 0, 12, 31, true }, - { __LINE__, 0, 2, 29, true }, - { __LINE__, 1, 1, 1, true }, - { __LINE__, 2010, 1, 2, true }, - { __LINE__, 2011, 2, 5, true }, - { __LINE__, 2012, 3, 10, true }, - { __LINE__, 2013, 4, 17, true }, - { __LINE__, 2014, 5, 23, true }, - { __LINE__, 1600, 2, 29, true }, - { __LINE__, 1700, 2, 29, false }, - { __LINE__, 1800, 2, 29, false }, - { __LINE__, 1900, 2, 29, false }, - { __LINE__, 2000, 2, 29, true }, - { __LINE__, 2100, 2, 29, false }, - }; - - const int num_data = sizeof data / sizeof *data; - for (int di = 0; di < num_data; ++di) - { - const int line = data[di].d_lineNum; - const int year = data[di].d_year; - const int month = data[di].d_month; - const int day = data[di].d_day; - const bool exp = data[di].d_exp; - - bool isValid = DateTime::isValid(year, month, day); - loop_1_assert(line, exp == isValid); - } -} - - -void DateTimeTest::testDayOfWeek() -{ - typedef DateTime::DaysOfWeek DOW; - - static const struct - { - int d_lineNum; // source line number - int d_year; // year under test - int d_month; // month under test - int d_day; // day under test - DOW d_expDay; // number of days to be added - } data[] = - { - //Line no. year month day expDay - //------- ----- ----- ----- ------- - { __LINE__, 1600, 1, 1, DateTime::SATURDAY }, - { __LINE__, 1600, 1, 2, DateTime::SUNDAY }, - { __LINE__, 1600, 1, 3, DateTime::MONDAY }, - { __LINE__, 1600, 1, 4, DateTime::TUESDAY }, - { __LINE__, 1600, 1, 5, DateTime::WEDNESDAY }, - { __LINE__, 1600, 1, 6, DateTime::THURSDAY }, - { __LINE__, 1600, 1, 7, DateTime::FRIDAY }, - { __LINE__, 1600, 1, 8, DateTime::SATURDAY }, - { __LINE__, 1752, 8, 27, DateTime::SUNDAY }, - { __LINE__, 1752, 8, 28, DateTime::MONDAY }, - { __LINE__, 1752, 8, 29, DateTime::TUESDAY }, - { __LINE__, 1752, 8, 30, DateTime::WEDNESDAY }, - { __LINE__, 1752, 8, 31, DateTime::THURSDAY }, - { __LINE__, 1752, 9, 1, DateTime::FRIDAY }, - { __LINE__, 1752, 9, 2, DateTime::SATURDAY }, - { __LINE__, 1752, 9, 14, DateTime::THURSDAY }, - { __LINE__, 1752, 9, 15, DateTime::FRIDAY }, - { __LINE__, 1752, 9, 16, DateTime::SATURDAY }, - { __LINE__, 1752, 9, 17, DateTime::SUNDAY }, - { __LINE__, 1752, 9, 18, DateTime::MONDAY }, - { __LINE__, 1752, 9, 19, DateTime::TUESDAY }, - { __LINE__, 1999, 12, 28, DateTime::TUESDAY }, - { __LINE__, 1999, 12, 29, DateTime::WEDNESDAY }, - { __LINE__, 1999, 12, 30, DateTime::THURSDAY }, - { __LINE__, 1999, 12, 31, DateTime::FRIDAY }, - { __LINE__, 2000, 1, 1, DateTime::SATURDAY }, - { __LINE__, 2000, 1, 2, DateTime::SUNDAY }, - { __LINE__, 2000, 1, 3, DateTime::MONDAY }, - { __LINE__, 2000, 1, 4, DateTime::TUESDAY }, - }; - - const int num_data = sizeof data / sizeof *data; - for (int di = 0; di < num_data ; ++di) - { - const int line = data[di].d_lineNum; - DateTime x = DateTime(data[di].d_year, data[di].d_month, data[di].d_day); - const DateTime& X = x; - loop_1_assert(line, data[di].d_expDay == X.dayOfWeek()); - } -} - - -void DateTimeTest::setUp() -{ -} - - -void DateTimeTest::tearDown() -{ -} - - -CppUnit::Test* DateTimeTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("DateTimeTest"); - - CppUnit_addTest(pSuite, DateTimeTest, testTimestamp); - CppUnit_addTest(pSuite, DateTimeTest, testJulian); - CppUnit_addTest(pSuite, DateTimeTest, testGregorian); - CppUnit_addTest(pSuite, DateTimeTest, testConversions); - CppUnit_addTest(pSuite, DateTimeTest, testStatics); - CppUnit_addTest(pSuite, DateTimeTest, testCalcs); - CppUnit_addTest(pSuite, DateTimeTest, testAMPM); - CppUnit_addTest(pSuite, DateTimeTest, testRelational); - CppUnit_addTest(pSuite, DateTimeTest, testArithmetics); - CppUnit_addTest(pSuite, DateTimeTest, testSwap); - - CppUnit_addTest(pSuite, DateTimeTest, testUsage); - CppUnit_addTest(pSuite, DateTimeTest, testSetYearDay); - CppUnit_addTest(pSuite, DateTimeTest, testIsValid); - CppUnit_addTest(pSuite, DateTimeTest, testDayOfWeek); - CppUnit_addTest(pSuite, DateTimeTest, testIncrementDecrement); - - return pSuite; -} +// +// DateTimeTest.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/DateTimeTest.cpp#2 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "DateTimeTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/DateTime.h" +#include "Poco/Timestamp.h" +#include "Poco/Timespan.h" +#include "Poco/Exception.h" + + +using Poco::Timestamp; +using Poco::DateTime; +using Poco::Timespan; +using Poco::AssertionViolationException; + + +DateTimeTest::DateTimeTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +DateTimeTest::~DateTimeTest() +{ +} + + +void DateTimeTest::testTimestamp() +{ + Timestamp ts(0); // Unix epoch 1970-01-01 00:00:00 Thursday + DateTime dt(ts); + assert (dt.year() == 1970); + assert (dt.month() == 1); + assert (dt.day() == 1); + assert (dt.hour() == 0); + assert (dt.minute() == 0); + assert (dt.second() == 0); + assert (dt.millisecond() == 0); + assert (dt.dayOfWeek() == 4); + assert (dt.julianDay() == 2440587.5); + assert (dt.timestamp() == 0); + + ts = Timestamp::fromEpochTime(1000000000); + dt = ts; // 2001-09-09 01:46:40 Sunday + assert (dt.year() == 2001); + assert (dt.month() == 9); + assert (dt.day() == 9); + assert (dt.hour() == 1); + assert (dt.minute() == 46); + assert (dt.second() == 40); + assert (dt.millisecond() == 0); + assert (dt.dayOfWeek() == 0); + assert (dt.timestamp().epochTime() == 1000000000); + assertEqualDelta (dt.julianDay(), 2452161.574074, 0.000001); +} + + +void DateTimeTest::testJulian() +{ + DateTime dt(2440587.5); // unix epoch as Julian day + assert (dt.year() == 1970); + assert (dt.month() == 1); + assert (dt.day() == 1); + assert (dt.hour() == 0); + assert (dt.minute() == 0); + assert (dt.second() == 0); + assert (dt.millisecond() == 0); + assert (dt.dayOfWeek() == 4); + assert (dt.julianDay() == 2440587.5); + assert (dt.timestamp() == 0); + + dt = 2299160.5; // 1582-10-15 00:00:00 (first day of Gregorian reform, UTC base) + assert (dt.year() == 1582); + assert (dt.month() == 10); + assert (dt.day() == 15); + assert (dt.hour() == 0); + assert (dt.minute() == 0); + assert (dt.second() == 0); + assert (dt.millisecond() == 0); + assert (dt.dayOfWeek() == 5); + assert (dt.julianDay() == 2299160.5); + + dt = 0.0; // -4713-11-24 12:00:00 (Gregorian date of Julian day reference) + assert (dt.year() == -4713); + assert (dt.month() == 11); + assert (dt.day() == 24); + assert (dt.hour() == 12); + assert (dt.minute() == 0); + assert (dt.second() == 0); + assert (dt.millisecond() == 0); + assert (dt.dayOfWeek() == 1); + assert (dt.julianDay() == 0); + + // Test that we can represent down to the microsecond. + dt = DateTime(2010, 1, 31, 17, 30, 15, 800, 3); + + assert (dt.year() == 2010); + assert (dt.month() == 1); + assert (dt.day() == 31); + assert (dt.hour() == 17); + assert (dt.minute() == 30); + assert (dt.second() == 15); + assert (dt.millisecond() == 800); + assert (dt.microsecond() == 3); +} + + +void DateTimeTest::testGregorian() +{ + DateTime dt(1970, 1, 1); + assert (dt.year() == 1970); + assert (dt.month() == 1); + assert (dt.day() == 1); + assert (dt.hour() == 0); + assert (dt.minute() == 0); + assert (dt.second() == 0); + assert (dt.millisecond() == 0); + assert (dt.dayOfWeek() == 4); + assert (dt.julianDay() == 2440587.5); + assert (dt.timestamp() == 0); + + dt.assign(2001, 9, 9, 1, 46, 40); + assert (dt.year() == 2001); + assert (dt.month() == 9); + assert (dt.day() == 9); + assert (dt.hour() == 1); + assert (dt.minute() == 46); + assert (dt.second() == 40); + assert (dt.millisecond() == 0); + assert (dt.dayOfWeek() == 0); + assert (dt.timestamp().epochTime() == 1000000000); + assertEqualDelta (dt.julianDay(), 2452161.574074, 0.000001); +} + + +void DateTimeTest::testConversions() +{ + DateTime dt1(2005, 1, 28, 14, 24, 44, 234); + Timestamp ts1 = dt1.timestamp(); + DateTime dt2(ts1); + Timestamp ts2 = dt2.timestamp(); + DateTime dt3; + dt3 = dt1; + Timestamp ts3 = dt3.timestamp(); + DateTime dt4(dt2); + Timestamp ts4 = dt4.timestamp(); + + assert (ts1 == ts2); + assert (ts2 == ts3); + assert (ts3 == ts4); + + assert (dt2.year() == 2005); + assert (dt2.month() == 1); + assert (dt2.day() == 28); + assert (dt2.hour() == 14); + assert (dt2.minute() == 24); + assert (dt2.second() == 44); + assert (dt2.millisecond() == 234); + assert (dt2.dayOfWeek() == 5); +} + + +void DateTimeTest::testStatics() +{ + assert (DateTime::isLeapYear(1984)); + assert (DateTime::isLeapYear(1988)); + assert (DateTime::isLeapYear(1992)); + assert (DateTime::isLeapYear(1996)); + assert (DateTime::isLeapYear(2000)); + assert (DateTime::isLeapYear(2400)); + assert (!DateTime::isLeapYear(1995)); + assert (!DateTime::isLeapYear(1998)); + assert (!DateTime::isLeapYear(2001)); + assert (!DateTime::isLeapYear(1800)); + assert (!DateTime::isLeapYear(1900)); + + assert (DateTime::daysOfMonth(2000, 1) == 31); + assert (DateTime::daysOfMonth(2000, 2) == 29); + assert (DateTime::daysOfMonth(1999, 2) == 28); +} + + +void DateTimeTest::testCalcs() +{ + DateTime dt1(2005, 1, 1); + assert (dt1.dayOfYear() == 1); + assert (dt1.week(DateTime::MONDAY) == 0); + dt1.assign(2005, 1, 3); + assert (dt1.dayOfYear() == 3); + assert (dt1.week(DateTime::MONDAY) == 1); + dt1.assign(2005, 1, 9); + assert (dt1.dayOfYear() == 9); + assert (dt1.week(DateTime::MONDAY) == 1); + dt1.assign(2005, 1, 10); + assert (dt1.dayOfYear() == 10); + assert (dt1.week(DateTime::MONDAY) == 2); + dt1.assign(2005, 2, 1); + assert (dt1.dayOfYear() == 32); + assert (dt1.week(DateTime::MONDAY) == 5); + dt1.assign(2005, 12, 31); + assert (dt1.week(DateTime::MONDAY) == 52); + dt1.assign(2007, 1, 1); + assert (dt1.week(DateTime::MONDAY) == 1); + dt1.assign(2007, 12, 31); + assert (dt1.week(DateTime::MONDAY) == 53); + + // Jan 1 is Mon + dt1.assign(2001, 1, 1); + assert (dt1.week() == 1); + dt1.assign(2001, 1, 7); + assert (dt1.week() == 1); + dt1.assign(2001, 1, 8); + assert (dt1.week() == 2); + dt1.assign(2001, 1, 21); + assert (dt1.week() == 3); + dt1.assign(2001, 1, 22); + assert (dt1.week() == 4); + + // Jan 1 is Tue + dt1.assign(2002, 1, 1); + assert (dt1.week() == 1); + dt1.assign(2002, 1, 6); + assert (dt1.week() == 1); + dt1.assign(2002, 1, 7); + assert (dt1.week() == 2); + dt1.assign(2002, 1, 20); + assert (dt1.week() == 3); + dt1.assign(2002, 1, 21); + assert (dt1.week() == 4); + + // Jan 1 is Wed + dt1.assign(2003, 1, 1); + assert (dt1.week() == 1); + dt1.assign(2003, 1, 5); + assert (dt1.week() == 1); + dt1.assign(2003, 1, 6); + assert (dt1.week() == 2); + dt1.assign(2003, 1, 19); + assert (dt1.week() == 3); + dt1.assign(2003, 1, 20); + assert (dt1.week() == 4); + + // Jan 1 is Thu + dt1.assign(2004, 1, 1); + assert (dt1.week() == 1); + dt1.assign(2004, 1, 4); + assert (dt1.week() == 1); + dt1.assign(2004, 1, 5); + assert (dt1.week() == 2); + dt1.assign(2004, 1, 18); + assert (dt1.week() == 3); + dt1.assign(2004, 1, 19); + assert (dt1.week() == 4); + + // Jan 1 is Fri + dt1.assign(1999, 1, 1); + assert (dt1.week() == 0); + dt1.assign(1999, 1, 3); + assert (dt1.week() == 0); + dt1.assign(1999, 1, 4); + assert (dt1.week() == 1); + dt1.assign(1999, 1, 17); + assert (dt1.week() == 2); + dt1.assign(1999, 1, 18); + assert (dt1.week() == 3); + + // Jan 1 is Sat + dt1.assign(2000, 1, 1); + assert (dt1.week() == 0); + dt1.assign(2000, 1, 2); + assert (dt1.week() == 0); + dt1.assign(2000, 1, 3); + assert (dt1.week() == 1); + dt1.assign(2000, 1, 16); + assert (dt1.week() == 2); + dt1.assign(2000, 1, 17); + assert (dt1.week() == 3); + + // Jan 1 is Sun + dt1.assign(1995, 1, 1); + assert (dt1.week() == 0); + dt1.assign(1995, 1, 2); + assert (dt1.week() == 1); + dt1.assign(1995, 1, 3); + assert (dt1.week() == 1); + dt1.assign(1995, 1, 15); + assert (dt1.week() == 2); + dt1.assign(1995, 1, 16); + assert (dt1.week() == 3); +} + + +void DateTimeTest::testAMPM() +{ + DateTime dt1(2005, 1, 1, 0, 15, 30); + assert (dt1.isAM()); + assert (!dt1.isPM()); + assert (dt1.hourAMPM() == 12); + + dt1.assign(2005, 1, 1, 12, 15, 30); + assert (!dt1.isAM()); + assert (dt1.isPM()); + assert (dt1.hourAMPM() == 12); + + dt1.assign(2005, 1, 1, 13, 15, 30); + assert (!dt1.isAM()); + assert (dt1.isPM()); + assert (dt1.hourAMPM() == 1); +} + + +void DateTimeTest::testRelational() +{ + DateTime dt1(2005, 1, 1, 0, 15, 30); + DateTime dt2(2005, 1, 2, 0, 15, 30); + DateTime dt3(dt1); + + assert (dt1 < dt2); + assert (dt1 <= dt2); + assert (dt2 > dt1); + assert (dt2 >= dt1); + assert (dt1 != dt2); + assert (!(dt1 == dt2)); + + assert (dt1 == dt3); + assert (!(dt1 != dt3)); + assert (dt1 >= dt3); + assert (dt1 <= dt3); + assert (!(dt1 > dt3)); + assert (!(dt1 < dt3)); + + static const struct + { + int year; + int month; + int day; + } values[] = + { + { 1, 1, 1 }, + { 10, 4, 5 }, + { 100, 6, 7 }, + { 1000, 8, 9 }, + { 2000, 1, 31 }, + { 2002, 7, 4 }, + { 2002, 12, 31 }, + { 2003, 1, 1 }, + { 2003, 1, 2 }, + { 2003, 8, 5 }, + { 2003, 8, 6 }, + { 2003, 8, 7 }, + { 2004, 9, 3 }, + { 2004, 9, 4 }, + }; + + const int num_values = sizeof values / sizeof *values; + for (int i = 0; i < num_values; ++i) + { + DateTime v; + const DateTime& V = v; + v.assign(values[i].year, values[i].month, values[i].day); + for (int j = 0; j < num_values; ++j) + { + DateTime u; + const DateTime& U = u; + u.assign(values[j].year, values[j].month, values[j].day); + + loop_2_assert(i, j, j < i == U < V); + loop_2_assert(i, j, j <= i == U <= V); + loop_2_assert(i, j, j >= i == U >= V); + loop_2_assert(i, j, j > i == U > V); + } + } +} + + +void DateTimeTest::testArithmetics() +{ + DateTime dt1(2005, 1, 1, 0, 15, 30); + DateTime dt2(2005, 1, 2, 0, 15, 30); + + Timespan s = dt2 - dt1; + assert (s.days() == 1); + + DateTime dt3 = dt1 + s; + assert (dt3 == dt2); + + dt3 -= s; + assert (dt3 == dt1); + dt1 += s; + assert (dt1 == dt2); + + static const struct + { + int lineNum; // source line number + int year1; // operand/result date1 year + int month1; // operand/result date1 month + unsigned int day1; // operand/result date1 day + int numDays; // operand/result 'int' number of days + int year2; // operand/result date2 year + int month2; // operand/result date2 month + unsigned int day2; // operand/result date2 day + } data[] = + { + // - - - -first- - - - - - - second - - - + //line no. year month day numDays year month day + //------- ----- ----- ----- ------- ----- ----- ----- + { __LINE__, 1, 1, 1, 1, 1, 1, 2 }, + { __LINE__, 10, 2, 28, 1, 10, 3, 1 }, + { __LINE__, 100, 3, 31, 2, 100, 4, 2 }, + { __LINE__, 1000, 4, 30, 4, 1000, 5, 4 }, + { __LINE__, 1000, 6, 1, -31, 1000, 5, 1 }, + { __LINE__, 1001, 1, 1, -365, 1000, 1, 1 }, + { __LINE__, 1100, 5, 31, 30, 1100, 6, 30 }, + { __LINE__, 1200, 6, 30, 32, 1200, 8, 1 }, + { __LINE__, 1996, 2, 28, 367, 1997, 3, 1 }, + { __LINE__, 1997, 2, 28, 366, 1998, 3, 1 }, + { __LINE__, 1998, 2, 28, 365, 1999, 2, 28 }, + { __LINE__, 1999, 2, 28, 364, 2000, 2, 27 }, + { __LINE__, 1999, 2, 28, 1096, 2002, 2, 28 }, + { __LINE__, 2002, 2, 28, -1096, 1999, 2, 28 }, + }; + + const int num_data = sizeof data / sizeof *data; + for (int di = 0; di < num_data; ++di) + { + const int line = data[di].lineNum; + const int num_days = data[di].numDays; + DateTime x = DateTime(data[di].year1, data[di].month1, data[di].day1); + const DateTime& X = x; + x += Timespan(num_days, 0, 0, 0, 0); + loop_1_assert(line, data[di].year2 == X.year()); + loop_1_assert(line, data[di].month2 == X.month()); + loop_1_assert(line, data[di].day2 == X.day()); + } +} + +void DateTimeTest::testIncrementDecrement() +{ + static const struct + { + int lineNum; // source line number + int year1; // (first) date year + int month1; // (first) date month + unsigned int day1; // (first) date day + int year2; // (second) date year + int month2; // (second) date month + unsigned int day2; // (second) date day + } data[] = + { + // - - - -first- - - - - - - second - - - + //line no. year month day year month day + //------- ----- ----- ----- ----- ----- ----- + { __LINE__, 1, 1, 1, 1, 1, 2 }, + { __LINE__, 10, 2, 28, 10, 3, 1 }, + { __LINE__, 100, 3, 31, 100, 4, 1 }, + { __LINE__, 1000, 4, 30, 1000, 5, 1 }, + { __LINE__, 1100, 5, 31, 1100, 6, 1 }, + { __LINE__, 1200, 6, 30, 1200, 7, 1 }, + { __LINE__, 1300, 7, 31, 1300, 8, 1 }, + { __LINE__, 1400, 8, 31, 1400, 9, 1 }, + { __LINE__, 1500, 9, 30, 1500, 10, 1 }, + { __LINE__, 1600, 10, 31, 1600, 11, 1 }, + { __LINE__, 1700, 11, 30, 1700, 12, 1 }, + { __LINE__, 1800, 12, 31, 1801, 1, 1 }, + { __LINE__, 1996, 2, 28, 1996, 2, 29 }, + { __LINE__, 1997, 2, 28, 1997, 3, 1 }, + { __LINE__, 1998, 2, 28, 1998, 3, 1 }, + { __LINE__, 1999, 2, 28, 1999, 3, 1 }, + { __LINE__, 2000, 2, 28, 2000, 2, 29 }, + { __LINE__, 2001, 2, 28, 2001, 3, 1 }, + { __LINE__, 2004, 2, 28, 2004, 2, 29 }, + { __LINE__, 2100, 2, 28, 2100, 3, 1 }, + { __LINE__, 2400, 2, 28, 2400, 2, 29 }, + }; + + const int num_data = sizeof data / sizeof *data; + int di; + + for (di = 0; di < num_data; ++di) + { + const int line = data[di].lineNum; + DateTime x = DateTime(data[di].year1, data[di].month1, + data[di].day1); + // Would do pre-increment of x here. + const DateTime& X = x; + x = x + Timespan(1,0,0,0,0); + DateTime y = x; const DateTime& Y = y; + + loop_1_assert(line, data[di].year2 == X.year()); + loop_1_assert(line, data[di].month2 == X.month()); + loop_1_assert(line, data[di].day2 == X.day()); + + loop_1_assert(line, data[di].year2 == Y.year()); + loop_1_assert(line, data[di].month2 == Y.month()); + loop_1_assert(line, data[di].day2 == Y.day()); + } + + for (di = 0; di < num_data; ++di) + { + const int line = data[di].lineNum; + DateTime x = DateTime(data[di].year1, data[di].month1, data[di].day1); + DateTime x1 = DateTime(data[di].year1, data[di].month1, data[di].day1); + DateTime x2 = DateTime(data[di].year2, data[di].month2, data[di].day2); + DateTime y = x; const DateTime& Y = y; + + // Would do post increment of x here. + const DateTime& X = x; + x = x + Timespan(1,0,0,0,0); + + loop_1_assert(line, data[di].year2 == X.year()); + loop_1_assert(line, data[di].month2 == X.month()); + loop_1_assert(line, data[di].day2 == X.day()); + loop_1_assert(line, data[di].year1 == Y.year()); + loop_1_assert(line, data[di].month1 == Y.month()); + loop_1_assert(line, data[di].day1 == Y.day()); + } + + for (di = 0; di < num_data; ++di) + { + const int line = data[di].lineNum; + DateTime x = DateTime(data[di].year2, data[di].month2, data[di].day2); + const DateTime& X = x; + x = x - Timespan(1,0,0,0,0); + DateTime y = x; DateTime Y = y; + + loop_1_assert(line, data[di].year1 == X.year()); + loop_1_assert(line, data[di].month1 == X.month()); + loop_1_assert(line, data[di].day1 == X.day()); + + loop_1_assert(line, data[di].year1 == Y.year()); + loop_1_assert(line, data[di].month1 == Y.month()); + loop_1_assert(line, data[di].day1 == Y.day()); + } + + for (di = 0; di < num_data; ++di) + { + const int line = data[di].lineNum; + DateTime x1 = DateTime(data[di].year1, data[di].month1, data[di].day1); + DateTime x = DateTime(data[di].year2, data[di].month2, data[di].day2); + DateTime y = x; DateTime Y = y; + const DateTime& X = x; + // would post-decrement x here. + x = x - Timespan(1,0,0,0,0); + + loop_1_assert(line, data[di].year1 == X.year()); + loop_1_assert(line, data[di].month1 == X.month()); + loop_1_assert(line, data[di].day1 == X.day()); + + loop_1_assert(line, data[di].year2 == Y.year()); + loop_1_assert(line, data[di].month2 == Y.month()); + loop_1_assert(line, data[di].day2 == Y.day()); + } +} + + +void DateTimeTest::testSwap() +{ + DateTime dt1(2005, 1, 1, 0, 15, 30); + DateTime dt2(2005, 1, 2, 0, 15, 30); + DateTime dt3(2005, 1, 1, 0, 15, 30); + DateTime dt4(2005, 1, 2, 0, 15, 30); + + dt1.swap(dt2); + assert (dt2 == dt3); + assert (dt1 == dt4); +} + + +void DateTimeTest::testUsage() +{ + DateTime dt1(1776, 7, 4); + assert (dt1.year() == 1776); + assert (dt1.month() == 7); + assert (dt1.day() == 4); + + DateTime dt2(dt1); + dt2 += Timespan(6, 0, 0, 0, 0); + assert (dt2.year() == 1776); + assert (dt2.month() == 7); + assert (dt2.day() == 10); + + Timespan span = dt2 - dt1; + assert (span.days() == 6); + + // TODO - When adding months and years we need to be + // able to specify the end-end convention. + // We cannot do this in POCO at the moment. +} + + +void DateTimeTest::testSetYearDay() +{ + static const struct + { + int d_lineNum; // source line number + int d_year; // year under test + unsigned int d_day; // day-of-year under test + int d_expMonth; // expected month + unsigned int d_expDay; // expected day + } data[] = + { + //line no. year dayOfYr exp. month exp. day + //------- ----- ------- ---------- -------- + { __LINE__, 1, 1, 1, 1 }, + { __LINE__, 1, 2, 1, 2 }, + { __LINE__, 1, 365, 12, 31 }, + { __LINE__, 1996, 1, 1, 1 }, + { __LINE__, 1996, 2, 1, 2 }, + { __LINE__, 1996, 365, 12, 30 }, + { __LINE__, 1996, 366, 12, 31 } + }; + + const int num_data = sizeof data / sizeof *data; + for (int di = 0; di < num_data; ++di) + { + const int line = data[di].d_lineNum; + const int year = data[di].d_year; + const unsigned int day = data[di].d_day; + + const int exp_month = data[di].d_expMonth; + const unsigned int exp_day = data[di].d_expDay; + const DateTime r(year, exp_month, exp_day); + DateTime x; + const DateTime& X = x; + +#if 0 + // TODO - need to be able to assign a day number in the year + // but POCO is not able to do this. + + x.assign(year, day); + + // TODO - need to be able to assert with the loop counter + // but cppUnit is not able to do this. + + assert (r == x); + assert (day == X.dayOfYear()); +#endif + } + + static const struct + { + int d_lineNum; // source line number + int d_year; // year under test + int d_day; // day-of-year under test + int d_exp; // expected status + } data2[] = + { + //line no. year dayOfYr expected value + //------- ----- ------- -------------- + { __LINE__, 1, 1, 1 }, + { __LINE__, 1, -1, 0 }, + { __LINE__, 1, 0, 0 }, + { __LINE__, 1, 365, 1 }, + { __LINE__, 1, 366, 0 }, + { __LINE__, 1, 367, 0 }, + { __LINE__, 0, 0, 0 }, + { __LINE__, -1, -1, 0 }, + { __LINE__, 1996, 1, 1 }, + { __LINE__, 1996, 2, 1 }, + { __LINE__, 1996, 32, 1 }, + { __LINE__, 1996, 365, 1 }, + { __LINE__, 1996, 366, 1 }, + { __LINE__, 1996, 367, 0 }, + }; + + const int num_data2 = sizeof data2 / sizeof *data2; + for (int di = 0; di < num_data2; ++di) + { + const int line = data2[di].d_lineNum; + const int year = data2[di].d_year; + const int day = data2[di].d_day; + const int exp = data2[di].d_exp; + DateTime x; + const DateTime& X = x; + if (1 == exp) + { + DateTime r; + const DateTime& r2 = r; +#if 0 + r.set(year, day); +#endif + } + } +} + + +void DateTimeTest::testIsValid() +{ + static const struct + { + int d_lineNum; // source line number + int d_year; // year under test + int d_month; // month under test + int d_day; // day under test + bool d_exp; // expected value + } data[] = + { + //line no. year month day expected value + //------- ----- ----- ----- -------------- + { __LINE__, 0, 0, 0, false }, + { __LINE__, 1, 1, 0, false }, + { __LINE__, 1, 0, 1, false }, + { __LINE__, 0, 1, 1, true }, + { __LINE__, 1, 1, -1, false }, + { __LINE__, 1, -1, 1, false }, + { __LINE__, 2004, 1, 32, false }, + { __LINE__, 2004, 2, 30, false }, + { __LINE__, 2004, 3, 32, false }, + { __LINE__, 2004, 4, 31, false }, + { __LINE__, 2004, 5, 32, false }, + { __LINE__, 2004, 6, 31, false }, + { __LINE__, 2004, 7, 32, false }, + { __LINE__, 2004, 8, 32, false }, + { __LINE__, 2004, 9, 31, false }, + { __LINE__, 2004, 10, 32, false }, + { __LINE__, 2004, 11, 31, false }, + { __LINE__, 2004, 12, 32, false }, + { __LINE__, 0, 12, 31, true }, + { __LINE__, 0, 2, 29, true }, + { __LINE__, 1, 1, 1, true }, + { __LINE__, 2010, 1, 2, true }, + { __LINE__, 2011, 2, 5, true }, + { __LINE__, 2012, 3, 10, true }, + { __LINE__, 2013, 4, 17, true }, + { __LINE__, 2014, 5, 23, true }, + { __LINE__, 1600, 2, 29, true }, + { __LINE__, 1700, 2, 29, false }, + { __LINE__, 1800, 2, 29, false }, + { __LINE__, 1900, 2, 29, false }, + { __LINE__, 2000, 2, 29, true }, + { __LINE__, 2100, 2, 29, false }, + }; + + const int num_data = sizeof data / sizeof *data; + for (int di = 0; di < num_data; ++di) + { + const int line = data[di].d_lineNum; + const int year = data[di].d_year; + const int month = data[di].d_month; + const int day = data[di].d_day; + const bool exp = data[di].d_exp; + + bool isValid = DateTime::isValid(year, month, day); + loop_1_assert(line, exp == isValid); + } +} + + +void DateTimeTest::testDayOfWeek() +{ + typedef DateTime::DaysOfWeek DOW; + + static const struct + { + int d_lineNum; // source line number + int d_year; // year under test + int d_month; // month under test + int d_day; // day under test + DOW d_expDay; // number of days to be added + } data[] = + { + //Line no. year month day expDay + //------- ----- ----- ----- ------- + { __LINE__, 1600, 1, 1, DateTime::SATURDAY }, + { __LINE__, 1600, 1, 2, DateTime::SUNDAY }, + { __LINE__, 1600, 1, 3, DateTime::MONDAY }, + { __LINE__, 1600, 1, 4, DateTime::TUESDAY }, + { __LINE__, 1600, 1, 5, DateTime::WEDNESDAY }, + { __LINE__, 1600, 1, 6, DateTime::THURSDAY }, + { __LINE__, 1600, 1, 7, DateTime::FRIDAY }, + { __LINE__, 1600, 1, 8, DateTime::SATURDAY }, + { __LINE__, 1752, 8, 27, DateTime::SUNDAY }, + { __LINE__, 1752, 8, 28, DateTime::MONDAY }, + { __LINE__, 1752, 8, 29, DateTime::TUESDAY }, + { __LINE__, 1752, 8, 30, DateTime::WEDNESDAY }, + { __LINE__, 1752, 8, 31, DateTime::THURSDAY }, + { __LINE__, 1752, 9, 1, DateTime::FRIDAY }, + { __LINE__, 1752, 9, 2, DateTime::SATURDAY }, + { __LINE__, 1752, 9, 14, DateTime::THURSDAY }, + { __LINE__, 1752, 9, 15, DateTime::FRIDAY }, + { __LINE__, 1752, 9, 16, DateTime::SATURDAY }, + { __LINE__, 1752, 9, 17, DateTime::SUNDAY }, + { __LINE__, 1752, 9, 18, DateTime::MONDAY }, + { __LINE__, 1752, 9, 19, DateTime::TUESDAY }, + { __LINE__, 1999, 12, 28, DateTime::TUESDAY }, + { __LINE__, 1999, 12, 29, DateTime::WEDNESDAY }, + { __LINE__, 1999, 12, 30, DateTime::THURSDAY }, + { __LINE__, 1999, 12, 31, DateTime::FRIDAY }, + { __LINE__, 2000, 1, 1, DateTime::SATURDAY }, + { __LINE__, 2000, 1, 2, DateTime::SUNDAY }, + { __LINE__, 2000, 1, 3, DateTime::MONDAY }, + { __LINE__, 2000, 1, 4, DateTime::TUESDAY }, + }; + + const int num_data = sizeof data / sizeof *data; + for (int di = 0; di < num_data ; ++di) + { + const int line = data[di].d_lineNum; + DateTime x = DateTime(data[di].d_year, data[di].d_month, data[di].d_day); + const DateTime& X = x; + loop_1_assert(line, data[di].d_expDay == X.dayOfWeek()); + } +} + + +void DateTimeTest::setUp() +{ +} + + +void DateTimeTest::tearDown() +{ +} + + +CppUnit::Test* DateTimeTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("DateTimeTest"); + + CppUnit_addTest(pSuite, DateTimeTest, testTimestamp); + CppUnit_addTest(pSuite, DateTimeTest, testJulian); + CppUnit_addTest(pSuite, DateTimeTest, testGregorian); + CppUnit_addTest(pSuite, DateTimeTest, testConversions); + CppUnit_addTest(pSuite, DateTimeTest, testStatics); + CppUnit_addTest(pSuite, DateTimeTest, testCalcs); + CppUnit_addTest(pSuite, DateTimeTest, testAMPM); + CppUnit_addTest(pSuite, DateTimeTest, testRelational); + CppUnit_addTest(pSuite, DateTimeTest, testArithmetics); + CppUnit_addTest(pSuite, DateTimeTest, testSwap); + + CppUnit_addTest(pSuite, DateTimeTest, testUsage); + CppUnit_addTest(pSuite, DateTimeTest, testSetYearDay); + CppUnit_addTest(pSuite, DateTimeTest, testIsValid); + CppUnit_addTest(pSuite, DateTimeTest, testDayOfWeek); + CppUnit_addTest(pSuite, DateTimeTest, testIncrementDecrement); + + return pSuite; +} diff --git a/Foundation/testsuite/src/DateTimeTest.h b/Foundation/testsuite/src/DateTimeTest.h index f10103554..70aea0f4f 100644 --- a/Foundation/testsuite/src/DateTimeTest.h +++ b/Foundation/testsuite/src/DateTimeTest.h @@ -1,74 +1,74 @@ -// -// DateTimeTest.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/DateTimeTest.h#1 $ -// -// Definition of the DateTimeTest class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 DateTimeTest_INCLUDED -#define DateTimeTest_INCLUDED - - -#include "Poco/Foundation.h" -#include "CppUnit/TestCase.h" - - -class DateTimeTest: public CppUnit::TestCase -{ -public: - DateTimeTest(const std::string& name); - ~DateTimeTest(); - - void testTimestamp(); - void testJulian(); - void testGregorian(); - void testConversions(); - void testStatics(); - void testCalcs(); - void testAMPM(); - void testRelational(); - void testArithmetics(); - void testSwap(); - void testUsage(); - void testSetYearDay(); - void testIsValid(); - void testDayOfWeek(); - void testIncrementDecrement(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // DateTimeTest_INCLUDED +// +// DateTimeTest.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/DateTimeTest.h#1 $ +// +// Definition of the DateTimeTest class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 DateTimeTest_INCLUDED +#define DateTimeTest_INCLUDED + + +#include "Poco/Foundation.h" +#include "CppUnit/TestCase.h" + + +class DateTimeTest: public CppUnit::TestCase +{ +public: + DateTimeTest(const std::string& name); + ~DateTimeTest(); + + void testTimestamp(); + void testJulian(); + void testGregorian(); + void testConversions(); + void testStatics(); + void testCalcs(); + void testAMPM(); + void testRelational(); + void testArithmetics(); + void testSwap(); + void testUsage(); + void testSetYearDay(); + void testIsValid(); + void testDayOfWeek(); + void testIncrementDecrement(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // DateTimeTest_INCLUDED diff --git a/Foundation/testsuite/src/DateTimeTestSuite.cpp b/Foundation/testsuite/src/DateTimeTestSuite.cpp index 22c30db52..f1dd3a933 100644 --- a/Foundation/testsuite/src/DateTimeTestSuite.cpp +++ b/Foundation/testsuite/src/DateTimeTestSuite.cpp @@ -1,56 +1,56 @@ -// -// DateTimeTestSuite.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/DateTimeTestSuite.cpp#1 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "DateTimeTestSuite.h" -#include "TimestampTest.h" -#include "TimespanTest.h" -#include "TimezoneTest.h" -#include "DateTimeTest.h" -#include "LocalDateTimeTest.h" -#include "DateTimeFormatterTest.h" -#include "DateTimeParserTest.h" - - -CppUnit::Test* DateTimeTestSuite::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("DateTimeTestSuite"); - - pSuite->addTest(TimestampTest::suite()); - pSuite->addTest(TimespanTest::suite()); - pSuite->addTest(TimezoneTest::suite()); - pSuite->addTest(DateTimeTest::suite()); - pSuite->addTest(LocalDateTimeTest::suite()); - pSuite->addTest(DateTimeFormatterTest::suite()); - pSuite->addTest(DateTimeParserTest::suite()); - - return pSuite; -} +// +// DateTimeTestSuite.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/DateTimeTestSuite.cpp#1 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "DateTimeTestSuite.h" +#include "TimestampTest.h" +#include "TimespanTest.h" +#include "TimezoneTest.h" +#include "DateTimeTest.h" +#include "LocalDateTimeTest.h" +#include "DateTimeFormatterTest.h" +#include "DateTimeParserTest.h" + + +CppUnit::Test* DateTimeTestSuite::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("DateTimeTestSuite"); + + pSuite->addTest(TimestampTest::suite()); + pSuite->addTest(TimespanTest::suite()); + pSuite->addTest(TimezoneTest::suite()); + pSuite->addTest(DateTimeTest::suite()); + pSuite->addTest(LocalDateTimeTest::suite()); + pSuite->addTest(DateTimeFormatterTest::suite()); + pSuite->addTest(DateTimeParserTest::suite()); + + return pSuite; +} diff --git a/Foundation/testsuite/src/DateTimeTestSuite.h b/Foundation/testsuite/src/DateTimeTestSuite.h index fe3a5176a..7153ef4f8 100644 --- a/Foundation/testsuite/src/DateTimeTestSuite.h +++ b/Foundation/testsuite/src/DateTimeTestSuite.h @@ -1,49 +1,49 @@ -// -// DateTimeTestSuite.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/DateTimeTestSuite.h#1 $ -// -// Definition of the DateTimeTestSuite class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 DateTimeTestSuite_INCLUDED -#define DateTimeTestSuite_INCLUDED - - -#include "CppUnit/TestSuite.h" - - -class DateTimeTestSuite -{ -public: - static CppUnit::Test* suite(); -}; - - -#endif // DateTimeTestSuite_INCLUDED +// +// DateTimeTestSuite.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/DateTimeTestSuite.h#1 $ +// +// Definition of the DateTimeTestSuite class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 DateTimeTestSuite_INCLUDED +#define DateTimeTestSuite_INCLUDED + + +#include "CppUnit/TestSuite.h" + + +class DateTimeTestSuite +{ +public: + static CppUnit::Test* suite(); +}; + + +#endif // DateTimeTestSuite_INCLUDED diff --git a/Foundation/testsuite/src/DigestStreamTest.cpp b/Foundation/testsuite/src/DigestStreamTest.cpp index ecbecd30b..00f6fa577 100644 --- a/Foundation/testsuite/src/DigestStreamTest.cpp +++ b/Foundation/testsuite/src/DigestStreamTest.cpp @@ -1,115 +1,115 @@ -// -// DigestStreamTest.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/DigestStreamTest.cpp#1 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "DigestStreamTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/DigestStream.h" -#include "Poco/MD5Engine.h" -#include - - -using Poco::DigestInputStream; -using Poco::DigestOutputStream; -using Poco::DigestEngine; -using Poco::MD5Engine; - - -DigestStreamTest::DigestStreamTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -DigestStreamTest::~DigestStreamTest() -{ -} - - -void DigestStreamTest::testInputStream() -{ - std::istringstream istr("abcdefghijklmnopqrstuvwxyz"); - MD5Engine md5; - DigestInputStream ds(md5, istr); - std::string s; - ds >> s; - assert (DigestEngine::digestToHex(md5.digest()) == "c3fcd3d76192e4007dfb496cca67e13b"); - assert (s == "abcdefghijklmnopqrstuvwxyz"); -} - - -void DigestStreamTest::testOutputStream1() -{ - MD5Engine md5; - DigestOutputStream ds(md5); - ds << "abcdefghijklmnopqrstuvwxyz"; - ds.close(); - assert (DigestEngine::digestToHex(md5.digest()) == "c3fcd3d76192e4007dfb496cca67e13b"); - - ds << "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; - ds << "abcdefghijklmnopqrstuvwxyz0123456789"; - ds.close(); - assert (DigestEngine::digestToHex(md5.digest()) == "d174ab98d277d9f5a5611c2c9f419d9f"); -} - - -void DigestStreamTest::testOutputStream2() -{ - MD5Engine md5; - std::ostringstream ostr; - DigestOutputStream ds(md5, ostr); - ds << "abcdefghijklmnopqrstuvwxyz"; - ds.close(); - assert (DigestEngine::digestToHex(md5.digest()) == "c3fcd3d76192e4007dfb496cca67e13b"); - assert (ostr.str() == "abcdefghijklmnopqrstuvwxyz"); -} - - -void DigestStreamTest::setUp() -{ -} - - -void DigestStreamTest::tearDown() -{ -} - - -CppUnit::Test* DigestStreamTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("DigestStreamTest"); - - CppUnit_addTest(pSuite, DigestStreamTest, testInputStream); - CppUnit_addTest(pSuite, DigestStreamTest, testOutputStream1); - CppUnit_addTest(pSuite, DigestStreamTest, testOutputStream2); - - return pSuite; -} +// +// DigestStreamTest.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/DigestStreamTest.cpp#1 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "DigestStreamTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/DigestStream.h" +#include "Poco/MD5Engine.h" +#include + + +using Poco::DigestInputStream; +using Poco::DigestOutputStream; +using Poco::DigestEngine; +using Poco::MD5Engine; + + +DigestStreamTest::DigestStreamTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +DigestStreamTest::~DigestStreamTest() +{ +} + + +void DigestStreamTest::testInputStream() +{ + std::istringstream istr("abcdefghijklmnopqrstuvwxyz"); + MD5Engine md5; + DigestInputStream ds(md5, istr); + std::string s; + ds >> s; + assert (DigestEngine::digestToHex(md5.digest()) == "c3fcd3d76192e4007dfb496cca67e13b"); + assert (s == "abcdefghijklmnopqrstuvwxyz"); +} + + +void DigestStreamTest::testOutputStream1() +{ + MD5Engine md5; + DigestOutputStream ds(md5); + ds << "abcdefghijklmnopqrstuvwxyz"; + ds.close(); + assert (DigestEngine::digestToHex(md5.digest()) == "c3fcd3d76192e4007dfb496cca67e13b"); + + ds << "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + ds << "abcdefghijklmnopqrstuvwxyz0123456789"; + ds.close(); + assert (DigestEngine::digestToHex(md5.digest()) == "d174ab98d277d9f5a5611c2c9f419d9f"); +} + + +void DigestStreamTest::testOutputStream2() +{ + MD5Engine md5; + std::ostringstream ostr; + DigestOutputStream ds(md5, ostr); + ds << "abcdefghijklmnopqrstuvwxyz"; + ds.close(); + assert (DigestEngine::digestToHex(md5.digest()) == "c3fcd3d76192e4007dfb496cca67e13b"); + assert (ostr.str() == "abcdefghijklmnopqrstuvwxyz"); +} + + +void DigestStreamTest::setUp() +{ +} + + +void DigestStreamTest::tearDown() +{ +} + + +CppUnit::Test* DigestStreamTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("DigestStreamTest"); + + CppUnit_addTest(pSuite, DigestStreamTest, testInputStream); + CppUnit_addTest(pSuite, DigestStreamTest, testOutputStream1); + CppUnit_addTest(pSuite, DigestStreamTest, testOutputStream2); + + return pSuite; +} diff --git a/Foundation/testsuite/src/DigestStreamTest.h b/Foundation/testsuite/src/DigestStreamTest.h index eabcf2cb1..52fe1157d 100644 --- a/Foundation/testsuite/src/DigestStreamTest.h +++ b/Foundation/testsuite/src/DigestStreamTest.h @@ -1,62 +1,62 @@ -// -// DigestStreamTest.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/DigestStreamTest.h#1 $ -// -// Definition of the DigestStreamTest class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 DigestStreamTest_INCLUDED -#define DigestStreamTest_INCLUDED - - -#include "Poco/Foundation.h" -#include "CppUnit/TestCase.h" - - -class DigestStreamTest: public CppUnit::TestCase -{ -public: - DigestStreamTest(const std::string& name); - ~DigestStreamTest(); - - void testInputStream(); - void testOutputStream1(); - void testOutputStream2(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // DigestStreamTest_INCLUDED +// +// DigestStreamTest.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/DigestStreamTest.h#1 $ +// +// Definition of the DigestStreamTest class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 DigestStreamTest_INCLUDED +#define DigestStreamTest_INCLUDED + + +#include "Poco/Foundation.h" +#include "CppUnit/TestCase.h" + + +class DigestStreamTest: public CppUnit::TestCase +{ +public: + DigestStreamTest(const std::string& name); + ~DigestStreamTest(); + + void testInputStream(); + void testOutputStream1(); + void testOutputStream2(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // DigestStreamTest_INCLUDED diff --git a/Foundation/testsuite/src/Driver.cpp b/Foundation/testsuite/src/Driver.cpp index 5575cece5..3ec2fcd87 100644 --- a/Foundation/testsuite/src/Driver.cpp +++ b/Foundation/testsuite/src/Driver.cpp @@ -1,39 +1,39 @@ -// -// Driver.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/Driver.cpp#1 $ -// -// Console-based test driver. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "CppUnit/TestRunner.h" -#include "FoundationTestSuite.h" - - -CppUnitMain(FoundationTestSuite) +// +// Driver.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/Driver.cpp#1 $ +// +// Console-based test driver. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "CppUnit/TestRunner.h" +#include "FoundationTestSuite.h" + + +CppUnitMain(FoundationTestSuite) diff --git a/Foundation/testsuite/src/DummyDelegate.cpp b/Foundation/testsuite/src/DummyDelegate.cpp index 5405f4b3a..1225173cb 100644 --- a/Foundation/testsuite/src/DummyDelegate.cpp +++ b/Foundation/testsuite/src/DummyDelegate.cpp @@ -1,55 +1,55 @@ -// -// DummyDelegate.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/DummyDelegate.cpp#2 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "DummyDelegate.h" -#include "Poco/Exception.h" - -DummyDelegate::DummyDelegate() {} -DummyDelegate::~DummyDelegate() {} - -void DummyDelegate::onSimple(const void* pSender, int& i) -{ - if (i != 0) - { - throw Poco::InvalidArgumentException(); - } - i++; -} -void DummyDelegate::onSimple2(const void* pSender, int& i) -{ - if (i != 1) - { - throw Poco::InvalidArgumentException(); - } - i++; -} - +// +// DummyDelegate.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/DummyDelegate.cpp#2 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "DummyDelegate.h" +#include "Poco/Exception.h" + +DummyDelegate::DummyDelegate() {} +DummyDelegate::~DummyDelegate() {} + +void DummyDelegate::onSimple(const void* pSender, int& i) +{ + if (i != 0) + { + throw Poco::InvalidArgumentException(); + } + i++; +} +void DummyDelegate::onSimple2(const void* pSender, int& i) +{ + if (i != 1) + { + throw Poco::InvalidArgumentException(); + } + i++; +} + diff --git a/Foundation/testsuite/src/DummyDelegate.h b/Foundation/testsuite/src/DummyDelegate.h index d2f1f05c3..81ce35674 100644 --- a/Foundation/testsuite/src/DummyDelegate.h +++ b/Foundation/testsuite/src/DummyDelegate.h @@ -1,50 +1,50 @@ -// -// DummyDelegate.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/DummyDelegate.h#1 $ -// -// Definition of DummyDelegate class. -// -// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 DummyDelegate_INCLUDED -#define DummyDelegate_INCLUDED - - -class DummyDelegate -{ -public: - DummyDelegate(); - virtual ~DummyDelegate(); - - void onSimple(const void* pSender, int& i); - void onSimple2(const void* pSender, int& i); -}; - - -#endif // DummyDelegate_INCLUDED +// +// DummyDelegate.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/DummyDelegate.h#1 $ +// +// Definition of DummyDelegate class. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 DummyDelegate_INCLUDED +#define DummyDelegate_INCLUDED + + +class DummyDelegate +{ +public: + DummyDelegate(); + virtual ~DummyDelegate(); + + void onSimple(const void* pSender, int& i); + void onSimple2(const void* pSender, int& i); +}; + + +#endif // DummyDelegate_INCLUDED diff --git a/Foundation/testsuite/src/DynamicFactoryTest.cpp b/Foundation/testsuite/src/DynamicFactoryTest.cpp index aa6b0365b..1de097965 100644 --- a/Foundation/testsuite/src/DynamicFactoryTest.cpp +++ b/Foundation/testsuite/src/DynamicFactoryTest.cpp @@ -1,138 +1,138 @@ -// -// DynamicFactoryTest.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/DynamicFactoryTest.cpp#1 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "DynamicFactoryTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/DynamicFactory.h" -#include "Poco/Exception.h" -#include - - -using Poco::DynamicFactory; -using Poco::Instantiator; - - -namespace -{ - class Base - { - public: - Base() - { - } - - virtual ~Base() - { - } - }; - - class A: public Base - { - }; - - class B: public Base - { - }; -} - - -DynamicFactoryTest::DynamicFactoryTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -DynamicFactoryTest::~DynamicFactoryTest() -{ -} - - -void DynamicFactoryTest::testDynamicFactory() -{ - DynamicFactory dynFactory; - - dynFactory.registerClass("A"); - dynFactory.registerClass("B"); - - assert (dynFactory.isClass("A")); - assert (dynFactory.isClass("B")); - - assert (!dynFactory.isClass("C")); - - std::auto_ptr a(dynamic_cast(dynFactory.createInstance("A"))); - std::auto_ptr b(dynamic_cast(dynFactory.createInstance("B"))); - - assertNotNull(a.get()); - assertNotNull(b.get()); - - try - { - dynFactory.registerClass("A"); - fail("already registered - must throw"); - } - catch (Poco::ExistsException&) - { - } - - dynFactory.unregisterClass("B"); - assert (dynFactory.isClass("A")); - assert (!dynFactory.isClass("B")); - - try - { - std::auto_ptr b(dynamic_cast(dynFactory.createInstance("B"))); - fail("unregistered - must throw"); - } - catch (Poco::NotFoundException&) - { - } -} - - -void DynamicFactoryTest::setUp() -{ -} - - -void DynamicFactoryTest::tearDown() -{ -} - - -CppUnit::Test* DynamicFactoryTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("DynamicFactoryTest"); - - CppUnit_addTest(pSuite, DynamicFactoryTest, testDynamicFactory); - - return pSuite; -} +// +// DynamicFactoryTest.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/DynamicFactoryTest.cpp#1 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "DynamicFactoryTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/DynamicFactory.h" +#include "Poco/Exception.h" +#include + + +using Poco::DynamicFactory; +using Poco::Instantiator; + + +namespace +{ + class Base + { + public: + Base() + { + } + + virtual ~Base() + { + } + }; + + class A: public Base + { + }; + + class B: public Base + { + }; +} + + +DynamicFactoryTest::DynamicFactoryTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +DynamicFactoryTest::~DynamicFactoryTest() +{ +} + + +void DynamicFactoryTest::testDynamicFactory() +{ + DynamicFactory dynFactory; + + dynFactory.registerClass("A"); + dynFactory.registerClass("B"); + + assert (dynFactory.isClass("A")); + assert (dynFactory.isClass("B")); + + assert (!dynFactory.isClass("C")); + + std::auto_ptr a(dynamic_cast(dynFactory.createInstance("A"))); + std::auto_ptr b(dynamic_cast(dynFactory.createInstance("B"))); + + assertNotNull(a.get()); + assertNotNull(b.get()); + + try + { + dynFactory.registerClass("A"); + fail("already registered - must throw"); + } + catch (Poco::ExistsException&) + { + } + + dynFactory.unregisterClass("B"); + assert (dynFactory.isClass("A")); + assert (!dynFactory.isClass("B")); + + try + { + std::auto_ptr b(dynamic_cast(dynFactory.createInstance("B"))); + fail("unregistered - must throw"); + } + catch (Poco::NotFoundException&) + { + } +} + + +void DynamicFactoryTest::setUp() +{ +} + + +void DynamicFactoryTest::tearDown() +{ +} + + +CppUnit::Test* DynamicFactoryTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("DynamicFactoryTest"); + + CppUnit_addTest(pSuite, DynamicFactoryTest, testDynamicFactory); + + return pSuite; +} diff --git a/Foundation/testsuite/src/DynamicFactoryTest.h b/Foundation/testsuite/src/DynamicFactoryTest.h index 12c5e3338..fe552e7c8 100644 --- a/Foundation/testsuite/src/DynamicFactoryTest.h +++ b/Foundation/testsuite/src/DynamicFactoryTest.h @@ -1,60 +1,60 @@ -// -// DynamicFactoryTest.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/DynamicFactoryTest.h#1 $ -// -// Definition of the DynamicFactoryTest class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 DynamicFactoryTest_INCLUDED -#define DynamicFactoryTest_INCLUDED - - -#include "Poco/Foundation.h" -#include "CppUnit/TestCase.h" - - -class DynamicFactoryTest: public CppUnit::TestCase -{ -public: - DynamicFactoryTest(const std::string& name); - ~DynamicFactoryTest(); - - void testDynamicFactory(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // DynamicFactoryTest_INCLUDED +// +// DynamicFactoryTest.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/DynamicFactoryTest.h#1 $ +// +// Definition of the DynamicFactoryTest class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 DynamicFactoryTest_INCLUDED +#define DynamicFactoryTest_INCLUDED + + +#include "Poco/Foundation.h" +#include "CppUnit/TestCase.h" + + +class DynamicFactoryTest: public CppUnit::TestCase +{ +public: + DynamicFactoryTest(const std::string& name); + ~DynamicFactoryTest(); + + void testDynamicFactory(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // DynamicFactoryTest_INCLUDED diff --git a/Foundation/testsuite/src/EventTestSuite.cpp b/Foundation/testsuite/src/EventTestSuite.cpp index fd7a2f43d..27c38a1e7 100644 --- a/Foundation/testsuite/src/EventTestSuite.cpp +++ b/Foundation/testsuite/src/EventTestSuite.cpp @@ -1,47 +1,47 @@ -// -// EventTestSuite.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/EventTestSuite.cpp#1 $ -// -// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "EventTestSuite.h" -#include "FIFOEventTest.h" -#include "BasicEventTest.h" -#include "PriorityEventTest.h" - -CppUnit::Test* EventTestSuite::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("EventTestSuite"); - - pSuite->addTest(BasicEventTest::suite()); - pSuite->addTest(PriorityEventTest::suite()); - pSuite->addTest(FIFOEventTest::suite()); - - return pSuite; -} +// +// EventTestSuite.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/EventTestSuite.cpp#1 $ +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "EventTestSuite.h" +#include "FIFOEventTest.h" +#include "BasicEventTest.h" +#include "PriorityEventTest.h" + +CppUnit::Test* EventTestSuite::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("EventTestSuite"); + + pSuite->addTest(BasicEventTest::suite()); + pSuite->addTest(PriorityEventTest::suite()); + pSuite->addTest(FIFOEventTest::suite()); + + return pSuite; +} diff --git a/Foundation/testsuite/src/EventTestSuite.h b/Foundation/testsuite/src/EventTestSuite.h index 1cd4f4643..e73d12360 100644 --- a/Foundation/testsuite/src/EventTestSuite.h +++ b/Foundation/testsuite/src/EventTestSuite.h @@ -1,49 +1,49 @@ -// -// EventTestSuite.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/EventTestSuite.h#1 $ -// -// Definition of the EventTestSuite class. -// -// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 EventTestSuite_INCLUDED -#define EventTestSuite_INCLUDED - - -#include "CppUnit/TestSuite.h" - - -class EventTestSuite -{ -public: - static CppUnit::Test* suite(); -}; - - -#endif // EventTestSuite_INCLUDED +// +// EventTestSuite.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/EventTestSuite.h#1 $ +// +// Definition of the EventTestSuite class. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 EventTestSuite_INCLUDED +#define EventTestSuite_INCLUDED + + +#include "CppUnit/TestSuite.h" + + +class EventTestSuite +{ +public: + static CppUnit::Test* suite(); +}; + + +#endif // EventTestSuite_INCLUDED diff --git a/Foundation/testsuite/src/ExpireCacheTest.cpp b/Foundation/testsuite/src/ExpireCacheTest.cpp index 2bb6d05a9..92532f316 100644 --- a/Foundation/testsuite/src/ExpireCacheTest.cpp +++ b/Foundation/testsuite/src/ExpireCacheTest.cpp @@ -1,176 +1,176 @@ -// -// ExpireCacheTest.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/ExpireCacheTest.cpp#2 $ -// -// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "ExpireCacheTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/Exception.h" -#include "Poco/ExpireCache.h" -#include "Poco/Bugcheck.h" -#include "Poco/Thread.h" - - -using namespace Poco; - - -#define DURSLEEP 250 -#define DURHALFSLEEP DURSLEEP / 2 -#define DURWAIT 300 - - -ExpireCacheTest::ExpireCacheTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -ExpireCacheTest::~ExpireCacheTest() -{ -} - - -void ExpireCacheTest::testClear() -{ - ExpireCache aCache(DURSLEEP); - aCache.add(1, 2); - aCache.add(3, 4); - aCache.add(5, 6); - assert (aCache.has(1)); - assert (aCache.has(3)); - assert (aCache.has(5)); - assert (*aCache.get(1) == 2); - assert (*aCache.get(3) == 4); - assert (*aCache.get(5) == 6); - aCache.clear(); - assert (!aCache.has(1)); - assert (!aCache.has(3)); - assert (!aCache.has(5)); -} - - -void ExpireCacheTest::testExpire0() -{ - try - { - ExpireCache aCache(24); - failmsg("cache expire lower than 25 is illegal, test should fail"); - } - catch (Poco::InvalidArgumentException&) - { - } -} - - -void ExpireCacheTest::testExpireN() -{ - // 3-1 represents the cache sorted by age, elements get replaced at the end of the list - // 3-1|5 -> 5 gets removed - ExpireCache aCache(DURSLEEP); - aCache.add(1, 2); // 1 - assert (aCache.has(1)); - SharedPtr tmp = aCache.get(1); - assert (!tmp.isNull()); - assert (*tmp == 2); - Thread::sleep(DURWAIT); - assert (!aCache.has(1)); - - // tmp must still be valid, access it - assert (*tmp == 2); - tmp = aCache.get(1); - assert (!tmp); - - aCache.add(1, 2); // 1 - Thread::sleep(DURHALFSLEEP); - aCache.add(3, 4); // 3-1 - assert (aCache.has(1)); - assert (aCache.has(3)); - tmp = aCache.get(1); - SharedPtr tmp2 = aCache.get(3); - assert (*tmp == 2); - assert (*tmp2 == 4); - - Thread::sleep(DURHALFSLEEP+25); //3|1 - assert (!aCache.has(1)); - assert (aCache.has(3)); - assert (*tmp == 2); // 1-3 - assert (*tmp2 == 4); // 3-1 - tmp2 = aCache.get(3); - assert (*tmp2 == 4); - Thread::sleep(DURHALFSLEEP+25); //3|1 - assert (!aCache.has(3)); - assert (*tmp2 == 4); - tmp = aCache.get(1); - tmp2 = aCache.get(3); - assert (!tmp); - assert (!tmp2); - - // removing illegal entries should work too - aCache.remove(666); - - aCache.clear(); - assert (!aCache.has(5)); - assert (!aCache.has(3)); -} - - -void ExpireCacheTest::testDuplicateAdd() -{ - ExpireCache aCache(DURSLEEP); - aCache.add(1, 2); // 1 - assert (aCache.has(1)); - assert (*aCache.get(1) == 2); - aCache.add(1, 3); - assert (aCache.has(1)); - assert (*aCache.get(1) == 3); -} - - -void ExpireCacheTest::setUp() -{ -} - - -void ExpireCacheTest::tearDown() -{ -} - - -CppUnit::Test* ExpireCacheTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("ExpireCacheTest"); - - CppUnit_addTest(pSuite, ExpireCacheTest, testClear); - CppUnit_addTest(pSuite, ExpireCacheTest, testExpire0); - CppUnit_addTest(pSuite, ExpireCacheTest, testExpireN); - CppUnit_addTest(pSuite, ExpireCacheTest, testDuplicateAdd); - - return pSuite; -} +// +// ExpireCacheTest.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/ExpireCacheTest.cpp#2 $ +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "ExpireCacheTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/Exception.h" +#include "Poco/ExpireCache.h" +#include "Poco/Bugcheck.h" +#include "Poco/Thread.h" + + +using namespace Poco; + + +#define DURSLEEP 250 +#define DURHALFSLEEP DURSLEEP / 2 +#define DURWAIT 300 + + +ExpireCacheTest::ExpireCacheTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +ExpireCacheTest::~ExpireCacheTest() +{ +} + + +void ExpireCacheTest::testClear() +{ + ExpireCache aCache(DURSLEEP); + aCache.add(1, 2); + aCache.add(3, 4); + aCache.add(5, 6); + assert (aCache.has(1)); + assert (aCache.has(3)); + assert (aCache.has(5)); + assert (*aCache.get(1) == 2); + assert (*aCache.get(3) == 4); + assert (*aCache.get(5) == 6); + aCache.clear(); + assert (!aCache.has(1)); + assert (!aCache.has(3)); + assert (!aCache.has(5)); +} + + +void ExpireCacheTest::testExpire0() +{ + try + { + ExpireCache aCache(24); + failmsg("cache expire lower than 25 is illegal, test should fail"); + } + catch (Poco::InvalidArgumentException&) + { + } +} + + +void ExpireCacheTest::testExpireN() +{ + // 3-1 represents the cache sorted by age, elements get replaced at the end of the list + // 3-1|5 -> 5 gets removed + ExpireCache aCache(DURSLEEP); + aCache.add(1, 2); // 1 + assert (aCache.has(1)); + SharedPtr tmp = aCache.get(1); + assert (!tmp.isNull()); + assert (*tmp == 2); + Thread::sleep(DURWAIT); + assert (!aCache.has(1)); + + // tmp must still be valid, access it + assert (*tmp == 2); + tmp = aCache.get(1); + assert (!tmp); + + aCache.add(1, 2); // 1 + Thread::sleep(DURHALFSLEEP); + aCache.add(3, 4); // 3-1 + assert (aCache.has(1)); + assert (aCache.has(3)); + tmp = aCache.get(1); + SharedPtr tmp2 = aCache.get(3); + assert (*tmp == 2); + assert (*tmp2 == 4); + + Thread::sleep(DURHALFSLEEP+25); //3|1 + assert (!aCache.has(1)); + assert (aCache.has(3)); + assert (*tmp == 2); // 1-3 + assert (*tmp2 == 4); // 3-1 + tmp2 = aCache.get(3); + assert (*tmp2 == 4); + Thread::sleep(DURHALFSLEEP+25); //3|1 + assert (!aCache.has(3)); + assert (*tmp2 == 4); + tmp = aCache.get(1); + tmp2 = aCache.get(3); + assert (!tmp); + assert (!tmp2); + + // removing illegal entries should work too + aCache.remove(666); + + aCache.clear(); + assert (!aCache.has(5)); + assert (!aCache.has(3)); +} + + +void ExpireCacheTest::testDuplicateAdd() +{ + ExpireCache aCache(DURSLEEP); + aCache.add(1, 2); // 1 + assert (aCache.has(1)); + assert (*aCache.get(1) == 2); + aCache.add(1, 3); + assert (aCache.has(1)); + assert (*aCache.get(1) == 3); +} + + +void ExpireCacheTest::setUp() +{ +} + + +void ExpireCacheTest::tearDown() +{ +} + + +CppUnit::Test* ExpireCacheTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("ExpireCacheTest"); + + CppUnit_addTest(pSuite, ExpireCacheTest, testClear); + CppUnit_addTest(pSuite, ExpireCacheTest, testExpire0); + CppUnit_addTest(pSuite, ExpireCacheTest, testExpireN); + CppUnit_addTest(pSuite, ExpireCacheTest, testDuplicateAdd); + + return pSuite; +} diff --git a/Foundation/testsuite/src/ExpireCacheTest.h b/Foundation/testsuite/src/ExpireCacheTest.h index 22a70546d..854423274 100644 --- a/Foundation/testsuite/src/ExpireCacheTest.h +++ b/Foundation/testsuite/src/ExpireCacheTest.h @@ -1,60 +1,60 @@ -// -// ExpireCacheTest.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/ExpireCacheTest.h#1 $ -// -// Tests for ExpireCache -// -// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 ExpireCacheTest_INCLUDED -#define ExpireCacheTest_INCLUDED - - -#include "Poco/Foundation.h" -#include "CppUnit/TestCase.h" - - -class ExpireCacheTest: public CppUnit::TestCase -{ -public: - ExpireCacheTest(const std::string& name); - ~ExpireCacheTest(); - - void testClear(); - void testDuplicateAdd(); - void testExpire0(); - void testExpireN(); - - - void setUp(); - void tearDown(); - static CppUnit::Test* suite(); -}; - - -#endif // ExpireCacheTest_INCLUDED +// +// ExpireCacheTest.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/ExpireCacheTest.h#1 $ +// +// Tests for ExpireCache +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 ExpireCacheTest_INCLUDED +#define ExpireCacheTest_INCLUDED + + +#include "Poco/Foundation.h" +#include "CppUnit/TestCase.h" + + +class ExpireCacheTest: public CppUnit::TestCase +{ +public: + ExpireCacheTest(const std::string& name); + ~ExpireCacheTest(); + + void testClear(); + void testDuplicateAdd(); + void testExpire0(); + void testExpireN(); + + + void setUp(); + void tearDown(); + static CppUnit::Test* suite(); +}; + + +#endif // ExpireCacheTest_INCLUDED diff --git a/Foundation/testsuite/src/ExpireLRUCacheTest.cpp b/Foundation/testsuite/src/ExpireLRUCacheTest.cpp index 2473578ba..28c43f760 100644 --- a/Foundation/testsuite/src/ExpireLRUCacheTest.cpp +++ b/Foundation/testsuite/src/ExpireLRUCacheTest.cpp @@ -1,311 +1,311 @@ -// -// ExpireLRUCacheTest.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/ExpireLRUCacheTest.cpp#2 $ -// -// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "ExpireLRUCacheTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/Exception.h" -#include "Poco/ExpireLRUCache.h" -#include "Poco/Bugcheck.h" -#include "Poco/Thread.h" - - -using namespace Poco; - - -#define DURSLEEP 250 -#define DURHALFSLEEP DURSLEEP / 2 -#define DURWAIT 300 - - -ExpireLRUCacheTest::ExpireLRUCacheTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -ExpireLRUCacheTest::~ExpireLRUCacheTest() -{ -} - - -void ExpireLRUCacheTest::testClear() -{ - ExpireLRUCache aCache(DURSLEEP); - aCache.add(1, 2); - aCache.add(3, 4); - aCache.add(5, 6); - assert (aCache.has(1)); - assert (aCache.has(3)); - assert (aCache.has(5)); - assert (*aCache.get(1) == 2); - assert (*aCache.get(3) == 4); - assert (*aCache.get(5) == 6); - aCache.clear(); - assert (!aCache.has(1)); - assert (!aCache.has(3)); - assert (!aCache.has(5)); -} - - -void ExpireLRUCacheTest::testExpire0() -{ - try - { - ExpireLRUCache aCache(1024, 24); - failmsg("cache expire lower than 25 is illegal, test should fail"); - } - catch (Poco::InvalidArgumentException&) - { - } -} - - -void ExpireLRUCacheTest::testExpireN() -{ - // 3-1 represents the cache sorted by age, elements get replaced at the end of the list - // 3-1|5 -> 5 gets removed - ExpireLRUCache aCache(3, DURSLEEP); - aCache.add(1, 2); // 1 - assert (aCache.has(1)); - SharedPtr tmp = aCache.get(1); - assert (!tmp.isNull()); - assert (*tmp == 2); - Thread::sleep(DURWAIT); - assert (!aCache.has(1)); - - // tmp must still be valid, access it - assert (*tmp == 2); - tmp = aCache.get(1); - assert (!tmp); - - aCache.add(1, 2); // 1 - Thread::sleep(DURHALFSLEEP); - aCache.add(3, 4); // 3-1 - assert (aCache.has(1)); - assert (aCache.has(3)); - tmp = aCache.get(1); - SharedPtr tmp2 = aCache.get(3); - assert (*tmp == 2); - assert (*tmp2 == 4); - - Thread::sleep(DURHALFSLEEP+25); //3|1 - assert (!aCache.has(1)); - assert (aCache.has(3)); - assert (*tmp == 2); // 1-3 - assert (*tmp2 == 4); // 3-1 - tmp2 = aCache.get(3); - assert (*tmp2 == 4); - Thread::sleep(DURHALFSLEEP+25); //3|1 - assert (!aCache.has(3)); - assert (*tmp2 == 4); - tmp = aCache.get(1); - tmp2 = aCache.get(3); - assert (!tmp); - assert (!tmp2); - - // removing illegal entries should work too - aCache.remove(666); - - aCache.clear(); - assert (!aCache.has(5)); - assert (!aCache.has(3)); -} - - -void ExpireLRUCacheTest::testCacheSize0() -{ - // cache size 0 is illegal - try - { - ExpireLRUCache aCache(0); - failmsg ("cache size of 0 is illegal, test should fail"); - } - catch (Poco::InvalidArgumentException&) - { - } -} - - -void ExpireLRUCacheTest::testCacheSize1() -{ - ExpireLRUCache aCache(1); - aCache.add(1, 2); - assert (aCache.has(1)); - assert (*aCache.get(1) == 2); - - aCache.add(3, 4); // replaces 1 - assert (!aCache.has(1)); - assert (aCache.has(3)); - assert (*aCache.get(3) == 4); - - aCache.add(5, 6); - assert (!aCache.has(1)); - assert (!aCache.has(3)); - assert (aCache.has(5)); - assert (*aCache.get(5) == 6); - - aCache.remove(5); - assert (!aCache.has(5)); - - // removing illegal entries should work too - aCache.remove(666); -} - - -void ExpireLRUCacheTest::testCacheSize2() -{ - // 3-1 represents the cache sorted by pos, elements get replaced at the end of the list - // 3-1|5 -> 5 gets removed - ExpireLRUCache aCache(2); - aCache.add(1, 2); // 1 - assert (aCache.has(1)); - assert (*aCache.get(1) == 2); - - aCache.add(3, 4); // 3-1 - assert (aCache.has(1)); - assert (aCache.has(3)); - assert (*aCache.get(1) == 2); // 1-3 - assert (*aCache.get(3) == 4); // 3-1 - - aCache.add(5, 6); // 5-3|1 - assert (!aCache.has(1)); - assert (aCache.has(3)); - assert (aCache.has(5)); - assert (*aCache.get(5) == 6); // 5-3 - assert (*aCache.get(3) == 4); // 3-5 - - // test remove from the end and the beginning of the list - aCache.remove(5); // 3 - assert (!aCache.has(5)); - assert (*aCache.get(3) == 4); // 3 - aCache.add(5, 6); // 5-3 - assert (*aCache.get(3) == 4); // 3-5 - aCache.remove(3); // 5 - assert (!aCache.has(3)); - assert (*aCache.get(5) == 6); // 5 - - // removing illegal entries should work too - aCache.remove(666); - - aCache.clear(); - assert (!aCache.has(5)); -} - - -void ExpireLRUCacheTest::testCacheSizeN() -{ - // 3-1 represents the cache sorted by pos, elements get replaced at the end of the list - // 3-1|5 -> 5 gets removed - ExpireLRUCache aCache(3); - aCache.add(1, 2); // 1 - assert (aCache.has(1)); - assert (*aCache.get(1) == 2); - - aCache.add(3, 4); // 3-1 - assert (aCache.has(1)); - assert (aCache.has(3)); - assert (*aCache.get(1) == 2); // 1-3 - assert (*aCache.get(3) == 4); // 3-1 - - aCache.add(5, 6); // 5-3-1 - assert (aCache.has(1)); - assert (aCache.has(3)); - assert (aCache.has(5)); - assert (*aCache.get(5) == 6); // 5-3-1 - assert (*aCache.get(3) == 4); // 3-5-1 - - aCache.add(7, 8); // 7-5-3|1 - assert (!aCache.has(1)); - assert (aCache.has(7)); - assert (aCache.has(3)); - assert (aCache.has(5)); - assert (*aCache.get(5) == 6); // 5-7-3 - assert (*aCache.get(3) == 4); // 3-5-7 - assert (*aCache.get(7) == 8); // 7-3-5 - - // test remove from the end and the beginning of the list - aCache.remove(5); // 7-3 - assert (!aCache.has(5)); - assert (*aCache.get(3) == 4); // 3-7 - aCache.add(5, 6); // 5-3-7 - assert (*aCache.get(7) == 8); // 7-5-3 - aCache.remove(7); // 5-3 - assert (!aCache.has(7)); - assert (aCache.has(3)); - assert (*aCache.get(5) == 6); // 5-3 - - // removing illegal entries should work too - aCache.remove(666); - - aCache.clear(); - assert (!aCache.has(5)); - assert (!aCache.has(3)); -} - - -void ExpireLRUCacheTest::testDuplicateAdd() -{ - ExpireLRUCache aCache(3); - aCache.add(1, 2); // 1 - assert (aCache.has(1)); - assert (*aCache.get(1) == 2); - aCache.add(1, 3); - assert (aCache.has(1)); - assert (*aCache.get(1) == 3); -} - - -void ExpireLRUCacheTest::setUp() -{ -} - - -void ExpireLRUCacheTest::tearDown() -{ -} - - -CppUnit::Test* ExpireLRUCacheTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("ExpireLRUCacheTest"); - - CppUnit_addTest(pSuite, ExpireLRUCacheTest, testClear); - CppUnit_addTest(pSuite, ExpireLRUCacheTest, testExpire0); - CppUnit_addTest(pSuite, ExpireLRUCacheTest, testExpireN); - CppUnit_addTest(pSuite, ExpireLRUCacheTest, testCacheSize0); - CppUnit_addTest(pSuite, ExpireLRUCacheTest, testCacheSize1); - CppUnit_addTest(pSuite, ExpireLRUCacheTest, testCacheSize2); - CppUnit_addTest(pSuite, ExpireLRUCacheTest, testCacheSizeN); - CppUnit_addTest(pSuite, ExpireLRUCacheTest, testDuplicateAdd); - - return pSuite; -} +// +// ExpireLRUCacheTest.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/ExpireLRUCacheTest.cpp#2 $ +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "ExpireLRUCacheTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/Exception.h" +#include "Poco/ExpireLRUCache.h" +#include "Poco/Bugcheck.h" +#include "Poco/Thread.h" + + +using namespace Poco; + + +#define DURSLEEP 250 +#define DURHALFSLEEP DURSLEEP / 2 +#define DURWAIT 300 + + +ExpireLRUCacheTest::ExpireLRUCacheTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +ExpireLRUCacheTest::~ExpireLRUCacheTest() +{ +} + + +void ExpireLRUCacheTest::testClear() +{ + ExpireLRUCache aCache(DURSLEEP); + aCache.add(1, 2); + aCache.add(3, 4); + aCache.add(5, 6); + assert (aCache.has(1)); + assert (aCache.has(3)); + assert (aCache.has(5)); + assert (*aCache.get(1) == 2); + assert (*aCache.get(3) == 4); + assert (*aCache.get(5) == 6); + aCache.clear(); + assert (!aCache.has(1)); + assert (!aCache.has(3)); + assert (!aCache.has(5)); +} + + +void ExpireLRUCacheTest::testExpire0() +{ + try + { + ExpireLRUCache aCache(1024, 24); + failmsg("cache expire lower than 25 is illegal, test should fail"); + } + catch (Poco::InvalidArgumentException&) + { + } +} + + +void ExpireLRUCacheTest::testExpireN() +{ + // 3-1 represents the cache sorted by age, elements get replaced at the end of the list + // 3-1|5 -> 5 gets removed + ExpireLRUCache aCache(3, DURSLEEP); + aCache.add(1, 2); // 1 + assert (aCache.has(1)); + SharedPtr tmp = aCache.get(1); + assert (!tmp.isNull()); + assert (*tmp == 2); + Thread::sleep(DURWAIT); + assert (!aCache.has(1)); + + // tmp must still be valid, access it + assert (*tmp == 2); + tmp = aCache.get(1); + assert (!tmp); + + aCache.add(1, 2); // 1 + Thread::sleep(DURHALFSLEEP); + aCache.add(3, 4); // 3-1 + assert (aCache.has(1)); + assert (aCache.has(3)); + tmp = aCache.get(1); + SharedPtr tmp2 = aCache.get(3); + assert (*tmp == 2); + assert (*tmp2 == 4); + + Thread::sleep(DURHALFSLEEP+25); //3|1 + assert (!aCache.has(1)); + assert (aCache.has(3)); + assert (*tmp == 2); // 1-3 + assert (*tmp2 == 4); // 3-1 + tmp2 = aCache.get(3); + assert (*tmp2 == 4); + Thread::sleep(DURHALFSLEEP+25); //3|1 + assert (!aCache.has(3)); + assert (*tmp2 == 4); + tmp = aCache.get(1); + tmp2 = aCache.get(3); + assert (!tmp); + assert (!tmp2); + + // removing illegal entries should work too + aCache.remove(666); + + aCache.clear(); + assert (!aCache.has(5)); + assert (!aCache.has(3)); +} + + +void ExpireLRUCacheTest::testCacheSize0() +{ + // cache size 0 is illegal + try + { + ExpireLRUCache aCache(0); + failmsg ("cache size of 0 is illegal, test should fail"); + } + catch (Poco::InvalidArgumentException&) + { + } +} + + +void ExpireLRUCacheTest::testCacheSize1() +{ + ExpireLRUCache aCache(1); + aCache.add(1, 2); + assert (aCache.has(1)); + assert (*aCache.get(1) == 2); + + aCache.add(3, 4); // replaces 1 + assert (!aCache.has(1)); + assert (aCache.has(3)); + assert (*aCache.get(3) == 4); + + aCache.add(5, 6); + assert (!aCache.has(1)); + assert (!aCache.has(3)); + assert (aCache.has(5)); + assert (*aCache.get(5) == 6); + + aCache.remove(5); + assert (!aCache.has(5)); + + // removing illegal entries should work too + aCache.remove(666); +} + + +void ExpireLRUCacheTest::testCacheSize2() +{ + // 3-1 represents the cache sorted by pos, elements get replaced at the end of the list + // 3-1|5 -> 5 gets removed + ExpireLRUCache aCache(2); + aCache.add(1, 2); // 1 + assert (aCache.has(1)); + assert (*aCache.get(1) == 2); + + aCache.add(3, 4); // 3-1 + assert (aCache.has(1)); + assert (aCache.has(3)); + assert (*aCache.get(1) == 2); // 1-3 + assert (*aCache.get(3) == 4); // 3-1 + + aCache.add(5, 6); // 5-3|1 + assert (!aCache.has(1)); + assert (aCache.has(3)); + assert (aCache.has(5)); + assert (*aCache.get(5) == 6); // 5-3 + assert (*aCache.get(3) == 4); // 3-5 + + // test remove from the end and the beginning of the list + aCache.remove(5); // 3 + assert (!aCache.has(5)); + assert (*aCache.get(3) == 4); // 3 + aCache.add(5, 6); // 5-3 + assert (*aCache.get(3) == 4); // 3-5 + aCache.remove(3); // 5 + assert (!aCache.has(3)); + assert (*aCache.get(5) == 6); // 5 + + // removing illegal entries should work too + aCache.remove(666); + + aCache.clear(); + assert (!aCache.has(5)); +} + + +void ExpireLRUCacheTest::testCacheSizeN() +{ + // 3-1 represents the cache sorted by pos, elements get replaced at the end of the list + // 3-1|5 -> 5 gets removed + ExpireLRUCache aCache(3); + aCache.add(1, 2); // 1 + assert (aCache.has(1)); + assert (*aCache.get(1) == 2); + + aCache.add(3, 4); // 3-1 + assert (aCache.has(1)); + assert (aCache.has(3)); + assert (*aCache.get(1) == 2); // 1-3 + assert (*aCache.get(3) == 4); // 3-1 + + aCache.add(5, 6); // 5-3-1 + assert (aCache.has(1)); + assert (aCache.has(3)); + assert (aCache.has(5)); + assert (*aCache.get(5) == 6); // 5-3-1 + assert (*aCache.get(3) == 4); // 3-5-1 + + aCache.add(7, 8); // 7-5-3|1 + assert (!aCache.has(1)); + assert (aCache.has(7)); + assert (aCache.has(3)); + assert (aCache.has(5)); + assert (*aCache.get(5) == 6); // 5-7-3 + assert (*aCache.get(3) == 4); // 3-5-7 + assert (*aCache.get(7) == 8); // 7-3-5 + + // test remove from the end and the beginning of the list + aCache.remove(5); // 7-3 + assert (!aCache.has(5)); + assert (*aCache.get(3) == 4); // 3-7 + aCache.add(5, 6); // 5-3-7 + assert (*aCache.get(7) == 8); // 7-5-3 + aCache.remove(7); // 5-3 + assert (!aCache.has(7)); + assert (aCache.has(3)); + assert (*aCache.get(5) == 6); // 5-3 + + // removing illegal entries should work too + aCache.remove(666); + + aCache.clear(); + assert (!aCache.has(5)); + assert (!aCache.has(3)); +} + + +void ExpireLRUCacheTest::testDuplicateAdd() +{ + ExpireLRUCache aCache(3); + aCache.add(1, 2); // 1 + assert (aCache.has(1)); + assert (*aCache.get(1) == 2); + aCache.add(1, 3); + assert (aCache.has(1)); + assert (*aCache.get(1) == 3); +} + + +void ExpireLRUCacheTest::setUp() +{ +} + + +void ExpireLRUCacheTest::tearDown() +{ +} + + +CppUnit::Test* ExpireLRUCacheTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("ExpireLRUCacheTest"); + + CppUnit_addTest(pSuite, ExpireLRUCacheTest, testClear); + CppUnit_addTest(pSuite, ExpireLRUCacheTest, testExpire0); + CppUnit_addTest(pSuite, ExpireLRUCacheTest, testExpireN); + CppUnit_addTest(pSuite, ExpireLRUCacheTest, testCacheSize0); + CppUnit_addTest(pSuite, ExpireLRUCacheTest, testCacheSize1); + CppUnit_addTest(pSuite, ExpireLRUCacheTest, testCacheSize2); + CppUnit_addTest(pSuite, ExpireLRUCacheTest, testCacheSizeN); + CppUnit_addTest(pSuite, ExpireLRUCacheTest, testDuplicateAdd); + + return pSuite; +} diff --git a/Foundation/testsuite/src/ExpireLRUCacheTest.h b/Foundation/testsuite/src/ExpireLRUCacheTest.h index 279874815..0a3e6fae3 100644 --- a/Foundation/testsuite/src/ExpireLRUCacheTest.h +++ b/Foundation/testsuite/src/ExpireLRUCacheTest.h @@ -1,63 +1,63 @@ -// -// ExpireLRUCacheTest.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/ExpireLRUCacheTest.h#1 $ -// -// Tests for ExpireLRUCache -// -// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 ExpireLRUCacheTest_INCLUDED -#define ExpireLRUCacheTest_INCLUDED - - -#include "Poco/Foundation.h" -#include "CppUnit/TestCase.h" - - -class ExpireLRUCacheTest: public CppUnit::TestCase -{ -public: - ExpireLRUCacheTest(const std::string& name); - ~ExpireLRUCacheTest(); - - void testClear(); - void testExpire0(); - void testExpireN(); - void testCacheSize0(); - void testCacheSize1(); - void testCacheSize2(); - void testCacheSizeN(); - void testDuplicateAdd(); - - void setUp(); - void tearDown(); - static CppUnit::Test* suite(); -}; - - -#endif // ExpireLRUCacheTest_INCLUDED +// +// ExpireLRUCacheTest.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/ExpireLRUCacheTest.h#1 $ +// +// Tests for ExpireLRUCache +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 ExpireLRUCacheTest_INCLUDED +#define ExpireLRUCacheTest_INCLUDED + + +#include "Poco/Foundation.h" +#include "CppUnit/TestCase.h" + + +class ExpireLRUCacheTest: public CppUnit::TestCase +{ +public: + ExpireLRUCacheTest(const std::string& name); + ~ExpireLRUCacheTest(); + + void testClear(); + void testExpire0(); + void testExpireN(); + void testCacheSize0(); + void testCacheSize1(); + void testCacheSize2(); + void testCacheSizeN(); + void testDuplicateAdd(); + + void setUp(); + void tearDown(); + static CppUnit::Test* suite(); +}; + + +#endif // ExpireLRUCacheTest_INCLUDED diff --git a/Foundation/testsuite/src/FIFOEventTest.cpp b/Foundation/testsuite/src/FIFOEventTest.cpp index cef21e410..0ee776998 100644 --- a/Foundation/testsuite/src/FIFOEventTest.cpp +++ b/Foundation/testsuite/src/FIFOEventTest.cpp @@ -1,444 +1,444 @@ -// -// FIFOEventTest.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/FIFOEventTest.cpp#2 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "FIFOEventTest.h" -#include "DummyDelegate.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/Delegate.h" -#include "Poco/Expire.h" -#include "Poco/Thread.h" -#include "Poco/Exception.h" - - -using namespace Poco; - - -#define LARGEINC 100 - - -FIFOEventTest::FIFOEventTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -FIFOEventTest::~FIFOEventTest() -{ -} - -void FIFOEventTest::testNoDelegate() -{ - int tmp = 0; - EventArgs args; - - assert (_count == 0); - Simple.notify(this, tmp); - assert (_count == 0); - - Simple += Delegate(this, &FIFOEventTest::onSimple); - Simple -= Delegate(this, &FIFOEventTest::onSimple); - Simple.notify(this, tmp); - assert (_count == 0); - - ConstSimple += Delegate(this, &FIFOEventTest::onConstSimple); - ConstSimple -= Delegate(this, &FIFOEventTest::onConstSimple); - ConstSimple.notify(this, tmp); - assert (_count == 0); - - //Note: passing &args will not work due to & - EventArgs* pArgs = &args; - Complex += Delegate(this, &FIFOEventTest::onComplex); - Complex -= Delegate(this, &FIFOEventTest::onComplex); - Complex.notify(this, pArgs); - assert (_count == 0); - - Complex2 += Delegate(this, &FIFOEventTest::onComplex2); - Complex2 -= Delegate(this, &FIFOEventTest::onComplex2); - Complex2.notify(this, args); - assert (_count == 0); - - const EventArgs* pCArgs = &args; - ConstComplex += Delegate(this, &FIFOEventTest::onConstComplex); - ConstComplex -= Delegate(this, &FIFOEventTest::onConstComplex); - ConstComplex.notify(this, pCArgs); - assert (_count == 0); - - Const2Complex += Delegate(this, &FIFOEventTest::onConst2Complex); - Const2Complex -= Delegate(this, &FIFOEventTest::onConst2Complex); - Const2Complex.notify(this, pArgs); - assert (_count == 0); -} - -void FIFOEventTest::testSingleDelegate() -{ - int tmp = 0; - EventArgs args; - - assert (_count == 0); - - Simple += Delegate(this, &FIFOEventTest::onSimple); - Simple.notify(this, tmp); - assert (_count == 1); - - ConstSimple += Delegate(this, &FIFOEventTest::onConstSimple); - ConstSimple.notify(this, tmp); - assert (_count == 2); - - EventArgs* pArgs = &args; - Complex += Delegate(this, &FIFOEventTest::onComplex); - Complex.notify(this, pArgs); - assert (_count == 3); - - Complex2 += Delegate(this, &FIFOEventTest::onComplex2); - Complex2.notify(this, args); - assert (_count == 4); - - const EventArgs* pCArgs = &args; - ConstComplex += Delegate(this, &FIFOEventTest::onConstComplex); - ConstComplex.notify(this, pCArgs); - assert (_count == 5); - - Const2Complex += Delegate(this, &FIFOEventTest::onConst2Complex); - Const2Complex.notify(this, pArgs); - assert (_count == 6); - // check if 2nd notify also works - Const2Complex.notify(this, pArgs); - assert (_count == 7); - -} - -void FIFOEventTest::testDuplicateRegister() -{ - int tmp = 0; - - assert (_count == 0); - - Simple += Delegate(this, &FIFOEventTest::onSimple); - Simple += Delegate(this, &FIFOEventTest::onSimple); - Simple.notify(this, tmp); - assert (_count == 1); - Simple -= Delegate(this, &FIFOEventTest::onSimple); - Simple.notify(this, tmp); - assert (_count == 1); -} - -void FIFOEventTest::testDuplicateUnregister() -{ - // duplicate unregister shouldn't give an error, - int tmp = 0; - - assert (_count == 0); - - Simple -= Delegate(this, &FIFOEventTest::onSimple); // should work - Simple.notify(this, tmp); - assert (_count == 0); - - Simple += Delegate(this, &FIFOEventTest::onSimple); - Simple.notify(this, tmp); - assert (_count == 1); - - Simple -= Delegate(this, &FIFOEventTest::onSimple); - Simple.notify(this, tmp); - assert (_count == 1); - - Simple -= Delegate(this, &FIFOEventTest::onSimple); - Simple.notify(this, tmp); - assert (_count == 1); -} - - -void FIFOEventTest::testDisabling() -{ - int tmp = 0; - - assert (_count == 0); - - Simple += Delegate(this, &FIFOEventTest::onSimple); - Simple.disable(); - Simple.notify(this, tmp); - assert (_count == 0); - Simple.enable(); - Simple.notify(this, tmp); - assert (_count == 1); - - // unregister should also work with disabled event - Simple.disable(); - Simple -= Delegate(this, &FIFOEventTest::onSimple); - Simple.enable(); - Simple.notify(this, tmp); - assert (_count == 1); -} - -void FIFOEventTest::testFIFOOrder() -{ - DummyDelegate o1; - DummyDelegate o2; - - assert (_count == 0); - - Simple += Delegate(&o1, &DummyDelegate::onSimple); - Simple += Delegate(&o2, &DummyDelegate::onSimple2); - int tmp = 0; - Simple.notify(this, tmp); - assert (tmp == 2); - - Simple -= Delegate(&o1, &DummyDelegate::onSimple); - Simple -= Delegate(&o2, &DummyDelegate::onSimple2); - - // now try with the wrong order - Simple += Delegate(&o2, &DummyDelegate::onSimple2); - Simple += Delegate(&o1, &DummyDelegate::onSimple); - - try - { - tmp = 0; - Simple.notify(this, tmp); - failmsg ("Notify should not work"); - } - catch (Poco::InvalidArgumentException&) - { - } -} - -void FIFOEventTest::testFIFOOrderExpire() -{ - // expire must not break order! - DummyDelegate o1; - DummyDelegate o2; - - assert (_count == 0); - - Simple += Expire(Delegate(&o1, &DummyDelegate::onSimple), 5000); - Simple += Expire(Delegate(&o2, &DummyDelegate::onSimple2), 5000); - int tmp = 0; - Simple.notify(this, tmp); - assert (tmp == 2); - - // both ways of unregistering should work - Simple -= Expire(Delegate(&o1, &DummyDelegate::onSimple), 6000); - Simple -= Delegate(&o2, &DummyDelegate::onSimple2); - Simple.notify(this, tmp); - assert (tmp == 2); - - // now start mixing of expire and non expire - tmp = 0; - Simple += Delegate(&o1, &DummyDelegate::onSimple); - Simple += Expire(Delegate(&o2, &DummyDelegate::onSimple2), 5000); - Simple.notify(this, tmp); - assert (tmp == 2); - - Simple -= Delegate(&o2, &DummyDelegate::onSimple2); - // it is not forbidden to unregister a non expiring event with an expire decorator (it is just stupid ;-)) - Simple -= Expire(Delegate(&o1, &DummyDelegate::onSimple), 6000); - Simple.notify(this, tmp); - assert (tmp == 2); - - // now try with the wrong order - Simple += Expire(Delegate(&o2, &DummyDelegate::onSimple2), 5000); - Simple += Delegate(&o1, &DummyDelegate::onSimple); - - try - { - tmp = 0; - Simple.notify(this, tmp); - failmsg ("Notify should not work"); - } - catch (Poco::InvalidArgumentException&) - { - - } - -} - -void FIFOEventTest::testExpire() -{ - int tmp = 0; - - assert (_count == 0); - - Simple += Expire(Delegate(this, &FIFOEventTest::onSimple), 500); - Simple.notify(this, tmp); - assert (_count == 1); - Poco::Thread::sleep(700); - Simple.notify(this, tmp); - assert (_count == 1); -} - - -void FIFOEventTest::testExpireReRegister() -{ - int tmp = 0; - - assert (_count == 0); - - Simple += Expire(Delegate(this, &FIFOEventTest::onSimple), 500); - Simple.notify(this, tmp); - assert (_count == 1); - Poco::Thread::sleep(200); - Simple.notify(this, tmp); - assert (_count == 2); - // renew registration - Simple += Expire(Delegate(this, &FIFOEventTest::onSimple), 600); - Poco::Thread::sleep(400); - Simple.notify(this, tmp); - assert (_count == 3); - Poco::Thread::sleep(300); - Simple.notify(this, tmp); - assert (_count == 3); -} - - -void FIFOEventTest::testReturnParams() -{ - DummyDelegate o1; - Simple += Delegate(&o1, &DummyDelegate::onSimple); - - int tmp = 0; - Simple.notify(this, tmp); - assert (tmp == 1); -} - -void FIFOEventTest::testOverwriteDelegate() -{ - DummyDelegate o1; - Simple += Delegate(&o1, &DummyDelegate::onSimple2); - // o1 can only have one entry, thus the next line will replace the entry - Simple += Delegate(&o1, &DummyDelegate::onSimple); - - int tmp = 0; // onsimple requires 0 as input - Simple.notify(this, tmp); - assert (tmp == 1); - // now overwrite with onsimple2 with requires as input tmp = 1 - Simple += Expire(Delegate(&o1, &DummyDelegate::onSimple2), 23000); - Simple.notify(this, tmp); - assert (tmp == 2); -} - -void FIFOEventTest::testAsyncNotify() -{ - Poco::FIFOEvent* pSimple= new Poco::FIFOEvent(); - (*pSimple) += Delegate(this, &FIFOEventTest::onAsync); - assert (_count == 0); - int tmp = 0; - Poco::ActiveResultretArg = pSimple->notifyAsync(this, tmp); - delete pSimple; // must work even when the event got deleted! - pSimple = NULL; - assert (_count == 0); - retArg.wait(); - assert (retArg.data() == tmp); - assert (_count == LARGEINC); -} - -void FIFOEventTest::onSimple(const void* pSender, int& i) -{ - _count++; -} - -void FIFOEventTest::onSimpleOther(const void* pSender, int& i) -{ - _count+=100; -} - -void FIFOEventTest::onConstSimple(const void* pSender, const int& i) -{ - _count++; -} - -void FIFOEventTest::onComplex(const void* pSender, Poco::EventArgs* & i) -{ - _count++; -} - -void FIFOEventTest::onComplex2(const void* pSender, Poco::EventArgs & i) -{ - _count++; -} - -void FIFOEventTest::onConstComplex(const void* pSender, const Poco::EventArgs*& i) -{ - _count++; -} - -void FIFOEventTest::onConst2Complex(const void* pSender, const Poco::EventArgs * const & i) -{ - _count++; -} - -void FIFOEventTest::onAsync(const void* pSender, int& i) -{ - Poco::Thread::sleep(700); - _count += LARGEINC ; -} - -int FIFOEventTest::getCount() const -{ - return _count; -} - -void FIFOEventTest::setUp() -{ - _count = 0; - // must clear events, otherwise repeating test executions will fail - // because tests are only created once, only setup is called before - // each test run - Simple.clear(); - ConstSimple.clear(); - Complex.clear(); - Complex2.clear(); - ConstComplex.clear(); - Const2Complex.clear(); -} - - -void FIFOEventTest::tearDown() -{ -} - - -CppUnit::Test* FIFOEventTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("FIFOEventTest"); - - CppUnit_addTest(pSuite, FIFOEventTest, testNoDelegate); - CppUnit_addTest(pSuite, FIFOEventTest, testSingleDelegate); - CppUnit_addTest(pSuite, FIFOEventTest, testReturnParams); - CppUnit_addTest(pSuite, FIFOEventTest, testDuplicateRegister); - CppUnit_addTest(pSuite, FIFOEventTest, testDuplicateUnregister); - CppUnit_addTest(pSuite, FIFOEventTest, testDisabling); - CppUnit_addTest(pSuite, FIFOEventTest, testFIFOOrder); - CppUnit_addTest(pSuite, FIFOEventTest, testFIFOOrderExpire); - CppUnit_addTest(pSuite, FIFOEventTest, testExpire); - CppUnit_addTest(pSuite, FIFOEventTest, testExpireReRegister); - CppUnit_addTest(pSuite, FIFOEventTest, testOverwriteDelegate); - CppUnit_addTest(pSuite, FIFOEventTest, testAsyncNotify); - return pSuite; -} +// +// FIFOEventTest.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/FIFOEventTest.cpp#2 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "FIFOEventTest.h" +#include "DummyDelegate.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/Delegate.h" +#include "Poco/Expire.h" +#include "Poco/Thread.h" +#include "Poco/Exception.h" + + +using namespace Poco; + + +#define LARGEINC 100 + + +FIFOEventTest::FIFOEventTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +FIFOEventTest::~FIFOEventTest() +{ +} + +void FIFOEventTest::testNoDelegate() +{ + int tmp = 0; + EventArgs args; + + assert (_count == 0); + Simple.notify(this, tmp); + assert (_count == 0); + + Simple += Delegate(this, &FIFOEventTest::onSimple); + Simple -= Delegate(this, &FIFOEventTest::onSimple); + Simple.notify(this, tmp); + assert (_count == 0); + + ConstSimple += Delegate(this, &FIFOEventTest::onConstSimple); + ConstSimple -= Delegate(this, &FIFOEventTest::onConstSimple); + ConstSimple.notify(this, tmp); + assert (_count == 0); + + //Note: passing &args will not work due to & + EventArgs* pArgs = &args; + Complex += Delegate(this, &FIFOEventTest::onComplex); + Complex -= Delegate(this, &FIFOEventTest::onComplex); + Complex.notify(this, pArgs); + assert (_count == 0); + + Complex2 += Delegate(this, &FIFOEventTest::onComplex2); + Complex2 -= Delegate(this, &FIFOEventTest::onComplex2); + Complex2.notify(this, args); + assert (_count == 0); + + const EventArgs* pCArgs = &args; + ConstComplex += Delegate(this, &FIFOEventTest::onConstComplex); + ConstComplex -= Delegate(this, &FIFOEventTest::onConstComplex); + ConstComplex.notify(this, pCArgs); + assert (_count == 0); + + Const2Complex += Delegate(this, &FIFOEventTest::onConst2Complex); + Const2Complex -= Delegate(this, &FIFOEventTest::onConst2Complex); + Const2Complex.notify(this, pArgs); + assert (_count == 0); +} + +void FIFOEventTest::testSingleDelegate() +{ + int tmp = 0; + EventArgs args; + + assert (_count == 0); + + Simple += Delegate(this, &FIFOEventTest::onSimple); + Simple.notify(this, tmp); + assert (_count == 1); + + ConstSimple += Delegate(this, &FIFOEventTest::onConstSimple); + ConstSimple.notify(this, tmp); + assert (_count == 2); + + EventArgs* pArgs = &args; + Complex += Delegate(this, &FIFOEventTest::onComplex); + Complex.notify(this, pArgs); + assert (_count == 3); + + Complex2 += Delegate(this, &FIFOEventTest::onComplex2); + Complex2.notify(this, args); + assert (_count == 4); + + const EventArgs* pCArgs = &args; + ConstComplex += Delegate(this, &FIFOEventTest::onConstComplex); + ConstComplex.notify(this, pCArgs); + assert (_count == 5); + + Const2Complex += Delegate(this, &FIFOEventTest::onConst2Complex); + Const2Complex.notify(this, pArgs); + assert (_count == 6); + // check if 2nd notify also works + Const2Complex.notify(this, pArgs); + assert (_count == 7); + +} + +void FIFOEventTest::testDuplicateRegister() +{ + int tmp = 0; + + assert (_count == 0); + + Simple += Delegate(this, &FIFOEventTest::onSimple); + Simple += Delegate(this, &FIFOEventTest::onSimple); + Simple.notify(this, tmp); + assert (_count == 1); + Simple -= Delegate(this, &FIFOEventTest::onSimple); + Simple.notify(this, tmp); + assert (_count == 1); +} + +void FIFOEventTest::testDuplicateUnregister() +{ + // duplicate unregister shouldn't give an error, + int tmp = 0; + + assert (_count == 0); + + Simple -= Delegate(this, &FIFOEventTest::onSimple); // should work + Simple.notify(this, tmp); + assert (_count == 0); + + Simple += Delegate(this, &FIFOEventTest::onSimple); + Simple.notify(this, tmp); + assert (_count == 1); + + Simple -= Delegate(this, &FIFOEventTest::onSimple); + Simple.notify(this, tmp); + assert (_count == 1); + + Simple -= Delegate(this, &FIFOEventTest::onSimple); + Simple.notify(this, tmp); + assert (_count == 1); +} + + +void FIFOEventTest::testDisabling() +{ + int tmp = 0; + + assert (_count == 0); + + Simple += Delegate(this, &FIFOEventTest::onSimple); + Simple.disable(); + Simple.notify(this, tmp); + assert (_count == 0); + Simple.enable(); + Simple.notify(this, tmp); + assert (_count == 1); + + // unregister should also work with disabled event + Simple.disable(); + Simple -= Delegate(this, &FIFOEventTest::onSimple); + Simple.enable(); + Simple.notify(this, tmp); + assert (_count == 1); +} + +void FIFOEventTest::testFIFOOrder() +{ + DummyDelegate o1; + DummyDelegate o2; + + assert (_count == 0); + + Simple += Delegate(&o1, &DummyDelegate::onSimple); + Simple += Delegate(&o2, &DummyDelegate::onSimple2); + int tmp = 0; + Simple.notify(this, tmp); + assert (tmp == 2); + + Simple -= Delegate(&o1, &DummyDelegate::onSimple); + Simple -= Delegate(&o2, &DummyDelegate::onSimple2); + + // now try with the wrong order + Simple += Delegate(&o2, &DummyDelegate::onSimple2); + Simple += Delegate(&o1, &DummyDelegate::onSimple); + + try + { + tmp = 0; + Simple.notify(this, tmp); + failmsg ("Notify should not work"); + } + catch (Poco::InvalidArgumentException&) + { + } +} + +void FIFOEventTest::testFIFOOrderExpire() +{ + // expire must not break order! + DummyDelegate o1; + DummyDelegate o2; + + assert (_count == 0); + + Simple += Expire(Delegate(&o1, &DummyDelegate::onSimple), 5000); + Simple += Expire(Delegate(&o2, &DummyDelegate::onSimple2), 5000); + int tmp = 0; + Simple.notify(this, tmp); + assert (tmp == 2); + + // both ways of unregistering should work + Simple -= Expire(Delegate(&o1, &DummyDelegate::onSimple), 6000); + Simple -= Delegate(&o2, &DummyDelegate::onSimple2); + Simple.notify(this, tmp); + assert (tmp == 2); + + // now start mixing of expire and non expire + tmp = 0; + Simple += Delegate(&o1, &DummyDelegate::onSimple); + Simple += Expire(Delegate(&o2, &DummyDelegate::onSimple2), 5000); + Simple.notify(this, tmp); + assert (tmp == 2); + + Simple -= Delegate(&o2, &DummyDelegate::onSimple2); + // it is not forbidden to unregister a non expiring event with an expire decorator (it is just stupid ;-)) + Simple -= Expire(Delegate(&o1, &DummyDelegate::onSimple), 6000); + Simple.notify(this, tmp); + assert (tmp == 2); + + // now try with the wrong order + Simple += Expire(Delegate(&o2, &DummyDelegate::onSimple2), 5000); + Simple += Delegate(&o1, &DummyDelegate::onSimple); + + try + { + tmp = 0; + Simple.notify(this, tmp); + failmsg ("Notify should not work"); + } + catch (Poco::InvalidArgumentException&) + { + + } + +} + +void FIFOEventTest::testExpire() +{ + int tmp = 0; + + assert (_count == 0); + + Simple += Expire(Delegate(this, &FIFOEventTest::onSimple), 500); + Simple.notify(this, tmp); + assert (_count == 1); + Poco::Thread::sleep(700); + Simple.notify(this, tmp); + assert (_count == 1); +} + + +void FIFOEventTest::testExpireReRegister() +{ + int tmp = 0; + + assert (_count == 0); + + Simple += Expire(Delegate(this, &FIFOEventTest::onSimple), 500); + Simple.notify(this, tmp); + assert (_count == 1); + Poco::Thread::sleep(200); + Simple.notify(this, tmp); + assert (_count == 2); + // renew registration + Simple += Expire(Delegate(this, &FIFOEventTest::onSimple), 600); + Poco::Thread::sleep(400); + Simple.notify(this, tmp); + assert (_count == 3); + Poco::Thread::sleep(300); + Simple.notify(this, tmp); + assert (_count == 3); +} + + +void FIFOEventTest::testReturnParams() +{ + DummyDelegate o1; + Simple += Delegate(&o1, &DummyDelegate::onSimple); + + int tmp = 0; + Simple.notify(this, tmp); + assert (tmp == 1); +} + +void FIFOEventTest::testOverwriteDelegate() +{ + DummyDelegate o1; + Simple += Delegate(&o1, &DummyDelegate::onSimple2); + // o1 can only have one entry, thus the next line will replace the entry + Simple += Delegate(&o1, &DummyDelegate::onSimple); + + int tmp = 0; // onsimple requires 0 as input + Simple.notify(this, tmp); + assert (tmp == 1); + // now overwrite with onsimple2 with requires as input tmp = 1 + Simple += Expire(Delegate(&o1, &DummyDelegate::onSimple2), 23000); + Simple.notify(this, tmp); + assert (tmp == 2); +} + +void FIFOEventTest::testAsyncNotify() +{ + Poco::FIFOEvent* pSimple= new Poco::FIFOEvent(); + (*pSimple) += Delegate(this, &FIFOEventTest::onAsync); + assert (_count == 0); + int tmp = 0; + Poco::ActiveResultretArg = pSimple->notifyAsync(this, tmp); + delete pSimple; // must work even when the event got deleted! + pSimple = NULL; + assert (_count == 0); + retArg.wait(); + assert (retArg.data() == tmp); + assert (_count == LARGEINC); +} + +void FIFOEventTest::onSimple(const void* pSender, int& i) +{ + _count++; +} + +void FIFOEventTest::onSimpleOther(const void* pSender, int& i) +{ + _count+=100; +} + +void FIFOEventTest::onConstSimple(const void* pSender, const int& i) +{ + _count++; +} + +void FIFOEventTest::onComplex(const void* pSender, Poco::EventArgs* & i) +{ + _count++; +} + +void FIFOEventTest::onComplex2(const void* pSender, Poco::EventArgs & i) +{ + _count++; +} + +void FIFOEventTest::onConstComplex(const void* pSender, const Poco::EventArgs*& i) +{ + _count++; +} + +void FIFOEventTest::onConst2Complex(const void* pSender, const Poco::EventArgs * const & i) +{ + _count++; +} + +void FIFOEventTest::onAsync(const void* pSender, int& i) +{ + Poco::Thread::sleep(700); + _count += LARGEINC ; +} + +int FIFOEventTest::getCount() const +{ + return _count; +} + +void FIFOEventTest::setUp() +{ + _count = 0; + // must clear events, otherwise repeating test executions will fail + // because tests are only created once, only setup is called before + // each test run + Simple.clear(); + ConstSimple.clear(); + Complex.clear(); + Complex2.clear(); + ConstComplex.clear(); + Const2Complex.clear(); +} + + +void FIFOEventTest::tearDown() +{ +} + + +CppUnit::Test* FIFOEventTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("FIFOEventTest"); + + CppUnit_addTest(pSuite, FIFOEventTest, testNoDelegate); + CppUnit_addTest(pSuite, FIFOEventTest, testSingleDelegate); + CppUnit_addTest(pSuite, FIFOEventTest, testReturnParams); + CppUnit_addTest(pSuite, FIFOEventTest, testDuplicateRegister); + CppUnit_addTest(pSuite, FIFOEventTest, testDuplicateUnregister); + CppUnit_addTest(pSuite, FIFOEventTest, testDisabling); + CppUnit_addTest(pSuite, FIFOEventTest, testFIFOOrder); + CppUnit_addTest(pSuite, FIFOEventTest, testFIFOOrderExpire); + CppUnit_addTest(pSuite, FIFOEventTest, testExpire); + CppUnit_addTest(pSuite, FIFOEventTest, testExpireReRegister); + CppUnit_addTest(pSuite, FIFOEventTest, testOverwriteDelegate); + CppUnit_addTest(pSuite, FIFOEventTest, testAsyncNotify); + return pSuite; +} diff --git a/Foundation/testsuite/src/FIFOEventTest.h b/Foundation/testsuite/src/FIFOEventTest.h index 4d1ce5491..279fa6380 100644 --- a/Foundation/testsuite/src/FIFOEventTest.h +++ b/Foundation/testsuite/src/FIFOEventTest.h @@ -1,91 +1,91 @@ -// -// FIFOEventTest.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/FIFOEventTest.h#2 $ -// -// Definition of the FIFOEventTest class. -// -// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 FIFOEventTest_INCLUDED -#define FIFOEventTest_INCLUDED - - -#include "Poco/Foundation.h" -#include "CppUnit/TestCase.h" -#include "Poco/FIFOEvent.h" -#include "Poco/EventArgs.h" - - -class FIFOEventTest: public CppUnit::TestCase -{ - Poco::FIFOEvent Simple; - Poco::FIFOEvent ConstSimple; - Poco::FIFOEvent Complex; - Poco::FIFOEvent Complex2; - Poco::FIFOEvent ConstComplex; - Poco::FIFOEvent Const2Complex; -public: - FIFOEventTest(const std::string& name); - ~FIFOEventTest(); - - void testNoDelegate(); - void testSingleDelegate(); - void testDuplicateRegister(); - void testDuplicateUnregister(); - void testDisabling(); - void testFIFOOrder(); - void testFIFOOrderExpire(); - void testExpire(); - void testExpireReRegister(); - void testReturnParams(); - void testOverwriteDelegate(); - void testAsyncNotify(); - - void setUp(); - void tearDown(); - static CppUnit::Test* suite(); - -protected: - - void onSimple(const void* pSender, int& i); - void onSimpleOther(const void* pSender, int& i); - void onConstSimple(const void* pSender, const int& i); - void onComplex(const void* pSender, Poco::EventArgs* & i); - void onComplex2(const void* pSender, Poco::EventArgs & i); - void onConstComplex(const void* pSender, const Poco::EventArgs*& i); - void onConst2Complex(const void* pSender, const Poco::EventArgs * const & i); - void onAsync(const void* pSender, int& i); - - int getCount() const; -private: - int _count; -}; - - -#endif // FIFOEventTest_INCLUDED +// +// FIFOEventTest.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/FIFOEventTest.h#2 $ +// +// Definition of the FIFOEventTest class. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 FIFOEventTest_INCLUDED +#define FIFOEventTest_INCLUDED + + +#include "Poco/Foundation.h" +#include "CppUnit/TestCase.h" +#include "Poco/FIFOEvent.h" +#include "Poco/EventArgs.h" + + +class FIFOEventTest: public CppUnit::TestCase +{ + Poco::FIFOEvent Simple; + Poco::FIFOEvent ConstSimple; + Poco::FIFOEvent Complex; + Poco::FIFOEvent Complex2; + Poco::FIFOEvent ConstComplex; + Poco::FIFOEvent Const2Complex; +public: + FIFOEventTest(const std::string& name); + ~FIFOEventTest(); + + void testNoDelegate(); + void testSingleDelegate(); + void testDuplicateRegister(); + void testDuplicateUnregister(); + void testDisabling(); + void testFIFOOrder(); + void testFIFOOrderExpire(); + void testExpire(); + void testExpireReRegister(); + void testReturnParams(); + void testOverwriteDelegate(); + void testAsyncNotify(); + + void setUp(); + void tearDown(); + static CppUnit::Test* suite(); + +protected: + + void onSimple(const void* pSender, int& i); + void onSimpleOther(const void* pSender, int& i); + void onConstSimple(const void* pSender, const int& i); + void onComplex(const void* pSender, Poco::EventArgs* & i); + void onComplex2(const void* pSender, Poco::EventArgs & i); + void onConstComplex(const void* pSender, const Poco::EventArgs*& i); + void onConst2Complex(const void* pSender, const Poco::EventArgs * const & i); + void onAsync(const void* pSender, int& i); + + int getCount() const; +private: + int _count; +}; + + +#endif // FIFOEventTest_INCLUDED diff --git a/Foundation/testsuite/src/FPETest.cpp b/Foundation/testsuite/src/FPETest.cpp index d27b5a681..7ed20fb1c 100644 --- a/Foundation/testsuite/src/FPETest.cpp +++ b/Foundation/testsuite/src/FPETest.cpp @@ -1,168 +1,168 @@ -// -// FPETest.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/FPETest.cpp#1 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "FPETest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/FPEnvironment.h" - - -using Poco::FPE; - - -FPETest::FPETest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -FPETest::~FPETest() -{ -} - - -void FPETest::testClassify() -{ - { - float a = 0.0f; - float b = 0.0f; - float nan = a/b; - float inf = 1.0f/b; - - assert (FPE::isNaN(nan)); - assert (!FPE::isNaN(a)); - assert (FPE::isInfinite(inf)); - assert (!FPE::isInfinite(a)); - } - { - double a = 0; - double b = 0; - double nan = a/b; - double inf = 1.0/b; - - assert (FPE::isNaN(nan)); - assert (!FPE::isNaN(a)); - assert (FPE::isInfinite(inf)); - assert (!FPE::isInfinite(a)); - } -} - - -#if defined(__HP_aCC) -#pragma OPTIMIZE OFF -#elif defined(_MSC_VER) -#pragma optimize("", off) -#endif - - -double mult(double a, double b) -{ - return a*b; -} - - -double div(double a, double b) -{ - return a/b; -} - - -void FPETest::testFlags() -{ - FPE::clearFlags(); - - // some compilers are intelligent enough to optimize the calculations below away. - // unfortunately this leads to a failing test, so we have to trick out the - // compiler's optimizer a little bit by doing something with the results. - double a = 10; - double b = 0; - double c = div(a, b); - - assert (FPE::isFlag(FPE::FP_DIVIDE_BY_ZERO)); - assert (FPE::isInfinite(c)); - - FPE::clearFlags(); - a = 1.23456789e210; - b = 9.87654321e210; - c = mult(a, b); - assert (FPE::isFlag(FPE::FP_OVERFLOW)); - assertEqualDelta(c, c, 0); - - FPE::clearFlags(); - a = 1.23456789e-99; - b = 9.87654321e210; - c = div(a, b); - assert (FPE::isFlag(FPE::FP_UNDERFLOW)); - assertEqualDelta(c, c, 0); -} - - -#if defined(__HP_aCC) -#pragma OPTIMIZE ON -#elif defined(_MSC_VER) -#pragma optimize("", on) -#endif - - -void FPETest::testRound() -{ - #if !defined(__osf__) && !defined(__VMS) - FPE::setRoundingMode(FPE::FP_ROUND_TONEAREST); - assert (FPE::getRoundingMode() == FPE::FP_ROUND_TONEAREST); - { - FPE env(FPE::FP_ROUND_TOWARDZERO); - assert (FPE::getRoundingMode() == FPE::FP_ROUND_TOWARDZERO); - } - assert (FPE::getRoundingMode() == FPE::FP_ROUND_TONEAREST); - #endif -} - - -void FPETest::setUp() -{ -} - - -void FPETest::tearDown() -{ -} - - -CppUnit::Test* FPETest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("FPETest"); - - CppUnit_addTest(pSuite, FPETest, testClassify); - CppUnit_addTest(pSuite, FPETest, testFlags); - CppUnit_addTest(pSuite, FPETest, testRound); - - return pSuite; -} +// +// FPETest.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/FPETest.cpp#1 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "FPETest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/FPEnvironment.h" + + +using Poco::FPE; + + +FPETest::FPETest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +FPETest::~FPETest() +{ +} + + +void FPETest::testClassify() +{ + { + float a = 0.0f; + float b = 0.0f; + float nan = a/b; + float inf = 1.0f/b; + + assert (FPE::isNaN(nan)); + assert (!FPE::isNaN(a)); + assert (FPE::isInfinite(inf)); + assert (!FPE::isInfinite(a)); + } + { + double a = 0; + double b = 0; + double nan = a/b; + double inf = 1.0/b; + + assert (FPE::isNaN(nan)); + assert (!FPE::isNaN(a)); + assert (FPE::isInfinite(inf)); + assert (!FPE::isInfinite(a)); + } +} + + +#if defined(__HP_aCC) +#pragma OPTIMIZE OFF +#elif defined(_MSC_VER) +#pragma optimize("", off) +#endif + + +double mult(double a, double b) +{ + return a*b; +} + + +double div(double a, double b) +{ + return a/b; +} + + +void FPETest::testFlags() +{ + FPE::clearFlags(); + + // some compilers are intelligent enough to optimize the calculations below away. + // unfortunately this leads to a failing test, so we have to trick out the + // compiler's optimizer a little bit by doing something with the results. + double a = 10; + double b = 0; + double c = div(a, b); + + assert (FPE::isFlag(FPE::FP_DIVIDE_BY_ZERO)); + assert (FPE::isInfinite(c)); + + FPE::clearFlags(); + a = 1.23456789e210; + b = 9.87654321e210; + c = mult(a, b); + assert (FPE::isFlag(FPE::FP_OVERFLOW)); + assertEqualDelta(c, c, 0); + + FPE::clearFlags(); + a = 1.23456789e-99; + b = 9.87654321e210; + c = div(a, b); + assert (FPE::isFlag(FPE::FP_UNDERFLOW)); + assertEqualDelta(c, c, 0); +} + + +#if defined(__HP_aCC) +#pragma OPTIMIZE ON +#elif defined(_MSC_VER) +#pragma optimize("", on) +#endif + + +void FPETest::testRound() +{ + #if !defined(__osf__) && !defined(__VMS) + FPE::setRoundingMode(FPE::FP_ROUND_TONEAREST); + assert (FPE::getRoundingMode() == FPE::FP_ROUND_TONEAREST); + { + FPE env(FPE::FP_ROUND_TOWARDZERO); + assert (FPE::getRoundingMode() == FPE::FP_ROUND_TOWARDZERO); + } + assert (FPE::getRoundingMode() == FPE::FP_ROUND_TONEAREST); + #endif +} + + +void FPETest::setUp() +{ +} + + +void FPETest::tearDown() +{ +} + + +CppUnit::Test* FPETest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("FPETest"); + + CppUnit_addTest(pSuite, FPETest, testClassify); + CppUnit_addTest(pSuite, FPETest, testFlags); + CppUnit_addTest(pSuite, FPETest, testRound); + + return pSuite; +} diff --git a/Foundation/testsuite/src/FPETest.h b/Foundation/testsuite/src/FPETest.h index 9ddd4e891..b7458d841 100644 --- a/Foundation/testsuite/src/FPETest.h +++ b/Foundation/testsuite/src/FPETest.h @@ -1,62 +1,62 @@ -// -// FPETest.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/FPETest.h#1 $ -// -// Definition of the FPETest class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 FPETest_INCLUDED -#define FPETest_INCLUDED - - -#include "Poco/Foundation.h" -#include "CppUnit/TestCase.h" - - -class FPETest: public CppUnit::TestCase -{ -public: - FPETest(const std::string& name); - ~FPETest(); - - void testClassify(); - void testFlags(); - void testRound(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // FPETest_INCLUDED +// +// FPETest.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/FPETest.h#1 $ +// +// Definition of the FPETest class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 FPETest_INCLUDED +#define FPETest_INCLUDED + + +#include "Poco/Foundation.h" +#include "CppUnit/TestCase.h" + + +class FPETest: public CppUnit::TestCase +{ +public: + FPETest(const std::string& name); + ~FPETest(); + + void testClassify(); + void testFlags(); + void testRound(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // FPETest_INCLUDED diff --git a/Foundation/testsuite/src/FileChannelTest.cpp b/Foundation/testsuite/src/FileChannelTest.cpp index 2fe5435c1..0994ea4bc 100644 --- a/Foundation/testsuite/src/FileChannelTest.cpp +++ b/Foundation/testsuite/src/FileChannelTest.cpp @@ -1,541 +1,541 @@ -// -// FileChannelTest.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/FileChannelTest.cpp#1 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "FileChannelTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/FileChannel.h" -#include "Poco/Message.h" -#include "Poco/AutoPtr.h" -#include "Poco/TemporaryFile.h" -#include "Poco/Thread.h" -#include "Poco/File.h" -#include "Poco/Path.h" -#include "Poco/Timestamp.h" -#include "Poco/DateTime.h" -#include "Poco/LocalDateTime.h" -#include "Poco/DateTimeFormatter.h" -#include "Poco/DateTimeFormat.h" -#include "Poco/NumberFormatter.h" -#include "Poco/DirectoryIterator.h" -#include - - -using Poco::FileChannel; -using Poco::Message; -using Poco::AutoPtr; -using Poco::TemporaryFile; -using Poco::Thread; -using Poco::File; -using Poco::Path; -using Poco::Timestamp; -using Poco::NumberFormatter; -using Poco::DateTime; -using Poco::LocalDateTime; -using Poco::DateTimeFormatter; -using Poco::DateTimeFormat; -using Poco::DirectoryIterator; - - -FileChannelTest::FileChannelTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -FileChannelTest::~FileChannelTest() -{ -} - - -void FileChannelTest::testRotateBySize() -{ - std::string name = filename(); - try - { - AutoPtr pChannel = new FileChannel(name); - pChannel->setProperty(FileChannel::PROP_ROTATION, "2 K"); - pChannel->open(); - Message msg("source", "This is a log file entry", Message::PRIO_INFORMATION); - for (int i = 0; i < 200; ++i) - { - pChannel->log(msg); - } - File f(name + ".0"); - assert (f.exists()); - f = name + ".1"; - assert (f.exists()); - f = name + ".2"; - assert (!f.exists()); - } - catch (...) - { - remove(name); - throw; - } - remove(name); -} - - -void FileChannelTest::testRotateByAge() -{ - std::string name = filename(); - try - { - AutoPtr pChannel = new FileChannel(name); - pChannel->setProperty(FileChannel::PROP_ROTATION, "2 seconds"); - pChannel->open(); - Message msg("source", "This is a log file entry", Message::PRIO_INFORMATION); - for (int i = 0; i < 15; ++i) - { - pChannel->log(msg); - Thread::sleep(300); - } - File f(name + ".0"); - assert (f.exists()); - f = name + ".1"; - assert (f.exists()); - } - catch (...) - { - remove(name); - throw; - } - remove(name); -} - - -void FileChannelTest::testRotateAtTimeDayUTC() -{ - std::string name = filename(); - try - { - AutoPtr pChannel = new FileChannel(name); - pChannel->setProperty(FileChannel::PROP_TIMES, "utc"); - pChannel->setProperty(FileChannel::PROP_ROTATION, rotation(DAY_HOUR_MIN)); - pChannel->open(); - Message msg("source", "This is a log file entry", Message::PRIO_INFORMATION); - int min = DateTime().minute(); - while (DateTime().minute() == min) - { - pChannel->log(msg); - Thread::sleep(1000); - } - pChannel->log(msg); - File f(name + ".0"); - assert (f.exists()); - } - catch (...) - { - remove(name); - throw; - } - remove(name); -} - - -void FileChannelTest::testRotateAtTimeDayLocal() -{ - std::string name = filename(); - try - { - AutoPtr pChannel = new FileChannel(name); - pChannel->setProperty(FileChannel::PROP_TIMES, "local"); - pChannel->setProperty(FileChannel::PROP_ROTATION, rotation(DAY_HOUR_MIN)); - pChannel->open(); - Message msg("source", "This is a log file entry", Message::PRIO_INFORMATION); - int min = DateTime().minute(); - while (DateTime().minute() == min) - { - pChannel->log(msg); - Thread::sleep(1000); - } - pChannel->log(msg); - File f(name + ".0"); - assert (f.exists()); - } - catch (...) - { - remove(name); - throw; - } - remove(name); -} - - -void FileChannelTest::testRotateAtTimeHourUTC() -{ - std::string name = filename(); - try - { - AutoPtr pChannel = new FileChannel(name); - pChannel->setProperty(FileChannel::PROP_TIMES, "utc"); - pChannel->setProperty(FileChannel::PROP_ROTATION, rotation(HOUR_MIN)); - pChannel->open(); - Message msg("source", "This is a log file entry", Message::PRIO_INFORMATION); - int min = DateTime().minute(); - while (DateTime().minute() == min) - { - pChannel->log(msg); - Thread::sleep(1000); - } - pChannel->log(msg); - File f(name + ".0"); - assert (f.exists()); - } - catch (...) - { - remove(name); - throw; - } - remove(name); -} - - -void FileChannelTest::testRotateAtTimeHourLocal() -{ - std::string name = filename(); - try - { - AutoPtr pChannel = new FileChannel(name); - pChannel->setProperty(FileChannel::PROP_TIMES, "local"); - pChannel->setProperty(FileChannel::PROP_ROTATION, rotation(HOUR_MIN)); - pChannel->open(); - Message msg("source", "This is a log file entry", Message::PRIO_INFORMATION); - int min = DateTime().minute(); - while (DateTime().minute() == min) - { - pChannel->log(msg); - Thread::sleep(1000); - } - pChannel->log(msg); - File f(name + ".0"); - assert (f.exists()); - } - catch (...) - { - remove(name); - throw; - } - remove(name); -} - - -void FileChannelTest::testRotateAtTimeMinUTC() -{ - std::string name = filename(); - try - { - AutoPtr pChannel = new FileChannel(name); - pChannel->setProperty(FileChannel::PROP_TIMES, "utc"); - pChannel->setProperty(FileChannel::PROP_ROTATION, rotation(MIN)); - pChannel->open(); - Message msg("source", "This is a log file entry", Message::PRIO_INFORMATION); - int min = DateTime().minute(); - while (DateTime().minute() == min) - { - pChannel->log(msg); - Thread::sleep(1000); - } - pChannel->log(msg); - File f(name + ".0"); - assert (f.exists()); - } - catch (...) - { - remove(name); - throw; - } - remove(name); -} - - -void FileChannelTest::testRotateAtTimeMinLocal() -{ - std::string name = filename(); - try - { - AutoPtr pChannel = new FileChannel(name); - pChannel->setProperty(FileChannel::PROP_TIMES, "local"); - pChannel->setProperty(FileChannel::PROP_ROTATION, rotation(MIN)); - pChannel->open(); - Message msg("source", "This is a log file entry", Message::PRIO_INFORMATION); - int min = DateTime().minute(); - while (DateTime().minute() == min) - { - pChannel->log(msg); - Thread::sleep(1000); - } - pChannel->log(msg); - File f(name + ".0"); - assert (f.exists()); - } - catch (...) - { - remove(name); - throw; - } - remove(name); -} - - -void FileChannelTest::testArchive() -{ - std::string name = filename(); - try - { - AutoPtr pChannel = new FileChannel(name); - pChannel->setProperty(FileChannel::PROP_ROTATION, "2 K"); - pChannel->setProperty(FileChannel::PROP_ARCHIVE, "number"); - pChannel->open(); - Message msg("source", "This is a log file entry", Message::PRIO_INFORMATION); - for (int i = 0; i < 200; ++i) - { - pChannel->log(msg); - } - File f(name + ".0"); - assert (f.exists()); - } - catch (...) - { - remove(name); - throw; - } - remove(name); -} - - -void FileChannelTest::testCompress() -{ - std::string name = filename(); - try - { - AutoPtr pChannel = new FileChannel(name); - pChannel->setProperty(FileChannel::PROP_ROTATION, "1 K"); - pChannel->setProperty(FileChannel::PROP_ARCHIVE, "number"); - pChannel->setProperty(FileChannel::PROP_COMPRESS, "true"); - pChannel->open(); - Message msg("source", "This is a log file entry", Message::PRIO_INFORMATION); - for (int i = 0; i < 200; ++i) - { - pChannel->log(msg); - } - Thread::sleep(3000); // allow time for background compression - File f0(name + ".0.gz"); - assert (f0.exists()); - File f1(name + ".1.gz"); - assert (f1.exists()); - } - catch (...) - { - remove(name); - throw; - } - remove(name); -} - - -void FileChannelTest::testPurgeAge() -{ - std::string name = filename(); - try - { - AutoPtr pChannel = new FileChannel(name); - pChannel->setProperty(FileChannel::PROP_ROTATION, "1 K"); - pChannel->setProperty(FileChannel::PROP_ARCHIVE, "number"); - pChannel->setProperty(FileChannel::PROP_PURGEAGE, "5 seconds"); - pChannel->open(); - Message msg("source", "This is a log file entry", Message::PRIO_INFORMATION); - for (int i = 0; i < 200; ++i) - { - pChannel->log(msg); - } - File f0(name + ".0"); - assert (f0.exists()); - File f1(name + ".1"); - assert (f1.exists()); - File f2(name + ".2"); - assert (f2.exists()); - - Thread::sleep(5000); - for (int i = 0; i < 50; ++i) - { - pChannel->log(msg); - } - - assert (!f2.exists()); - } - catch (...) - { - remove(name); - throw; - } - remove(name); -} - - -void FileChannelTest::testPurgeCount() -{ - std::string name = filename(); - try - { - AutoPtr pChannel = new FileChannel(name); - pChannel->setProperty(FileChannel::PROP_ROTATION, "1 K"); - pChannel->setProperty(FileChannel::PROP_ARCHIVE, "number"); - pChannel->setProperty(FileChannel::PROP_PURGECOUNT, "2"); - pChannel->open(); - Message msg("source", "This is a log file entry", Message::PRIO_INFORMATION); - for (int i = 0; i < 200; ++i) - { - pChannel->log(msg); - Thread::sleep(50); - } - File f0(name + ".0"); - assert (f0.exists()); - File f1(name + ".1"); - assert (f1.exists()); - File f2(name + ".2"); - assert (!f2.exists()); - } - catch (...) - { - remove(name); - throw; - } - remove(name); -} - - -void FileChannelTest::setUp() -{ -} - - -void FileChannelTest::tearDown() -{ -} - - -void FileChannelTest::remove(const std::string& baseName) -{ - DirectoryIterator it(Path::current()); - DirectoryIterator end; - std::vector files; - while (it != end) - { - if (it.name().find(baseName) == 0) - { - files.push_back(it.name()); - } - ++it; - } - for (std::vector::iterator it = files.begin(); it != files.end(); ++it) - { - try - { - File f(*it); - f.remove(); - } - catch (...) - { - } - } -} - - -std::string FileChannelTest::filename() const -{ - std::string name = "log_"; - name.append(DateTimeFormatter::format(Timestamp(), "%Y%m%d%H%M%S")); - name.append(".log"); - return name; -} - - -template -std::string FileChannelTest::rotation(TimeRotation rtype) const -{ - DT now; - std::string rotation; - - int day = now.dayOfWeek(); - int min = now.minute(); - int hour = now.hour(); - if (++min == 60) - { - ++hour; - min = 0; - } - if (hour == 24) - { - hour = 0; - ++day; - day %= 7; - } - - switch (rtype) - { - case DAY_HOUR_MIN: // day,hh:m, - rotation = DateTimeFormat::WEEKDAY_NAMES[day]; - rotation += ',' + NumberFormatter::format0(hour, 2) + ':' + NumberFormatter::format0(min, 2); - break; - case HOUR_MIN: // hh:mm - rotation = NumberFormatter::format0(hour, 2) + ':' + NumberFormatter::format0(min, 2); - break; - case MIN: // mm - rotation = ':' + NumberFormatter::format0(min, 2); - break; - default: - rotation = ""; - } - return rotation; -} - - -CppUnit::Test* FileChannelTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("FileChannelTest"); - - CppUnit_addTest(pSuite, FileChannelTest, testRotateBySize); - CppUnit_addTest(pSuite, FileChannelTest, testRotateByAge); - CppUnit_addTest(pSuite, FileChannelTest, testRotateAtTimeDayUTC); - CppUnit_addTest(pSuite, FileChannelTest, testRotateAtTimeDayLocal); - CppUnit_addTest(pSuite, FileChannelTest, testRotateAtTimeHourUTC); - CppUnit_addTest(pSuite, FileChannelTest, testRotateAtTimeHourLocal); - CppUnit_addTest(pSuite, FileChannelTest, testRotateAtTimeMinUTC); - CppUnit_addTest(pSuite, FileChannelTest, testRotateAtTimeMinLocal); - CppUnit_addTest(pSuite, FileChannelTest, testArchive); - CppUnit_addTest(pSuite, FileChannelTest, testCompress); - CppUnit_addTest(pSuite, FileChannelTest, testPurgeAge); - CppUnit_addTest(pSuite, FileChannelTest, testPurgeCount); - - return pSuite; -} +// +// FileChannelTest.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/FileChannelTest.cpp#1 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "FileChannelTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/FileChannel.h" +#include "Poco/Message.h" +#include "Poco/AutoPtr.h" +#include "Poco/TemporaryFile.h" +#include "Poco/Thread.h" +#include "Poco/File.h" +#include "Poco/Path.h" +#include "Poco/Timestamp.h" +#include "Poco/DateTime.h" +#include "Poco/LocalDateTime.h" +#include "Poco/DateTimeFormatter.h" +#include "Poco/DateTimeFormat.h" +#include "Poco/NumberFormatter.h" +#include "Poco/DirectoryIterator.h" +#include + + +using Poco::FileChannel; +using Poco::Message; +using Poco::AutoPtr; +using Poco::TemporaryFile; +using Poco::Thread; +using Poco::File; +using Poco::Path; +using Poco::Timestamp; +using Poco::NumberFormatter; +using Poco::DateTime; +using Poco::LocalDateTime; +using Poco::DateTimeFormatter; +using Poco::DateTimeFormat; +using Poco::DirectoryIterator; + + +FileChannelTest::FileChannelTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +FileChannelTest::~FileChannelTest() +{ +} + + +void FileChannelTest::testRotateBySize() +{ + std::string name = filename(); + try + { + AutoPtr pChannel = new FileChannel(name); + pChannel->setProperty(FileChannel::PROP_ROTATION, "2 K"); + pChannel->open(); + Message msg("source", "This is a log file entry", Message::PRIO_INFORMATION); + for (int i = 0; i < 200; ++i) + { + pChannel->log(msg); + } + File f(name + ".0"); + assert (f.exists()); + f = name + ".1"; + assert (f.exists()); + f = name + ".2"; + assert (!f.exists()); + } + catch (...) + { + remove(name); + throw; + } + remove(name); +} + + +void FileChannelTest::testRotateByAge() +{ + std::string name = filename(); + try + { + AutoPtr pChannel = new FileChannel(name); + pChannel->setProperty(FileChannel::PROP_ROTATION, "2 seconds"); + pChannel->open(); + Message msg("source", "This is a log file entry", Message::PRIO_INFORMATION); + for (int i = 0; i < 15; ++i) + { + pChannel->log(msg); + Thread::sleep(300); + } + File f(name + ".0"); + assert (f.exists()); + f = name + ".1"; + assert (f.exists()); + } + catch (...) + { + remove(name); + throw; + } + remove(name); +} + + +void FileChannelTest::testRotateAtTimeDayUTC() +{ + std::string name = filename(); + try + { + AutoPtr pChannel = new FileChannel(name); + pChannel->setProperty(FileChannel::PROP_TIMES, "utc"); + pChannel->setProperty(FileChannel::PROP_ROTATION, rotation(DAY_HOUR_MIN)); + pChannel->open(); + Message msg("source", "This is a log file entry", Message::PRIO_INFORMATION); + int min = DateTime().minute(); + while (DateTime().minute() == min) + { + pChannel->log(msg); + Thread::sleep(1000); + } + pChannel->log(msg); + File f(name + ".0"); + assert (f.exists()); + } + catch (...) + { + remove(name); + throw; + } + remove(name); +} + + +void FileChannelTest::testRotateAtTimeDayLocal() +{ + std::string name = filename(); + try + { + AutoPtr pChannel = new FileChannel(name); + pChannel->setProperty(FileChannel::PROP_TIMES, "local"); + pChannel->setProperty(FileChannel::PROP_ROTATION, rotation(DAY_HOUR_MIN)); + pChannel->open(); + Message msg("source", "This is a log file entry", Message::PRIO_INFORMATION); + int min = DateTime().minute(); + while (DateTime().minute() == min) + { + pChannel->log(msg); + Thread::sleep(1000); + } + pChannel->log(msg); + File f(name + ".0"); + assert (f.exists()); + } + catch (...) + { + remove(name); + throw; + } + remove(name); +} + + +void FileChannelTest::testRotateAtTimeHourUTC() +{ + std::string name = filename(); + try + { + AutoPtr pChannel = new FileChannel(name); + pChannel->setProperty(FileChannel::PROP_TIMES, "utc"); + pChannel->setProperty(FileChannel::PROP_ROTATION, rotation(HOUR_MIN)); + pChannel->open(); + Message msg("source", "This is a log file entry", Message::PRIO_INFORMATION); + int min = DateTime().minute(); + while (DateTime().minute() == min) + { + pChannel->log(msg); + Thread::sleep(1000); + } + pChannel->log(msg); + File f(name + ".0"); + assert (f.exists()); + } + catch (...) + { + remove(name); + throw; + } + remove(name); +} + + +void FileChannelTest::testRotateAtTimeHourLocal() +{ + std::string name = filename(); + try + { + AutoPtr pChannel = new FileChannel(name); + pChannel->setProperty(FileChannel::PROP_TIMES, "local"); + pChannel->setProperty(FileChannel::PROP_ROTATION, rotation(HOUR_MIN)); + pChannel->open(); + Message msg("source", "This is a log file entry", Message::PRIO_INFORMATION); + int min = DateTime().minute(); + while (DateTime().minute() == min) + { + pChannel->log(msg); + Thread::sleep(1000); + } + pChannel->log(msg); + File f(name + ".0"); + assert (f.exists()); + } + catch (...) + { + remove(name); + throw; + } + remove(name); +} + + +void FileChannelTest::testRotateAtTimeMinUTC() +{ + std::string name = filename(); + try + { + AutoPtr pChannel = new FileChannel(name); + pChannel->setProperty(FileChannel::PROP_TIMES, "utc"); + pChannel->setProperty(FileChannel::PROP_ROTATION, rotation(MIN)); + pChannel->open(); + Message msg("source", "This is a log file entry", Message::PRIO_INFORMATION); + int min = DateTime().minute(); + while (DateTime().minute() == min) + { + pChannel->log(msg); + Thread::sleep(1000); + } + pChannel->log(msg); + File f(name + ".0"); + assert (f.exists()); + } + catch (...) + { + remove(name); + throw; + } + remove(name); +} + + +void FileChannelTest::testRotateAtTimeMinLocal() +{ + std::string name = filename(); + try + { + AutoPtr pChannel = new FileChannel(name); + pChannel->setProperty(FileChannel::PROP_TIMES, "local"); + pChannel->setProperty(FileChannel::PROP_ROTATION, rotation(MIN)); + pChannel->open(); + Message msg("source", "This is a log file entry", Message::PRIO_INFORMATION); + int min = DateTime().minute(); + while (DateTime().minute() == min) + { + pChannel->log(msg); + Thread::sleep(1000); + } + pChannel->log(msg); + File f(name + ".0"); + assert (f.exists()); + } + catch (...) + { + remove(name); + throw; + } + remove(name); +} + + +void FileChannelTest::testArchive() +{ + std::string name = filename(); + try + { + AutoPtr pChannel = new FileChannel(name); + pChannel->setProperty(FileChannel::PROP_ROTATION, "2 K"); + pChannel->setProperty(FileChannel::PROP_ARCHIVE, "number"); + pChannel->open(); + Message msg("source", "This is a log file entry", Message::PRIO_INFORMATION); + for (int i = 0; i < 200; ++i) + { + pChannel->log(msg); + } + File f(name + ".0"); + assert (f.exists()); + } + catch (...) + { + remove(name); + throw; + } + remove(name); +} + + +void FileChannelTest::testCompress() +{ + std::string name = filename(); + try + { + AutoPtr pChannel = new FileChannel(name); + pChannel->setProperty(FileChannel::PROP_ROTATION, "1 K"); + pChannel->setProperty(FileChannel::PROP_ARCHIVE, "number"); + pChannel->setProperty(FileChannel::PROP_COMPRESS, "true"); + pChannel->open(); + Message msg("source", "This is a log file entry", Message::PRIO_INFORMATION); + for (int i = 0; i < 200; ++i) + { + pChannel->log(msg); + } + Thread::sleep(3000); // allow time for background compression + File f0(name + ".0.gz"); + assert (f0.exists()); + File f1(name + ".1.gz"); + assert (f1.exists()); + } + catch (...) + { + remove(name); + throw; + } + remove(name); +} + + +void FileChannelTest::testPurgeAge() +{ + std::string name = filename(); + try + { + AutoPtr pChannel = new FileChannel(name); + pChannel->setProperty(FileChannel::PROP_ROTATION, "1 K"); + pChannel->setProperty(FileChannel::PROP_ARCHIVE, "number"); + pChannel->setProperty(FileChannel::PROP_PURGEAGE, "5 seconds"); + pChannel->open(); + Message msg("source", "This is a log file entry", Message::PRIO_INFORMATION); + for (int i = 0; i < 200; ++i) + { + pChannel->log(msg); + } + File f0(name + ".0"); + assert (f0.exists()); + File f1(name + ".1"); + assert (f1.exists()); + File f2(name + ".2"); + assert (f2.exists()); + + Thread::sleep(5000); + for (int i = 0; i < 50; ++i) + { + pChannel->log(msg); + } + + assert (!f2.exists()); + } + catch (...) + { + remove(name); + throw; + } + remove(name); +} + + +void FileChannelTest::testPurgeCount() +{ + std::string name = filename(); + try + { + AutoPtr pChannel = new FileChannel(name); + pChannel->setProperty(FileChannel::PROP_ROTATION, "1 K"); + pChannel->setProperty(FileChannel::PROP_ARCHIVE, "number"); + pChannel->setProperty(FileChannel::PROP_PURGECOUNT, "2"); + pChannel->open(); + Message msg("source", "This is a log file entry", Message::PRIO_INFORMATION); + for (int i = 0; i < 200; ++i) + { + pChannel->log(msg); + Thread::sleep(50); + } + File f0(name + ".0"); + assert (f0.exists()); + File f1(name + ".1"); + assert (f1.exists()); + File f2(name + ".2"); + assert (!f2.exists()); + } + catch (...) + { + remove(name); + throw; + } + remove(name); +} + + +void FileChannelTest::setUp() +{ +} + + +void FileChannelTest::tearDown() +{ +} + + +void FileChannelTest::remove(const std::string& baseName) +{ + DirectoryIterator it(Path::current()); + DirectoryIterator end; + std::vector files; + while (it != end) + { + if (it.name().find(baseName) == 0) + { + files.push_back(it.name()); + } + ++it; + } + for (std::vector::iterator it = files.begin(); it != files.end(); ++it) + { + try + { + File f(*it); + f.remove(); + } + catch (...) + { + } + } +} + + +std::string FileChannelTest::filename() const +{ + std::string name = "log_"; + name.append(DateTimeFormatter::format(Timestamp(), "%Y%m%d%H%M%S")); + name.append(".log"); + return name; +} + + +template +std::string FileChannelTest::rotation(TimeRotation rtype) const +{ + DT now; + std::string rotation; + + int day = now.dayOfWeek(); + int min = now.minute(); + int hour = now.hour(); + if (++min == 60) + { + ++hour; + min = 0; + } + if (hour == 24) + { + hour = 0; + ++day; + day %= 7; + } + + switch (rtype) + { + case DAY_HOUR_MIN: // day,hh:m, + rotation = DateTimeFormat::WEEKDAY_NAMES[day]; + rotation += ',' + NumberFormatter::format0(hour, 2) + ':' + NumberFormatter::format0(min, 2); + break; + case HOUR_MIN: // hh:mm + rotation = NumberFormatter::format0(hour, 2) + ':' + NumberFormatter::format0(min, 2); + break; + case MIN: // mm + rotation = ':' + NumberFormatter::format0(min, 2); + break; + default: + rotation = ""; + } + return rotation; +} + + +CppUnit::Test* FileChannelTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("FileChannelTest"); + + CppUnit_addTest(pSuite, FileChannelTest, testRotateBySize); + CppUnit_addTest(pSuite, FileChannelTest, testRotateByAge); + CppUnit_addTest(pSuite, FileChannelTest, testRotateAtTimeDayUTC); + CppUnit_addTest(pSuite, FileChannelTest, testRotateAtTimeDayLocal); + CppUnit_addTest(pSuite, FileChannelTest, testRotateAtTimeHourUTC); + CppUnit_addTest(pSuite, FileChannelTest, testRotateAtTimeHourLocal); + CppUnit_addTest(pSuite, FileChannelTest, testRotateAtTimeMinUTC); + CppUnit_addTest(pSuite, FileChannelTest, testRotateAtTimeMinLocal); + CppUnit_addTest(pSuite, FileChannelTest, testArchive); + CppUnit_addTest(pSuite, FileChannelTest, testCompress); + CppUnit_addTest(pSuite, FileChannelTest, testPurgeAge); + CppUnit_addTest(pSuite, FileChannelTest, testPurgeCount); + + return pSuite; +} diff --git a/Foundation/testsuite/src/FileChannelTest.h b/Foundation/testsuite/src/FileChannelTest.h index bff4bad41..9facb9ad6 100644 --- a/Foundation/testsuite/src/FileChannelTest.h +++ b/Foundation/testsuite/src/FileChannelTest.h @@ -1,81 +1,81 @@ -// -// FileChannelTest.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/FileChannelTest.h#1 $ -// -// Definition of the FileChannelTest class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 FileChannelTest_INCLUDED -#define FileChannelTest_INCLUDED - - -#include "Poco/Foundation.h" -#include "CppUnit/TestCase.h" - - -class FileChannelTest: public CppUnit::TestCase -{ -public: - enum TimeRotation - { - DAY_HOUR_MIN = 0, - HOUR_MIN, - MIN - }; - - FileChannelTest(const std::string& name); - ~FileChannelTest(); - - void testRotateBySize(); - void testRotateByAge(); - void testRotateAtTimeDayUTC(); - void testRotateAtTimeDayLocal(); - void testRotateAtTimeHourUTC(); - void testRotateAtTimeHourLocal(); - void testRotateAtTimeMinUTC(); - void testRotateAtTimeMinLocal(); - void testArchive(); - void testCompress(); - void testPurgeAge(); - void testPurgeCount(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: - template std::string rotation(TimeRotation rtype) const; - void remove(const std::string& baseName); - std::string filename() const; -}; - - -#endif // FileChannelTest_INCLUDED +// +// FileChannelTest.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/FileChannelTest.h#1 $ +// +// Definition of the FileChannelTest class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 FileChannelTest_INCLUDED +#define FileChannelTest_INCLUDED + + +#include "Poco/Foundation.h" +#include "CppUnit/TestCase.h" + + +class FileChannelTest: public CppUnit::TestCase +{ +public: + enum TimeRotation + { + DAY_HOUR_MIN = 0, + HOUR_MIN, + MIN + }; + + FileChannelTest(const std::string& name); + ~FileChannelTest(); + + void testRotateBySize(); + void testRotateByAge(); + void testRotateAtTimeDayUTC(); + void testRotateAtTimeDayLocal(); + void testRotateAtTimeHourUTC(); + void testRotateAtTimeHourLocal(); + void testRotateAtTimeMinUTC(); + void testRotateAtTimeMinLocal(); + void testArchive(); + void testCompress(); + void testPurgeAge(); + void testPurgeCount(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: + template std::string rotation(TimeRotation rtype) const; + void remove(const std::string& baseName); + std::string filename() const; +}; + + +#endif // FileChannelTest_INCLUDED diff --git a/Foundation/testsuite/src/FileTest.cpp b/Foundation/testsuite/src/FileTest.cpp index f07cc9799..f892d571b 100644 --- a/Foundation/testsuite/src/FileTest.cpp +++ b/Foundation/testsuite/src/FileTest.cpp @@ -1,434 +1,434 @@ -// -// FileTest.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/FileTest.cpp#1 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "FileTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/File.h" -#include "Poco/TemporaryFile.h" -#include "Poco/Path.h" -#include "Poco/Exception.h" -#include "Poco/Thread.h" -#include -#include - - -using Poco::File; -using Poco::TemporaryFile; -using Poco::Path; -using Poco::Exception; -using Poco::Timestamp; -using Poco::Thread; - - -FileTest::FileTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -FileTest::~FileTest() -{ -} - - -void FileTest::testFileAttributes1() -{ - File f("testfile.dat"); - assert (!f.exists()); - - try - { - bool flag = f.canRead(); - failmsg("file does not exist - must throw exception"); - } - catch (Exception&) - { - } - - try - { - bool flag = f.canWrite(); - failmsg("file does not exist - must throw exception"); - } - catch (Exception&) - { - } - - try - { - bool flag = f.isFile(); - failmsg("file does not exist - must throw exception"); - } - catch (Exception&) - { - } - - try - { - bool flag = f.isDirectory(); - failmsg("file does not exist - must throw exception"); - } - catch (Exception&) - { - } - - try - { - Timestamp ts = f.created(); - failmsg("file does not exist - must throw exception"); - } - catch (Exception&) - { - } - - try - { - Timestamp ts = f.getLastModified(); - failmsg("file does not exist - must throw exception"); - } - catch (Exception&) - { - } - - try - { - Timestamp ts; - f.setLastModified(ts); - failmsg("file does not exist - must throw exception"); - } - catch (Exception&) - { - } - - try - { - File::FileSize fs = f.getSize(); - failmsg("file does not exist - must throw exception"); - } - catch (Exception&) - { - } - - try - { - f.setSize(0); - failmsg("file does not exist - must throw exception"); - } - catch (Exception&) - { - } - - try - { - f.setWriteable(); - failmsg("file does not exist - must throw exception"); - } - catch (Exception&) - { - } - - try - { - f.setReadOnly(); - failmsg("file does not exist - must throw exception"); - } - catch (Exception&) - { - } - - try - { - f.copyTo("copy.dat"); - failmsg("file does not exist - must throw exception"); - } - catch (Exception&) - { - } - - try - { - f.moveTo("copy.dat"); - failmsg("file does not exist - must throw exception"); - } - catch (Exception&) - { - } - - try - { - f.renameTo("copy.dat"); - failmsg("file does not exist - must throw exception"); - } - catch (Exception&) - { - } - - try - { - f.remove(); - failmsg("file does not exist - must throw exception"); - } - catch (Exception&) - { - } -} - - -void FileTest::testCreateFile() -{ - File f("testfile.dat"); - bool created = f.createFile(); - assert (created); - created = f.createFile(); - assert (!created); -} - - -void FileTest::testFileAttributes2() -{ - TemporaryFile f; - bool created = f.createFile(); - Timestamp ts; - assert (created); - - assert (f.exists()); - assert (f.canRead()); - assert (f.canWrite()); - assert (f.isFile()); - assert (!f.isDirectory()); - Timestamp tsc = f.created(); - Timestamp tsm = f.getLastModified(); - assert (tsc - ts >= -2000000 && tsc - ts <= 2000000); - assert (tsm - ts >= -2000000 && tsm - ts <= 2000000); - - f.setWriteable(false); - assert (!f.canWrite()); - assert (f.canRead()); - - f.setReadOnly(false); - assert (f.canWrite()); - assert (f.canRead()); - - ts = Timestamp::fromEpochTime(1000000); - f.setLastModified(ts); - assert (f.getLastModified() == ts); -} - - -void FileTest::testCompare() -{ - File f1("abc.txt"); - File f2("def.txt"); - File f3("abc.txt"); - - assert (f1 == f3); - assert (!(f1 == f2)); - assert (f1 != f2); - assert (!(f1 != f3)); - assert (!(f1 == f2)); - assert (f1 < f2); - assert (f1 <= f2); - assert (!(f2 < f1)); - assert (!(f2 <= f1)); - assert (f2 > f1); - assert (f2 >= f1); - assert (!(f1 > f2)); - assert (!(f1 >= f2)); - - assert (f1 <= f3); - assert (f1 >= f3); -} - - -void FileTest::testSwap() -{ - File f1("abc.txt"); - File f2("def.txt"); - f1.swap(f2); - assert (f1.path() == "def.txt"); - assert (f2.path() == "abc.txt"); -} - - -void FileTest::testSize() -{ - std::ofstream ostr("testfile.dat"); - ostr << "Hello, world!" << std::endl; - ostr.close(); - File f("testfile.dat"); - assert (f.getSize() > 0); - f.setSize(0); - assert (f.getSize() == 0); -} - - -void FileTest::testDirectory() -{ - File d("testdir"); - try - { - d.remove(true); - } - catch (...) - { - } - TemporaryFile::registerForDeletion("testdir"); - - bool created = d.createDirectory(); - assert (created); - assert (d.isDirectory()); - assert (!d.isFile()); - std::vector files; - d.list(files); - assert (files.empty()); - - File f = Path("testdir/file1", Path::PATH_UNIX); - f.createFile(); - f = Path("testdir/file2", Path::PATH_UNIX); - f.createFile(); - f = Path("testdir/file3", Path::PATH_UNIX); - f.createFile(); - - d.list(files); - assert (files.size() == 3); - - std::set fs; - fs.insert(files.begin(), files.end()); - assert (fs.find("file1") != fs.end()); - assert (fs.find("file2") != fs.end()); - assert (fs.find("file3") != fs.end()); - - File dd(Path("testdir/testdir2/testdir3", Path::PATH_UNIX)); - dd.createDirectories(); - assert (dd.exists()); - assert (dd.isDirectory()); - - File ddd(Path("testdir/testdirB/testdirC/testdirD", Path::PATH_UNIX)); - ddd.createDirectories(); - assert (ddd.exists()); - assert (ddd.isDirectory()); - - d.remove(true); -} - - -void FileTest::testCopy() -{ - std::ofstream ostr("testfile.dat"); - ostr << "Hello, world!" << std::endl; - ostr.close(); - - File f1("testfile.dat"); - TemporaryFile f2; - f1.copyTo(f2.path()); - assert (f2.exists()); - assert (f1.getSize() == f2.getSize()); -} - - -void FileTest::testMove() -{ - std::ofstream ostr("testfile.dat"); - ostr << "Hello, world!" << std::endl; - ostr.close(); - - File f1("testfile.dat"); - File::FileSize sz = f1.getSize(); - TemporaryFile f2; - f1.moveTo(f2.path()); - assert (f2.exists()); - assert (f2.getSize() == sz); - assert (f1.exists()); - assert (f1 == f2); -} - - -void FileTest::testRename() -{ - std::ofstream ostr("testfile.dat"); - ostr << "Hello, world!" << std::endl; - ostr.close(); - - File f1("testfile.dat"); - File f2("testfile2.dat"); - f1.renameTo(f2.path()); - - assert (f2.exists()); - assert (f1.exists()); - assert (f1 == f2); - - f2.remove(); -} - - -void FileTest::setUp() -{ - File f("testfile.dat"); - try - { - f.remove(); - } - catch (...) - { - } -} - - -void FileTest::tearDown() -{ - File f("testfile.dat"); - try - { - f.remove(); - } - catch (...) - { - } -} - - -CppUnit::Test* FileTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("FileTest"); - - CppUnit_addTest(pSuite, FileTest, testFileAttributes1); - CppUnit_addTest(pSuite, FileTest, testFileAttributes2); - CppUnit_addTest(pSuite, FileTest, testCompare); - CppUnit_addTest(pSuite, FileTest, testSwap); - CppUnit_addTest(pSuite, FileTest, testSize); - CppUnit_addTest(pSuite, FileTest, testDirectory); - CppUnit_addTest(pSuite, FileTest, testCopy); - CppUnit_addTest(pSuite, FileTest, testMove); - CppUnit_addTest(pSuite, FileTest, testRename); - - return pSuite; -} +// +// FileTest.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/FileTest.cpp#1 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "FileTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/File.h" +#include "Poco/TemporaryFile.h" +#include "Poco/Path.h" +#include "Poco/Exception.h" +#include "Poco/Thread.h" +#include +#include + + +using Poco::File; +using Poco::TemporaryFile; +using Poco::Path; +using Poco::Exception; +using Poco::Timestamp; +using Poco::Thread; + + +FileTest::FileTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +FileTest::~FileTest() +{ +} + + +void FileTest::testFileAttributes1() +{ + File f("testfile.dat"); + assert (!f.exists()); + + try + { + bool flag = f.canRead(); + failmsg("file does not exist - must throw exception"); + } + catch (Exception&) + { + } + + try + { + bool flag = f.canWrite(); + failmsg("file does not exist - must throw exception"); + } + catch (Exception&) + { + } + + try + { + bool flag = f.isFile(); + failmsg("file does not exist - must throw exception"); + } + catch (Exception&) + { + } + + try + { + bool flag = f.isDirectory(); + failmsg("file does not exist - must throw exception"); + } + catch (Exception&) + { + } + + try + { + Timestamp ts = f.created(); + failmsg("file does not exist - must throw exception"); + } + catch (Exception&) + { + } + + try + { + Timestamp ts = f.getLastModified(); + failmsg("file does not exist - must throw exception"); + } + catch (Exception&) + { + } + + try + { + Timestamp ts; + f.setLastModified(ts); + failmsg("file does not exist - must throw exception"); + } + catch (Exception&) + { + } + + try + { + File::FileSize fs = f.getSize(); + failmsg("file does not exist - must throw exception"); + } + catch (Exception&) + { + } + + try + { + f.setSize(0); + failmsg("file does not exist - must throw exception"); + } + catch (Exception&) + { + } + + try + { + f.setWriteable(); + failmsg("file does not exist - must throw exception"); + } + catch (Exception&) + { + } + + try + { + f.setReadOnly(); + failmsg("file does not exist - must throw exception"); + } + catch (Exception&) + { + } + + try + { + f.copyTo("copy.dat"); + failmsg("file does not exist - must throw exception"); + } + catch (Exception&) + { + } + + try + { + f.moveTo("copy.dat"); + failmsg("file does not exist - must throw exception"); + } + catch (Exception&) + { + } + + try + { + f.renameTo("copy.dat"); + failmsg("file does not exist - must throw exception"); + } + catch (Exception&) + { + } + + try + { + f.remove(); + failmsg("file does not exist - must throw exception"); + } + catch (Exception&) + { + } +} + + +void FileTest::testCreateFile() +{ + File f("testfile.dat"); + bool created = f.createFile(); + assert (created); + created = f.createFile(); + assert (!created); +} + + +void FileTest::testFileAttributes2() +{ + TemporaryFile f; + bool created = f.createFile(); + Timestamp ts; + assert (created); + + assert (f.exists()); + assert (f.canRead()); + assert (f.canWrite()); + assert (f.isFile()); + assert (!f.isDirectory()); + Timestamp tsc = f.created(); + Timestamp tsm = f.getLastModified(); + assert (tsc - ts >= -2000000 && tsc - ts <= 2000000); + assert (tsm - ts >= -2000000 && tsm - ts <= 2000000); + + f.setWriteable(false); + assert (!f.canWrite()); + assert (f.canRead()); + + f.setReadOnly(false); + assert (f.canWrite()); + assert (f.canRead()); + + ts = Timestamp::fromEpochTime(1000000); + f.setLastModified(ts); + assert (f.getLastModified() == ts); +} + + +void FileTest::testCompare() +{ + File f1("abc.txt"); + File f2("def.txt"); + File f3("abc.txt"); + + assert (f1 == f3); + assert (!(f1 == f2)); + assert (f1 != f2); + assert (!(f1 != f3)); + assert (!(f1 == f2)); + assert (f1 < f2); + assert (f1 <= f2); + assert (!(f2 < f1)); + assert (!(f2 <= f1)); + assert (f2 > f1); + assert (f2 >= f1); + assert (!(f1 > f2)); + assert (!(f1 >= f2)); + + assert (f1 <= f3); + assert (f1 >= f3); +} + + +void FileTest::testSwap() +{ + File f1("abc.txt"); + File f2("def.txt"); + f1.swap(f2); + assert (f1.path() == "def.txt"); + assert (f2.path() == "abc.txt"); +} + + +void FileTest::testSize() +{ + std::ofstream ostr("testfile.dat"); + ostr << "Hello, world!" << std::endl; + ostr.close(); + File f("testfile.dat"); + assert (f.getSize() > 0); + f.setSize(0); + assert (f.getSize() == 0); +} + + +void FileTest::testDirectory() +{ + File d("testdir"); + try + { + d.remove(true); + } + catch (...) + { + } + TemporaryFile::registerForDeletion("testdir"); + + bool created = d.createDirectory(); + assert (created); + assert (d.isDirectory()); + assert (!d.isFile()); + std::vector files; + d.list(files); + assert (files.empty()); + + File f = Path("testdir/file1", Path::PATH_UNIX); + f.createFile(); + f = Path("testdir/file2", Path::PATH_UNIX); + f.createFile(); + f = Path("testdir/file3", Path::PATH_UNIX); + f.createFile(); + + d.list(files); + assert (files.size() == 3); + + std::set fs; + fs.insert(files.begin(), files.end()); + assert (fs.find("file1") != fs.end()); + assert (fs.find("file2") != fs.end()); + assert (fs.find("file3") != fs.end()); + + File dd(Path("testdir/testdir2/testdir3", Path::PATH_UNIX)); + dd.createDirectories(); + assert (dd.exists()); + assert (dd.isDirectory()); + + File ddd(Path("testdir/testdirB/testdirC/testdirD", Path::PATH_UNIX)); + ddd.createDirectories(); + assert (ddd.exists()); + assert (ddd.isDirectory()); + + d.remove(true); +} + + +void FileTest::testCopy() +{ + std::ofstream ostr("testfile.dat"); + ostr << "Hello, world!" << std::endl; + ostr.close(); + + File f1("testfile.dat"); + TemporaryFile f2; + f1.copyTo(f2.path()); + assert (f2.exists()); + assert (f1.getSize() == f2.getSize()); +} + + +void FileTest::testMove() +{ + std::ofstream ostr("testfile.dat"); + ostr << "Hello, world!" << std::endl; + ostr.close(); + + File f1("testfile.dat"); + File::FileSize sz = f1.getSize(); + TemporaryFile f2; + f1.moveTo(f2.path()); + assert (f2.exists()); + assert (f2.getSize() == sz); + assert (f1.exists()); + assert (f1 == f2); +} + + +void FileTest::testRename() +{ + std::ofstream ostr("testfile.dat"); + ostr << "Hello, world!" << std::endl; + ostr.close(); + + File f1("testfile.dat"); + File f2("testfile2.dat"); + f1.renameTo(f2.path()); + + assert (f2.exists()); + assert (f1.exists()); + assert (f1 == f2); + + f2.remove(); +} + + +void FileTest::setUp() +{ + File f("testfile.dat"); + try + { + f.remove(); + } + catch (...) + { + } +} + + +void FileTest::tearDown() +{ + File f("testfile.dat"); + try + { + f.remove(); + } + catch (...) + { + } +} + + +CppUnit::Test* FileTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("FileTest"); + + CppUnit_addTest(pSuite, FileTest, testFileAttributes1); + CppUnit_addTest(pSuite, FileTest, testFileAttributes2); + CppUnit_addTest(pSuite, FileTest, testCompare); + CppUnit_addTest(pSuite, FileTest, testSwap); + CppUnit_addTest(pSuite, FileTest, testSize); + CppUnit_addTest(pSuite, FileTest, testDirectory); + CppUnit_addTest(pSuite, FileTest, testCopy); + CppUnit_addTest(pSuite, FileTest, testMove); + CppUnit_addTest(pSuite, FileTest, testRename); + + return pSuite; +} diff --git a/Foundation/testsuite/src/FileTest.h b/Foundation/testsuite/src/FileTest.h index ef732220e..886a08df1 100644 --- a/Foundation/testsuite/src/FileTest.h +++ b/Foundation/testsuite/src/FileTest.h @@ -1,69 +1,69 @@ -// -// FileTest.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/FileTest.h#1 $ -// -// Definition of the FileTest class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 FileTest_INCLUDED -#define FileTest_INCLUDED - - -#include "Poco/Foundation.h" -#include "CppUnit/TestCase.h" - - -class FileTest: public CppUnit::TestCase -{ -public: - FileTest(const std::string& name); - ~FileTest(); - - void testFileAttributes1(); - void testCreateFile(); - void testFileAttributes2(); - void testCompare(); - void testSwap(); - void testSize(); - void testDirectory(); - void testCopy(); - void testMove(); - void testRename(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // FileTest_INCLUDED +// +// FileTest.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/FileTest.h#1 $ +// +// Definition of the FileTest class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 FileTest_INCLUDED +#define FileTest_INCLUDED + + +#include "Poco/Foundation.h" +#include "CppUnit/TestCase.h" + + +class FileTest: public CppUnit::TestCase +{ +public: + FileTest(const std::string& name); + ~FileTest(); + + void testFileAttributes1(); + void testCreateFile(); + void testFileAttributes2(); + void testCompare(); + void testSwap(); + void testSize(); + void testDirectory(); + void testCopy(); + void testMove(); + void testRename(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // FileTest_INCLUDED diff --git a/Foundation/testsuite/src/FilesystemTestSuite.cpp b/Foundation/testsuite/src/FilesystemTestSuite.cpp index fe1ab1d00..96cf4e0ad 100644 --- a/Foundation/testsuite/src/FilesystemTestSuite.cpp +++ b/Foundation/testsuite/src/FilesystemTestSuite.cpp @@ -1,48 +1,48 @@ -// -// FilesystemTestSuite.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/FilesystemTestSuite.cpp#1 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "FilesystemTestSuite.h" -#include "PathTest.h" -#include "FileTest.h" -#include "GlobTest.h" - - -CppUnit::Test* FilesystemTestSuite::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("FilesystemTestSuite"); - - pSuite->addTest(PathTest::suite()); - pSuite->addTest(FileTest::suite()); - pSuite->addTest(GlobTest::suite()); - - return pSuite; -} +// +// FilesystemTestSuite.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/FilesystemTestSuite.cpp#1 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "FilesystemTestSuite.h" +#include "PathTest.h" +#include "FileTest.h" +#include "GlobTest.h" + + +CppUnit::Test* FilesystemTestSuite::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("FilesystemTestSuite"); + + pSuite->addTest(PathTest::suite()); + pSuite->addTest(FileTest::suite()); + pSuite->addTest(GlobTest::suite()); + + return pSuite; +} diff --git a/Foundation/testsuite/src/FilesystemTestSuite.h b/Foundation/testsuite/src/FilesystemTestSuite.h index a6fa98ed3..34caa4564 100644 --- a/Foundation/testsuite/src/FilesystemTestSuite.h +++ b/Foundation/testsuite/src/FilesystemTestSuite.h @@ -1,49 +1,49 @@ -// -// FilesystemTestSuite.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/FilesystemTestSuite.h#1 $ -// -// Definition of the FilesystemTestSuite class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 FilesystemTestSuite_INCLUDED -#define FilesystemTestSuite_INCLUDED - - -#include "CppUnit/TestSuite.h" - - -class FilesystemTestSuite -{ -public: - static CppUnit::Test* suite(); -}; - - -#endif // FilesystemTestSuite_INCLUDED +// +// FilesystemTestSuite.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/FilesystemTestSuite.h#1 $ +// +// Definition of the FilesystemTestSuite class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 FilesystemTestSuite_INCLUDED +#define FilesystemTestSuite_INCLUDED + + +#include "CppUnit/TestSuite.h" + + +class FilesystemTestSuite +{ +public: + static CppUnit::Test* suite(); +}; + + +#endif // FilesystemTestSuite_INCLUDED diff --git a/Foundation/testsuite/src/FormatTest.cpp b/Foundation/testsuite/src/FormatTest.cpp index c30d78e4a..8f438c3ca 100644 --- a/Foundation/testsuite/src/FormatTest.cpp +++ b/Foundation/testsuite/src/FormatTest.cpp @@ -1,310 +1,310 @@ -// -// FormatTest.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/FormatTest.cpp#1 $ -// -// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. -// 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. -// -// 3. Redistributions in any form must be accompanied by information on -// how to obtain complete source code for this software and any -// accompanying software that uses this software. The source code -// must either be included in the distribution or be available for no -// more than the cost of distribution plus a nominal fee, and must be -// freely redistributable under reasonable conditions. For an -// executable file, complete source code means the source code for all -// modules it contains. It does not include source code for modules or -// files that typically accompany the major components of the operating -// system on which the executable file runs. -// -// 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. -// - - -#include "FormatTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/Format.h" -#include "Poco/Exception.h" - - -using Poco::format; -using Poco::BadCastException; -using Poco::Int64; -using Poco::UInt64; - - -FormatTest::FormatTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -FormatTest::~FormatTest() -{ -} - - -void FormatTest::testChar() -{ - char c = 'a'; - std::string s(format("%c", c)); - assert (s == "a"); - s = format("%2c", c); - assert (s == " a"); - s = format("%-2c", c); - assert (s == "a "); - - try - { - s = format("%c", std::string("foo")); - fail("bad argument - must throw"); - } - catch (BadCastException&) - { - } -} - - -void FormatTest::testInt() -{ - int i = 42; - std::string s(format("%d", i)); - assert (s == "42"); - s = format("%4d", i); - assert (s == " 42"); - s = format("%04d", i); - assert (s == "0042"); - - short h = 42; - s = format("%hd", h); - assert (s == "42"); - s = format("%4hd", h); - assert (s == " 42"); - s = format("%04hd", h); - assert (s == "0042"); - - unsigned short hu = 42; - s = format("%hu", hu); - assert (s == "42"); - s = format("%4hu", hu); - assert (s == " 42"); - s = format("%04hu", hu); - assert (s == "0042"); - - unsigned x = 0x42; - s = format("%x", x); - assert (s == "42"); - s = format("%4x", x); - assert (s == " 42"); - s = format("%04x", x); - assert (s == "0042"); - - unsigned o = 042; - s = format("%o", o); - assert (s == "42"); - s = format("%4o", o); - assert (s == " 42"); - s = format("%04o", o); - assert (s == "0042"); - - unsigned u = 42; - s = format("%u", u); - assert (s == "42"); - s = format("%4u", u); - assert (s == " 42"); - s = format("%04u", u); - assert (s == "0042"); - - long l = 42; - s = format("%ld", l); - assert (s == "42"); - s = format("%4ld", l); - assert (s == " 42"); - s = format("%04ld", l); - assert (s == "0042"); - - unsigned long ul = 42; - s = format("%lu", ul); - assert (s == "42"); - s = format("%4lu", ul); - assert (s == " 42"); - s = format("%04lu", ul); - assert (s == "0042"); - - unsigned long xl = 0x42; - s = format("%lx", xl); - assert (s == "42"); - s = format("%4lx", xl); - assert (s == " 42"); - s = format("%04lx", xl); - assert (s == "0042"); - - Int64 i64 = 42; - s = format("%Ld", i64); - assert (s == "42"); - s = format("%4Ld", i64); - assert (s == " 42"); - s = format("%04Ld", i64); - assert (s == "0042"); - - UInt64 ui64 = 42; - s = format("%Lu", ui64); - assert (s == "42"); - s = format("%4Lu", ui64); - assert (s == " 42"); - s = format("%04Lu", ui64); - assert (s == "0042"); - - x = 0xaa; - s = format("%x", x); - assert (s == "aa"); - s = format("%X", x); - assert (s == "AA"); - - i = 42; - s = format("%+d", i); - assert (s == "+42"); - - i = -42; - s = format("%+d", i); - assert (s == "-42"); - s = format("%d", i); - assert (s == "-42"); - - s = format("%d", i); - assert (s == "-42"); - - x = 0x42; - s = format("%#x", x); - assert (s == "0x42"); - - try - { - s = format("%d", l); - fail("bad argument - must throw"); - } - catch (BadCastException&) - { - } - -} - - -void FormatTest::testFloatFix() -{ - double d = 1.5; - std::string s(format("%f", d)); - assert (s.find("1.50") == 0); - - s = format("%10f", d); - assert (s.find(" 1.50") != std::string::npos); - - s = format("%6.2f", d); - assert (s == " 1.50"); - s = format("%-6.2f", d); - assert (s == "1.50 "); - - float f = 1.5; - s = format("%hf", f); - assert (s.find("1.50") == 0); -} - - -void FormatTest::testFloatSci() -{ - double d = 1.5; - std::string s(format("%e", d)); - assert (s.find("1.50") == 0); - assert (s.find("0e+0") != std::string::npos); - - s = format("%20e", d); - assert (s.find(" 1.50") != std::string::npos); - assert (s.find("0e+0") != std::string::npos); - - s = format("%10.2e", d); - assert (s == " 1.50e+000" || s == " 1.50e+00"); - s = format("%-10.2e", d); - assert (s == "1.50e+000 " || s == "1.50e+00 "); - s = format("%-10.2E", d); - assert (s == "1.50E+000 " || s == "1.50E+00 "); -} - - -void FormatTest::testString() -{ - std::string foo("foo"); - std::string s(format("%s", foo)); - assert (s == "foo"); - - s = format("%5s", foo); - assert (s == " foo"); - - s = format("%-5s", foo); - assert (s == "foo "); -} - - -void FormatTest::testMultiple() -{ - std::string s(format("aaa%dbbb%4dccc", 1, 2)); - assert (s == "aaa1bbb 2ccc"); - - s = format("%%%d%%%d%%%d", 1, 2, 3); - assert (s == "%1%2%3"); - - s = format("%d%d%d%d", 1, 2, 3, 4); - assert (s == "1234"); - - s = format("%d%d%d%d%d", 1, 2, 3, 4, 5); - assert (s == "12345"); - - s = format("%d%d%d%d%d%d", 1, 2, 3, 4, 5, 6); - assert (s == "123456"); -} - - -void FormatTest::setUp() -{ -} - - -void FormatTest::tearDown() -{ -} - - -CppUnit::Test* FormatTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("FormatTest"); - - CppUnit_addTest(pSuite, FormatTest, testChar); - CppUnit_addTest(pSuite, FormatTest, testInt); - CppUnit_addTest(pSuite, FormatTest, testFloatFix); - CppUnit_addTest(pSuite, FormatTest, testFloatSci); - CppUnit_addTest(pSuite, FormatTest, testString); - CppUnit_addTest(pSuite, FormatTest, testMultiple); - - return pSuite; -} +// +// FormatTest.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/FormatTest.cpp#1 $ +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// 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. +// +// 3. Redistributions in any form must be accompanied by information on +// how to obtain complete source code for this software and any +// accompanying software that uses this software. The source code +// must either be included in the distribution or be available for no +// more than the cost of distribution plus a nominal fee, and must be +// freely redistributable under reasonable conditions. For an +// executable file, complete source code means the source code for all +// modules it contains. It does not include source code for modules or +// files that typically accompany the major components of the operating +// system on which the executable file runs. +// +// 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. +// + + +#include "FormatTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/Format.h" +#include "Poco/Exception.h" + + +using Poco::format; +using Poco::BadCastException; +using Poco::Int64; +using Poco::UInt64; + + +FormatTest::FormatTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +FormatTest::~FormatTest() +{ +} + + +void FormatTest::testChar() +{ + char c = 'a'; + std::string s(format("%c", c)); + assert (s == "a"); + s = format("%2c", c); + assert (s == " a"); + s = format("%-2c", c); + assert (s == "a "); + + try + { + s = format("%c", std::string("foo")); + fail("bad argument - must throw"); + } + catch (BadCastException&) + { + } +} + + +void FormatTest::testInt() +{ + int i = 42; + std::string s(format("%d", i)); + assert (s == "42"); + s = format("%4d", i); + assert (s == " 42"); + s = format("%04d", i); + assert (s == "0042"); + + short h = 42; + s = format("%hd", h); + assert (s == "42"); + s = format("%4hd", h); + assert (s == " 42"); + s = format("%04hd", h); + assert (s == "0042"); + + unsigned short hu = 42; + s = format("%hu", hu); + assert (s == "42"); + s = format("%4hu", hu); + assert (s == " 42"); + s = format("%04hu", hu); + assert (s == "0042"); + + unsigned x = 0x42; + s = format("%x", x); + assert (s == "42"); + s = format("%4x", x); + assert (s == " 42"); + s = format("%04x", x); + assert (s == "0042"); + + unsigned o = 042; + s = format("%o", o); + assert (s == "42"); + s = format("%4o", o); + assert (s == " 42"); + s = format("%04o", o); + assert (s == "0042"); + + unsigned u = 42; + s = format("%u", u); + assert (s == "42"); + s = format("%4u", u); + assert (s == " 42"); + s = format("%04u", u); + assert (s == "0042"); + + long l = 42; + s = format("%ld", l); + assert (s == "42"); + s = format("%4ld", l); + assert (s == " 42"); + s = format("%04ld", l); + assert (s == "0042"); + + unsigned long ul = 42; + s = format("%lu", ul); + assert (s == "42"); + s = format("%4lu", ul); + assert (s == " 42"); + s = format("%04lu", ul); + assert (s == "0042"); + + unsigned long xl = 0x42; + s = format("%lx", xl); + assert (s == "42"); + s = format("%4lx", xl); + assert (s == " 42"); + s = format("%04lx", xl); + assert (s == "0042"); + + Int64 i64 = 42; + s = format("%Ld", i64); + assert (s == "42"); + s = format("%4Ld", i64); + assert (s == " 42"); + s = format("%04Ld", i64); + assert (s == "0042"); + + UInt64 ui64 = 42; + s = format("%Lu", ui64); + assert (s == "42"); + s = format("%4Lu", ui64); + assert (s == " 42"); + s = format("%04Lu", ui64); + assert (s == "0042"); + + x = 0xaa; + s = format("%x", x); + assert (s == "aa"); + s = format("%X", x); + assert (s == "AA"); + + i = 42; + s = format("%+d", i); + assert (s == "+42"); + + i = -42; + s = format("%+d", i); + assert (s == "-42"); + s = format("%d", i); + assert (s == "-42"); + + s = format("%d", i); + assert (s == "-42"); + + x = 0x42; + s = format("%#x", x); + assert (s == "0x42"); + + try + { + s = format("%d", l); + fail("bad argument - must throw"); + } + catch (BadCastException&) + { + } + +} + + +void FormatTest::testFloatFix() +{ + double d = 1.5; + std::string s(format("%f", d)); + assert (s.find("1.50") == 0); + + s = format("%10f", d); + assert (s.find(" 1.50") != std::string::npos); + + s = format("%6.2f", d); + assert (s == " 1.50"); + s = format("%-6.2f", d); + assert (s == "1.50 "); + + float f = 1.5; + s = format("%hf", f); + assert (s.find("1.50") == 0); +} + + +void FormatTest::testFloatSci() +{ + double d = 1.5; + std::string s(format("%e", d)); + assert (s.find("1.50") == 0); + assert (s.find("0e+0") != std::string::npos); + + s = format("%20e", d); + assert (s.find(" 1.50") != std::string::npos); + assert (s.find("0e+0") != std::string::npos); + + s = format("%10.2e", d); + assert (s == " 1.50e+000" || s == " 1.50e+00"); + s = format("%-10.2e", d); + assert (s == "1.50e+000 " || s == "1.50e+00 "); + s = format("%-10.2E", d); + assert (s == "1.50E+000 " || s == "1.50E+00 "); +} + + +void FormatTest::testString() +{ + std::string foo("foo"); + std::string s(format("%s", foo)); + assert (s == "foo"); + + s = format("%5s", foo); + assert (s == " foo"); + + s = format("%-5s", foo); + assert (s == "foo "); +} + + +void FormatTest::testMultiple() +{ + std::string s(format("aaa%dbbb%4dccc", 1, 2)); + assert (s == "aaa1bbb 2ccc"); + + s = format("%%%d%%%d%%%d", 1, 2, 3); + assert (s == "%1%2%3"); + + s = format("%d%d%d%d", 1, 2, 3, 4); + assert (s == "1234"); + + s = format("%d%d%d%d%d", 1, 2, 3, 4, 5); + assert (s == "12345"); + + s = format("%d%d%d%d%d%d", 1, 2, 3, 4, 5, 6); + assert (s == "123456"); +} + + +void FormatTest::setUp() +{ +} + + +void FormatTest::tearDown() +{ +} + + +CppUnit::Test* FormatTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("FormatTest"); + + CppUnit_addTest(pSuite, FormatTest, testChar); + CppUnit_addTest(pSuite, FormatTest, testInt); + CppUnit_addTest(pSuite, FormatTest, testFloatFix); + CppUnit_addTest(pSuite, FormatTest, testFloatSci); + CppUnit_addTest(pSuite, FormatTest, testString); + CppUnit_addTest(pSuite, FormatTest, testMultiple); + + return pSuite; +} diff --git a/Foundation/testsuite/src/FormatTest.h b/Foundation/testsuite/src/FormatTest.h index b1e9c99de..7831eb51e 100644 --- a/Foundation/testsuite/src/FormatTest.h +++ b/Foundation/testsuite/src/FormatTest.h @@ -1,78 +1,78 @@ -// -// FormatTest.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/FormatTest.h#1 $ -// -// Definition of the FormatTest class. -// -// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. -// 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. -// -// 3. Redistributions in any form must be accompanied by information on -// how to obtain complete source code for this software and any -// accompanying software that uses this software. The source code -// must either be included in the distribution or be available for no -// more than the cost of distribution plus a nominal fee, and must be -// freely redistributable under reasonable conditions. For an -// executable file, complete source code means the source code for all -// modules it contains. It does not include source code for modules or -// files that typically accompany the major components of the operating -// system on which the executable file runs. -// -// 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 FormatTest_INCLUDED -#define FormatTest_INCLUDED - - -#include "Poco/Foundation.h" -#include "CppUnit/TestCase.h" - - -class FormatTest: public CppUnit::TestCase -{ -public: - FormatTest(const std::string& name); - ~FormatTest(); - - void testChar(); - void testInt(); - void testFloatFix(); - void testFloatSci(); - void testString(); - void testMultiple(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // FormatTest_INCLUDED +// +// FormatTest.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/FormatTest.h#1 $ +// +// Definition of the FormatTest class. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// 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. +// +// 3. Redistributions in any form must be accompanied by information on +// how to obtain complete source code for this software and any +// accompanying software that uses this software. The source code +// must either be included in the distribution or be available for no +// more than the cost of distribution plus a nominal fee, and must be +// freely redistributable under reasonable conditions. For an +// executable file, complete source code means the source code for all +// modules it contains. It does not include source code for modules or +// files that typically accompany the major components of the operating +// system on which the executable file runs. +// +// 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 FormatTest_INCLUDED +#define FormatTest_INCLUDED + + +#include "Poco/Foundation.h" +#include "CppUnit/TestCase.h" + + +class FormatTest: public CppUnit::TestCase +{ +public: + FormatTest(const std::string& name); + ~FormatTest(); + + void testChar(); + void testInt(); + void testFloatFix(); + void testFloatSci(); + void testString(); + void testMultiple(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // FormatTest_INCLUDED diff --git a/Foundation/testsuite/src/FoundationTestSuite.cpp b/Foundation/testsuite/src/FoundationTestSuite.cpp index 18bf0e1d8..1717faa31 100644 --- a/Foundation/testsuite/src/FoundationTestSuite.cpp +++ b/Foundation/testsuite/src/FoundationTestSuite.cpp @@ -1,73 +1,73 @@ -// -// FoundationTestSuite.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/FoundationTestSuite.cpp#1 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "FoundationTestSuite.h" -#include "CoreTestSuite.h" -#include "DateTimeTestSuite.h" -#include "StreamsTestSuite.h" -#include "CryptTestSuite.h" -#include "NotificationsTestSuite.h" -#include "ThreadingTestSuite.h" -#include "SharedLibraryTestSuite.h" -#include "LoggingTestSuite.h" -#include "FilesystemTestSuite.h" -#include "UUIDTestSuite.h" -#include "TextTestSuite.h" -#include "URITestSuite.h" -#include "ProcessesTestSuite.h" -#include "TaskTestSuite.h" -#include "EventTestSuite.h" -#include "CacheTestSuite.h" - -CppUnit::Test* FoundationTestSuite::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("FoundationTestSuite"); - - pSuite->addTest(CoreTestSuite::suite()); - pSuite->addTest(DateTimeTestSuite::suite()); - pSuite->addTest(StreamsTestSuite::suite()); - pSuite->addTest(CryptTestSuite::suite()); - pSuite->addTest(NotificationsTestSuite::suite()); - pSuite->addTest(ThreadingTestSuite::suite()); - pSuite->addTest(SharedLibraryTestSuite::suite()); - pSuite->addTest(LoggingTestSuite::suite()); - pSuite->addTest(FilesystemTestSuite::suite()); - pSuite->addTest(UUIDTestSuite::suite()); - pSuite->addTest(TextTestSuite::suite()); - pSuite->addTest(URITestSuite::suite()); - pSuite->addTest(ProcessesTestSuite::suite()); - pSuite->addTest(TaskTestSuite::suite()); - pSuite->addTest(EventTestSuite::suite()); - pSuite->addTest(CacheTestSuite::suite()); - - return pSuite; -} +// +// FoundationTestSuite.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/FoundationTestSuite.cpp#1 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "FoundationTestSuite.h" +#include "CoreTestSuite.h" +#include "DateTimeTestSuite.h" +#include "StreamsTestSuite.h" +#include "CryptTestSuite.h" +#include "NotificationsTestSuite.h" +#include "ThreadingTestSuite.h" +#include "SharedLibraryTestSuite.h" +#include "LoggingTestSuite.h" +#include "FilesystemTestSuite.h" +#include "UUIDTestSuite.h" +#include "TextTestSuite.h" +#include "URITestSuite.h" +#include "ProcessesTestSuite.h" +#include "TaskTestSuite.h" +#include "EventTestSuite.h" +#include "CacheTestSuite.h" + +CppUnit::Test* FoundationTestSuite::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("FoundationTestSuite"); + + pSuite->addTest(CoreTestSuite::suite()); + pSuite->addTest(DateTimeTestSuite::suite()); + pSuite->addTest(StreamsTestSuite::suite()); + pSuite->addTest(CryptTestSuite::suite()); + pSuite->addTest(NotificationsTestSuite::suite()); + pSuite->addTest(ThreadingTestSuite::suite()); + pSuite->addTest(SharedLibraryTestSuite::suite()); + pSuite->addTest(LoggingTestSuite::suite()); + pSuite->addTest(FilesystemTestSuite::suite()); + pSuite->addTest(UUIDTestSuite::suite()); + pSuite->addTest(TextTestSuite::suite()); + pSuite->addTest(URITestSuite::suite()); + pSuite->addTest(ProcessesTestSuite::suite()); + pSuite->addTest(TaskTestSuite::suite()); + pSuite->addTest(EventTestSuite::suite()); + pSuite->addTest(CacheTestSuite::suite()); + + return pSuite; +} diff --git a/Foundation/testsuite/src/FoundationTestSuite.h b/Foundation/testsuite/src/FoundationTestSuite.h index 4b4359877..0ec65ba85 100644 --- a/Foundation/testsuite/src/FoundationTestSuite.h +++ b/Foundation/testsuite/src/FoundationTestSuite.h @@ -1,49 +1,49 @@ -// -// FoundationTestSuite.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/FoundationTestSuite.h#1 $ -// -// Definition of the FoundationTestSuite class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 FoundationTestSuite_INCLUDED -#define FoundationTestSuite_INCLUDED - - -#include "CppUnit/TestSuite.h" - - -class FoundationTestSuite -{ -public: - static CppUnit::Test* suite(); -}; - - -#endif // FoundationTestSuite_INCLUDED +// +// FoundationTestSuite.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/FoundationTestSuite.h#1 $ +// +// Definition of the FoundationTestSuite class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 FoundationTestSuite_INCLUDED +#define FoundationTestSuite_INCLUDED + + +#include "CppUnit/TestSuite.h" + + +class FoundationTestSuite +{ +public: + static CppUnit::Test* suite(); +}; + + +#endif // FoundationTestSuite_INCLUDED diff --git a/Foundation/testsuite/src/GlobTest.cpp b/Foundation/testsuite/src/GlobTest.cpp index 667ceb061..a6ce7c7ed 100644 --- a/Foundation/testsuite/src/GlobTest.cpp +++ b/Foundation/testsuite/src/GlobTest.cpp @@ -1,445 +1,445 @@ -// -// GlobTest.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/GlobTest.cpp#1 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "GlobTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/Glob.h" -#include "Poco/File.h" -#include "Poco/Path.h" -#include - - -using Poco::Glob; -using Poco::File; -using Poco::Path; - - -GlobTest::GlobTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -GlobTest::~GlobTest() -{ -} - - -void GlobTest::testMatchChars() -{ - Glob g1("a"); - assert (g1.match("a")); - assert (!g1.match("b")); - assert (!g1.match("aa")); - assert (!g1.match("")); - - Glob g2("ab"); - assert (g2.match("ab")); - assert (!g2.match("aab")); - assert (!g2.match("abab")); -} - - -void GlobTest::testMatchQM() -{ - Glob g1("?"); - assert (g1.match("a")); - assert (g1.match("b")); - assert (!g1.match("aa")); - assert (g1.match(".")); - - Glob g2("\\?"); - assert (g2.match("?")); - assert (!g2.match("a")); - assert (!g2.match("ab")); - - Glob g3("a?"); - assert (g3.match("aa")); - assert (g3.match("az")); - assert (!g3.match("a")); - assert (!g3.match("aaa")); - - Glob g4("??"); - assert (g4.match("aa")); - assert (g4.match("ab")); - assert (!g4.match("a")); - assert (!g4.match("abc")); - - Glob g5("?a?"); - assert (g5.match("aaa")); - assert (g5.match("bac")); - assert (!g5.match("bbc")); - assert (!g5.match("ba")); - assert (!g5.match("ab")); - - Glob g6("a\\?"); - assert (g6.match("a?")); - assert (!g6.match("az")); - assert (!g6.match("a")); - - Glob g7("?", Glob::GLOB_DOT_SPECIAL); - assert (g7.match("a")); - assert (g7.match("b")); - assert (!g7.match("aa")); - assert (!g7.match(".")); -} - - -void GlobTest::testMatchAsterisk() -{ - Glob g1("*"); - assert (g1.match("")); - assert (g1.match("a")); - assert (g1.match("ab")); - assert (g1.match("abc")); - assert (g1.match(".")); - - Glob g2("a*"); - assert (g2.match("a")); - assert (g2.match("aa")); - assert (g2.match("abc")); - assert (!g2.match("b")); - assert (!g2.match("ba")); - - Glob g3("ab*"); - assert (g3.match("ab")); - assert (g3.match("abc")); - assert (g3.match("abab")); - assert (!g3.match("ac")); - assert (!g3.match("baab")); - - Glob g4("*a"); - assert (g4.match("a")); - assert (g4.match("ba")); - assert (g4.match("aa")); - assert (g4.match("aaaaaa")); - assert (g4.match("bbbbba")); - assert (!g4.match("b")); - assert (!g4.match("ab")); - assert (!g4.match("aaab")); - - Glob g5("a*a"); - assert (g5.match("aa")); - assert (g5.match("aba")); - assert (g5.match("abba")); - assert (!g5.match("aab")); - assert (!g5.match("aaab")); - assert (!g5.match("baaaa")); - - Glob g6("a*b*c"); - assert (g6.match("abc")); - assert (g6.match("aabbcc")); - assert (g6.match("abcbbc")); - assert (g6.match("aaaabbbbcccc")); - assert (!g6.match("aaaabbbcb")); - - Glob g7("a*b*"); - assert (g7.match("aaabbb")); - assert (g7.match("abababab")); - assert (g7.match("ab")); - assert (g7.match("aaaaab")); - assert (!g7.match("a")); - assert (!g7.match("aa")); - assert (!g7.match("aaa")); - - Glob g8("**"); - assert (g1.match("")); - assert (g1.match("a")); - assert (g1.match("ab")); - assert (g1.match("abc")); - - Glob g9("a\\*"); - assert (g9.match("a*")); - assert (!g9.match("aa")); - assert (!g9.match("a")); - - Glob g10("a*\\*"); - assert (g10.match("a*")); - assert (g10.match("aaa*")); - assert (!g10.match("a")); - assert (!g10.match("aa")); - - Glob g11("*", Glob::GLOB_DOT_SPECIAL); - assert (g11.match("")); - assert (g11.match("a")); - assert (g11.match("ab")); - assert (g11.match("abc")); - assert (!g11.match(".")); -} - - -void GlobTest::testMatchRange() -{ - Glob g1("[a]"); - assert (g1.match("a")); - assert (!g1.match("b")); - assert (!g1.match("aa")); - - Glob g2("[ab]"); - assert (g2.match("a")); - assert (g2.match("b")); - assert (!g2.match("c")); - assert (!g2.match("ab")); - - Glob g3("[abc]"); - assert (g3.match("a")); - assert (g3.match("b")); - assert (g3.match("c")); - assert (!g3.match("ab")); - - Glob g4("[a-z]"); - assert (g4.match("a")); - assert (g4.match("z")); - assert (!g4.match("A")); - - Glob g5("[!a]"); - assert (g5.match("b")); - assert (g5.match("c")); - assert (!g5.match("a")); - assert (!g5.match("bb")); - - Glob g6("[!a-z]"); - assert (g6.match("A")); - assert (!g6.match("a")); - assert (!g6.match("z")); - - Glob g7("[0-9a-zA-Z_]"); - assert (g7.match("0")); - assert (g7.match("1")); - assert (g7.match("8")); - assert (g7.match("9")); - assert (g7.match("a")); - assert (g7.match("b")); - assert (g7.match("z")); - assert (g7.match("A")); - assert (g7.match("Z")); - assert (g7.match("_")); - assert (!g7.match("-")); - - Glob g8("[1-3]"); - assert (g8.match("1")); - assert (g8.match("2")); - assert (g8.match("3")); - assert (!g8.match("0")); - assert (!g8.match("4")); - - Glob g9("[!1-3]"); - assert (g9.match("0")); - assert (g9.match("4")); - assert (!g9.match("1")); - assert (!g9.match("2")); - assert (!g9.match("3")); - - Glob g10("[\\!a]"); - assert (g10.match("!")); - assert (g10.match("a")); - assert (!g10.match("x")); - - Glob g11("[a\\-c]"); - assert (g11.match("a")); - assert (g11.match("c")); - assert (g11.match("-")); - assert (!g11.match("b")); - - Glob g12("[\\]]"); - assert (g12.match("]")); - assert (!g12.match("[")); - - Glob g13("[[\\]]"); - assert (g13.match("[")); - assert (g13.match("]")); - assert (!g13.match("x")); - - Glob g14("\\[]"); - assert (g14.match("[]")); - assert (!g14.match("[[")); - - Glob g15("a[bc]"); - assert (g15.match("ab")); - assert (g15.match("ac")); - assert (!g15.match("a")); - assert (!g15.match("aa")); - - Glob g16("[ab]c"); - assert (g16.match("ac")); - assert (g16.match("bc")); - assert (!g16.match("a")); - assert (!g16.match("b")); - assert (!g16.match("c")); - assert (!g16.match("aa")); -} - - -void GlobTest::testMisc() -{ - Glob g1("*.cpp"); - assert (g1.match("Glob.cpp")); - assert (!g1.match("Glob.h")); - - Glob g2("*.[hc]"); - assert (g2.match("foo.c")); - assert (g2.match("foo.h")); - assert (!g2.match("foo.i")); - - Glob g3("*.*"); - assert (g3.match("foo.cpp")); - assert (g3.match("foo.h")); - assert (g3.match("foo.")); - assert (!g3.match("foo")); - - Glob g4("File*.?pp"); - assert (g4.match("File.hpp")); - assert (g4.match("File.cpp")); - assert (g4.match("Filesystem.hpp")); - assert (!g4.match("File.h")); - - Glob g5("File*.[ch]*"); - assert (g5.match("File.hpp")); - assert (g5.match("File.cpp")); - assert (g5.match("Filesystem.hpp")); - assert (g5.match("File.h")); - assert (g5.match("Filesystem.cp")); -} - - -void GlobTest::testGlob() -{ - createFile("globtest/Makefile"); - createFile("globtest/.hidden"); - createFile("globtest/include/one.h"); - createFile("globtest/include/two.h"); - createFile("globtest/src/one.c"); - createFile("globtest/src/two.c"); - createFile("globtest/src/main.c"); - createFile("globtest/testsuite/src/test.h"); - createFile("globtest/testsuite/src/test.c"); - createFile("globtest/testsuite/src/main.c"); - - std::set files; - Glob::glob("globtest/*", files); - translatePaths(files); - assert (files.size() == 5); - assert (files.find("globtest/Makefile") != files.end()); - assert (files.find("globtest/.hidden") != files.end()); - assert (files.find("globtest/include/") != files.end()); - assert (files.find("globtest/src/") != files.end()); - assert (files.find("globtest/testsuite/") != files.end()); - - files.clear(); - Glob::glob("globtest/*/*.[hc]", files); - translatePaths(files); - assert (files.size() == 5); - assert (files.find("globtest/include/one.h") != files.end()); - assert (files.find("globtest/include/two.h") != files.end()); - assert (files.find("globtest/src/one.c") != files.end()); - assert (files.find("globtest/src/one.c") != files.end()); - assert (files.find("globtest/src/main.c") != files.end()); - - files.clear(); - Glob::glob("gl?bt?st/*/*/*.c", files); - translatePaths(files); - assert (files.size() == 2); - assert (files.find("globtest/testsuite/src/test.c") != files.end()); - assert (files.find("globtest/testsuite/src/main.c") != files.end()); - - files.clear(); - Glob::glob("globtest/*/src/*", files); - translatePaths(files); - assert (files.size() == 3); - assert (files.find("globtest/testsuite/src/test.h") != files.end()); - assert (files.find("globtest/testsuite/src/test.c") != files.end()); - assert (files.find("globtest/testsuite/src/main.c") != files.end()); - - files.clear(); - Glob::glob("globtest/*/", files); - translatePaths(files); - assert (files.size() == 3); - assert (files.find("globtest/include/") != files.end()); - assert (files.find("globtest/src/") != files.end()); - assert (files.find("globtest/testsuite/") != files.end()); - - files.clear(); - Glob::glob("../*/globtest/*/", files); - translatePaths(files); - assert (files.size() == 3); - - File dir("globtest"); - dir.remove(true); -} - - -void GlobTest::createFile(const std::string& path) -{ - Path p(path, Path::PATH_UNIX); - File dir(p.parent()); - dir.createDirectories(); - std::ofstream ostr(path.c_str()); - ostr << path << std::endl; -} - - -void GlobTest::translatePaths(std::set& paths) -{ - std::set translated; - for (std::set::const_iterator it = paths.begin(); it != paths.end(); ++it) - { - Path p(*it); - std::string tp(p.toString(Path::PATH_UNIX)); - translated.insert(tp); - } - paths = translated; -} - - -void GlobTest::setUp() -{ -} - - -void GlobTest::tearDown() -{ -} - - -CppUnit::Test* GlobTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("GlobTest"); - - CppUnit_addTest(pSuite, GlobTest, testMatchChars); - CppUnit_addTest(pSuite, GlobTest, testMatchQM); - CppUnit_addTest(pSuite, GlobTest, testMatchAsterisk); - CppUnit_addTest(pSuite, GlobTest, testMatchRange); - CppUnit_addTest(pSuite, GlobTest, testMisc); - CppUnit_addTest(pSuite, GlobTest, testGlob); - - return pSuite; -} +// +// GlobTest.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/GlobTest.cpp#1 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "GlobTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/Glob.h" +#include "Poco/File.h" +#include "Poco/Path.h" +#include + + +using Poco::Glob; +using Poco::File; +using Poco::Path; + + +GlobTest::GlobTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +GlobTest::~GlobTest() +{ +} + + +void GlobTest::testMatchChars() +{ + Glob g1("a"); + assert (g1.match("a")); + assert (!g1.match("b")); + assert (!g1.match("aa")); + assert (!g1.match("")); + + Glob g2("ab"); + assert (g2.match("ab")); + assert (!g2.match("aab")); + assert (!g2.match("abab")); +} + + +void GlobTest::testMatchQM() +{ + Glob g1("?"); + assert (g1.match("a")); + assert (g1.match("b")); + assert (!g1.match("aa")); + assert (g1.match(".")); + + Glob g2("\\?"); + assert (g2.match("?")); + assert (!g2.match("a")); + assert (!g2.match("ab")); + + Glob g3("a?"); + assert (g3.match("aa")); + assert (g3.match("az")); + assert (!g3.match("a")); + assert (!g3.match("aaa")); + + Glob g4("??"); + assert (g4.match("aa")); + assert (g4.match("ab")); + assert (!g4.match("a")); + assert (!g4.match("abc")); + + Glob g5("?a?"); + assert (g5.match("aaa")); + assert (g5.match("bac")); + assert (!g5.match("bbc")); + assert (!g5.match("ba")); + assert (!g5.match("ab")); + + Glob g6("a\\?"); + assert (g6.match("a?")); + assert (!g6.match("az")); + assert (!g6.match("a")); + + Glob g7("?", Glob::GLOB_DOT_SPECIAL); + assert (g7.match("a")); + assert (g7.match("b")); + assert (!g7.match("aa")); + assert (!g7.match(".")); +} + + +void GlobTest::testMatchAsterisk() +{ + Glob g1("*"); + assert (g1.match("")); + assert (g1.match("a")); + assert (g1.match("ab")); + assert (g1.match("abc")); + assert (g1.match(".")); + + Glob g2("a*"); + assert (g2.match("a")); + assert (g2.match("aa")); + assert (g2.match("abc")); + assert (!g2.match("b")); + assert (!g2.match("ba")); + + Glob g3("ab*"); + assert (g3.match("ab")); + assert (g3.match("abc")); + assert (g3.match("abab")); + assert (!g3.match("ac")); + assert (!g3.match("baab")); + + Glob g4("*a"); + assert (g4.match("a")); + assert (g4.match("ba")); + assert (g4.match("aa")); + assert (g4.match("aaaaaa")); + assert (g4.match("bbbbba")); + assert (!g4.match("b")); + assert (!g4.match("ab")); + assert (!g4.match("aaab")); + + Glob g5("a*a"); + assert (g5.match("aa")); + assert (g5.match("aba")); + assert (g5.match("abba")); + assert (!g5.match("aab")); + assert (!g5.match("aaab")); + assert (!g5.match("baaaa")); + + Glob g6("a*b*c"); + assert (g6.match("abc")); + assert (g6.match("aabbcc")); + assert (g6.match("abcbbc")); + assert (g6.match("aaaabbbbcccc")); + assert (!g6.match("aaaabbbcb")); + + Glob g7("a*b*"); + assert (g7.match("aaabbb")); + assert (g7.match("abababab")); + assert (g7.match("ab")); + assert (g7.match("aaaaab")); + assert (!g7.match("a")); + assert (!g7.match("aa")); + assert (!g7.match("aaa")); + + Glob g8("**"); + assert (g1.match("")); + assert (g1.match("a")); + assert (g1.match("ab")); + assert (g1.match("abc")); + + Glob g9("a\\*"); + assert (g9.match("a*")); + assert (!g9.match("aa")); + assert (!g9.match("a")); + + Glob g10("a*\\*"); + assert (g10.match("a*")); + assert (g10.match("aaa*")); + assert (!g10.match("a")); + assert (!g10.match("aa")); + + Glob g11("*", Glob::GLOB_DOT_SPECIAL); + assert (g11.match("")); + assert (g11.match("a")); + assert (g11.match("ab")); + assert (g11.match("abc")); + assert (!g11.match(".")); +} + + +void GlobTest::testMatchRange() +{ + Glob g1("[a]"); + assert (g1.match("a")); + assert (!g1.match("b")); + assert (!g1.match("aa")); + + Glob g2("[ab]"); + assert (g2.match("a")); + assert (g2.match("b")); + assert (!g2.match("c")); + assert (!g2.match("ab")); + + Glob g3("[abc]"); + assert (g3.match("a")); + assert (g3.match("b")); + assert (g3.match("c")); + assert (!g3.match("ab")); + + Glob g4("[a-z]"); + assert (g4.match("a")); + assert (g4.match("z")); + assert (!g4.match("A")); + + Glob g5("[!a]"); + assert (g5.match("b")); + assert (g5.match("c")); + assert (!g5.match("a")); + assert (!g5.match("bb")); + + Glob g6("[!a-z]"); + assert (g6.match("A")); + assert (!g6.match("a")); + assert (!g6.match("z")); + + Glob g7("[0-9a-zA-Z_]"); + assert (g7.match("0")); + assert (g7.match("1")); + assert (g7.match("8")); + assert (g7.match("9")); + assert (g7.match("a")); + assert (g7.match("b")); + assert (g7.match("z")); + assert (g7.match("A")); + assert (g7.match("Z")); + assert (g7.match("_")); + assert (!g7.match("-")); + + Glob g8("[1-3]"); + assert (g8.match("1")); + assert (g8.match("2")); + assert (g8.match("3")); + assert (!g8.match("0")); + assert (!g8.match("4")); + + Glob g9("[!1-3]"); + assert (g9.match("0")); + assert (g9.match("4")); + assert (!g9.match("1")); + assert (!g9.match("2")); + assert (!g9.match("3")); + + Glob g10("[\\!a]"); + assert (g10.match("!")); + assert (g10.match("a")); + assert (!g10.match("x")); + + Glob g11("[a\\-c]"); + assert (g11.match("a")); + assert (g11.match("c")); + assert (g11.match("-")); + assert (!g11.match("b")); + + Glob g12("[\\]]"); + assert (g12.match("]")); + assert (!g12.match("[")); + + Glob g13("[[\\]]"); + assert (g13.match("[")); + assert (g13.match("]")); + assert (!g13.match("x")); + + Glob g14("\\[]"); + assert (g14.match("[]")); + assert (!g14.match("[[")); + + Glob g15("a[bc]"); + assert (g15.match("ab")); + assert (g15.match("ac")); + assert (!g15.match("a")); + assert (!g15.match("aa")); + + Glob g16("[ab]c"); + assert (g16.match("ac")); + assert (g16.match("bc")); + assert (!g16.match("a")); + assert (!g16.match("b")); + assert (!g16.match("c")); + assert (!g16.match("aa")); +} + + +void GlobTest::testMisc() +{ + Glob g1("*.cpp"); + assert (g1.match("Glob.cpp")); + assert (!g1.match("Glob.h")); + + Glob g2("*.[hc]"); + assert (g2.match("foo.c")); + assert (g2.match("foo.h")); + assert (!g2.match("foo.i")); + + Glob g3("*.*"); + assert (g3.match("foo.cpp")); + assert (g3.match("foo.h")); + assert (g3.match("foo.")); + assert (!g3.match("foo")); + + Glob g4("File*.?pp"); + assert (g4.match("File.hpp")); + assert (g4.match("File.cpp")); + assert (g4.match("Filesystem.hpp")); + assert (!g4.match("File.h")); + + Glob g5("File*.[ch]*"); + assert (g5.match("File.hpp")); + assert (g5.match("File.cpp")); + assert (g5.match("Filesystem.hpp")); + assert (g5.match("File.h")); + assert (g5.match("Filesystem.cp")); +} + + +void GlobTest::testGlob() +{ + createFile("globtest/Makefile"); + createFile("globtest/.hidden"); + createFile("globtest/include/one.h"); + createFile("globtest/include/two.h"); + createFile("globtest/src/one.c"); + createFile("globtest/src/two.c"); + createFile("globtest/src/main.c"); + createFile("globtest/testsuite/src/test.h"); + createFile("globtest/testsuite/src/test.c"); + createFile("globtest/testsuite/src/main.c"); + + std::set files; + Glob::glob("globtest/*", files); + translatePaths(files); + assert (files.size() == 5); + assert (files.find("globtest/Makefile") != files.end()); + assert (files.find("globtest/.hidden") != files.end()); + assert (files.find("globtest/include/") != files.end()); + assert (files.find("globtest/src/") != files.end()); + assert (files.find("globtest/testsuite/") != files.end()); + + files.clear(); + Glob::glob("globtest/*/*.[hc]", files); + translatePaths(files); + assert (files.size() == 5); + assert (files.find("globtest/include/one.h") != files.end()); + assert (files.find("globtest/include/two.h") != files.end()); + assert (files.find("globtest/src/one.c") != files.end()); + assert (files.find("globtest/src/one.c") != files.end()); + assert (files.find("globtest/src/main.c") != files.end()); + + files.clear(); + Glob::glob("gl?bt?st/*/*/*.c", files); + translatePaths(files); + assert (files.size() == 2); + assert (files.find("globtest/testsuite/src/test.c") != files.end()); + assert (files.find("globtest/testsuite/src/main.c") != files.end()); + + files.clear(); + Glob::glob("globtest/*/src/*", files); + translatePaths(files); + assert (files.size() == 3); + assert (files.find("globtest/testsuite/src/test.h") != files.end()); + assert (files.find("globtest/testsuite/src/test.c") != files.end()); + assert (files.find("globtest/testsuite/src/main.c") != files.end()); + + files.clear(); + Glob::glob("globtest/*/", files); + translatePaths(files); + assert (files.size() == 3); + assert (files.find("globtest/include/") != files.end()); + assert (files.find("globtest/src/") != files.end()); + assert (files.find("globtest/testsuite/") != files.end()); + + files.clear(); + Glob::glob("../*/globtest/*/", files); + translatePaths(files); + assert (files.size() == 3); + + File dir("globtest"); + dir.remove(true); +} + + +void GlobTest::createFile(const std::string& path) +{ + Path p(path, Path::PATH_UNIX); + File dir(p.parent()); + dir.createDirectories(); + std::ofstream ostr(path.c_str()); + ostr << path << std::endl; +} + + +void GlobTest::translatePaths(std::set& paths) +{ + std::set translated; + for (std::set::const_iterator it = paths.begin(); it != paths.end(); ++it) + { + Path p(*it); + std::string tp(p.toString(Path::PATH_UNIX)); + translated.insert(tp); + } + paths = translated; +} + + +void GlobTest::setUp() +{ +} + + +void GlobTest::tearDown() +{ +} + + +CppUnit::Test* GlobTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("GlobTest"); + + CppUnit_addTest(pSuite, GlobTest, testMatchChars); + CppUnit_addTest(pSuite, GlobTest, testMatchQM); + CppUnit_addTest(pSuite, GlobTest, testMatchAsterisk); + CppUnit_addTest(pSuite, GlobTest, testMatchRange); + CppUnit_addTest(pSuite, GlobTest, testMisc); + CppUnit_addTest(pSuite, GlobTest, testGlob); + + return pSuite; +} diff --git a/Foundation/testsuite/src/GlobTest.h b/Foundation/testsuite/src/GlobTest.h index bd79f0d40..085f7bc4b 100644 --- a/Foundation/testsuite/src/GlobTest.h +++ b/Foundation/testsuite/src/GlobTest.h @@ -1,68 +1,68 @@ -// -// GlobTest.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/GlobTest.h#1 $ -// -// Definition of the GlobTest class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 GlobTest_INCLUDED -#define GlobTest_INCLUDED - - -#include "Poco/Foundation.h" -#include "CppUnit/TestCase.h" -#include - - -class GlobTest: public CppUnit::TestCase -{ -public: - GlobTest(const std::string& name); - ~GlobTest(); - - void testMatchChars(); - void testMatchQM(); - void testMatchAsterisk(); - void testMatchRange(); - void testMisc(); - void testGlob(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: - void createFile(const std::string& path); - void translatePaths(std::set& paths); -}; - - -#endif // GlobTest_INCLUDED +// +// GlobTest.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/GlobTest.h#1 $ +// +// Definition of the GlobTest class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 GlobTest_INCLUDED +#define GlobTest_INCLUDED + + +#include "Poco/Foundation.h" +#include "CppUnit/TestCase.h" +#include + + +class GlobTest: public CppUnit::TestCase +{ +public: + GlobTest(const std::string& name); + ~GlobTest(); + + void testMatchChars(); + void testMatchQM(); + void testMatchAsterisk(); + void testMatchRange(); + void testMisc(); + void testGlob(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: + void createFile(const std::string& path); + void translatePaths(std::set& paths); +}; + + +#endif // GlobTest_INCLUDED diff --git a/Foundation/testsuite/src/HMACEngineTest.cpp b/Foundation/testsuite/src/HMACEngineTest.cpp index 29c0ad4cb..2398140e7 100644 --- a/Foundation/testsuite/src/HMACEngineTest.cpp +++ b/Foundation/testsuite/src/HMACEngineTest.cpp @@ -1,99 +1,99 @@ -// -// HMACEngineTest.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/HMACEngineTest.cpp#1 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "HMACEngineTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/HMACEngine.h" -#include "Poco/MD5Engine.h" - - -using Poco::HMACEngine; -using Poco::MD5Engine; -using Poco::DigestEngine; - - -HMACEngineTest::HMACEngineTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -HMACEngineTest::~HMACEngineTest() -{ -} - - -void HMACEngineTest::testHMAC() -{ - // test vectors from RFC 2104 - - std::string key(16, 0x0b); - std::string data("Hi There"); - HMACEngine hmac1(key); - hmac1.update(data); - std::string digest = DigestEngine::digestToHex(hmac1.digest()); - assert (digest == "9294727a3638bb1c13f48ef8158bfc9d"); - - key = "Jefe"; - data = "what do ya want for nothing?"; - HMACEngine hmac2(key); - hmac2.update(data); - digest = DigestEngine::digestToHex(hmac2.digest()); - assert (digest == "750c783e6ab0b503eaa86e310a5db738"); - - key = std::string(16, 0xaa); - data = std::string(50, 0xdd); - HMACEngine hmac3(key); - hmac3.update(data); - digest = DigestEngine::digestToHex(hmac3.digest()); - assert (digest == "56be34521d144c88dbb8c733f0e8b3f6"); -} - - -void HMACEngineTest::setUp() -{ -} - - -void HMACEngineTest::tearDown() -{ -} - - -CppUnit::Test* HMACEngineTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("HMACEngineTest"); - - CppUnit_addTest(pSuite, HMACEngineTest, testHMAC); - - return pSuite; -} +// +// HMACEngineTest.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/HMACEngineTest.cpp#1 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "HMACEngineTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/HMACEngine.h" +#include "Poco/MD5Engine.h" + + +using Poco::HMACEngine; +using Poco::MD5Engine; +using Poco::DigestEngine; + + +HMACEngineTest::HMACEngineTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +HMACEngineTest::~HMACEngineTest() +{ +} + + +void HMACEngineTest::testHMAC() +{ + // test vectors from RFC 2104 + + std::string key(16, 0x0b); + std::string data("Hi There"); + HMACEngine hmac1(key); + hmac1.update(data); + std::string digest = DigestEngine::digestToHex(hmac1.digest()); + assert (digest == "9294727a3638bb1c13f48ef8158bfc9d"); + + key = "Jefe"; + data = "what do ya want for nothing?"; + HMACEngine hmac2(key); + hmac2.update(data); + digest = DigestEngine::digestToHex(hmac2.digest()); + assert (digest == "750c783e6ab0b503eaa86e310a5db738"); + + key = std::string(16, 0xaa); + data = std::string(50, 0xdd); + HMACEngine hmac3(key); + hmac3.update(data); + digest = DigestEngine::digestToHex(hmac3.digest()); + assert (digest == "56be34521d144c88dbb8c733f0e8b3f6"); +} + + +void HMACEngineTest::setUp() +{ +} + + +void HMACEngineTest::tearDown() +{ +} + + +CppUnit::Test* HMACEngineTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("HMACEngineTest"); + + CppUnit_addTest(pSuite, HMACEngineTest, testHMAC); + + return pSuite; +} diff --git a/Foundation/testsuite/src/HMACEngineTest.h b/Foundation/testsuite/src/HMACEngineTest.h index a0989c494..3ca793e1a 100644 --- a/Foundation/testsuite/src/HMACEngineTest.h +++ b/Foundation/testsuite/src/HMACEngineTest.h @@ -1,60 +1,60 @@ -// -// HMACEngineTest.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/HMACEngineTest.h#1 $ -// -// Definition of the HMACEngineTest class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 HMACEngineTest_INCLUDED -#define HMACEngineTest_INCLUDED - - -#include "Poco/Foundation.h" -#include "CppUnit/TestCase.h" - - -class HMACEngineTest: public CppUnit::TestCase -{ -public: - HMACEngineTest(const std::string& name); - ~HMACEngineTest(); - - void testHMAC(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // HMACEngineTest_INCLUDED +// +// HMACEngineTest.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/HMACEngineTest.h#1 $ +// +// Definition of the HMACEngineTest class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 HMACEngineTest_INCLUDED +#define HMACEngineTest_INCLUDED + + +#include "Poco/Foundation.h" +#include "CppUnit/TestCase.h" + + +class HMACEngineTest: public CppUnit::TestCase +{ +public: + HMACEngineTest(const std::string& name); + ~HMACEngineTest(); + + void testHMAC(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // HMACEngineTest_INCLUDED diff --git a/Foundation/testsuite/src/HashTest.cpp b/Foundation/testsuite/src/HashTest.cpp index 50eb823d7..5e7629c34 100644 --- a/Foundation/testsuite/src/HashTest.cpp +++ b/Foundation/testsuite/src/HashTest.cpp @@ -1,226 +1,226 @@ -// -// HashTest.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/HashTest.cpp#2 $ -// -// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "HashTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/HashTable.h" -#include "Poco/NumberFormatter.h" - - -using namespace Poco; - - -HashTest::HashTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -HashTest::~HashTest() -{ -} - - -void HashTest::testInsert() -{ - std::string s1("str1"); - std::string s2("str2"); - HashTable hashTable; - assert (!hashTable.exists(s1)); - hashTable.insert(s1, 13); - assert (hashTable.exists(s1)); - assert (hashTable.get(s1) == 13); - int retVal = 0; - - assert (hashTable.get(s1, retVal)); - assert (retVal == 13); - try - { - hashTable.insert(s1, 22); - failmsg ("duplicate insert must fail"); - } - catch (Exception&){} - try - { - hashTable.get(s2); - failmsg ("getting a non inserted item must fail"); - } - catch (Exception&){} - - assert (!hashTable.exists(s2)); - hashTable.insert(s2, 13); - assert (hashTable.exists(s2)); -} - - -void HashTest::testUpdate() -{ - // add code for second test here - std::string s1("str1"); - std::string s2("str2"); - HashTable hashTable; - hashTable.insert(s1, 13); - hashTable.update(s1, 14); - assert (hashTable.exists(s1)); - assert (hashTable.get(s1) == 14); - int retVal = 0; - - assert (hashTable.get(s1, retVal)); - assert (retVal == 14); - - // updating a non existing item must work too - hashTable.update(s2, 15); - assert (hashTable.get(s2) == 15); -} - - -void HashTest::testOverflow() -{ - HashTable hashTable(13); - for (int i = 0; i < 1024; ++i) - { - hashTable.insert(Poco::NumberFormatter::format(i), i*i); - } - - for (int i = 0; i < 1024; ++i) - { - std::string tmp = Poco::NumberFormatter::format(i); - assert (hashTable.exists(tmp)); - assert (hashTable.get(tmp) == i*i); - } -} - - -void HashTest::testSize() -{ - HashTable hashTable(13); - assert (hashTable.size() == 0); - Poco::UInt32 h1 = hashTable.insert("1", 1); - assert (hashTable.size() == 1); - Poco::UInt32 h2 = hashTable.update("2", 2); - assert (hashTable.size() == 2); - hashTable.remove("1"); - assert (hashTable.size() == 1); - hashTable.remove("3"); - assert (hashTable.size() == 1); - hashTable.removeRaw("2", h2); - assert (hashTable.size() == 0); - hashTable.insert("1", 1); - hashTable.insert("2", 2); - assert (hashTable.size() == 2); - hashTable.clear(); - assert (hashTable.size() == 0); -} - - -void HashTest::testResize() -{ - HashTable hashTable(13); - assert (hashTable.size() == 0); - hashTable.resize(19); - for (int i = 0; i < 1024; ++i) - { - hashTable.insert(Poco::NumberFormatter::format(i), i*i); - } - hashTable.resize(1009); - - for (int i = 0; i < 1024; ++i) - { - std::string tmp = Poco::NumberFormatter::format(i); - assert (hashTable.exists(tmp)); - assert (hashTable.get(tmp) == i*i); - } -} - - -void HashTest::testStatistic() -{ - double relax = 0.001; - HashTable hashTable(13); - assert (hashTable.size() == 0); - HashStatistic stat1(hashTable.currentState()); - assert (stat1.avgEntriesPerHash() < relax && stat1.avgEntriesPerHash() > -relax); - assert (stat1.maxPositionsOfTable() == 13); - assert (stat1.maxEntriesPerHash() == 0); - - hashTable.resize(19); - stat1 = hashTable.currentState(true); - assert (stat1.avgEntriesPerHash() < relax && stat1.avgEntriesPerHash() > -relax); - assert (stat1.maxPositionsOfTable() == 19); - assert (stat1.maxEntriesPerHash() == 0); - assert (stat1.detailedEntriesPerHash().size() == 19); - - for (int i = 0; i < 1024; ++i) - { - hashTable.insert(Poco::NumberFormatter::format(i), i*i); - } - stat1 = hashTable.currentState(true); - double expAvg = 1024.0/ 19; - assert (stat1.avgEntriesPerHash() < (expAvg + relax) && stat1.avgEntriesPerHash() > (expAvg - relax)); - assert (stat1.maxPositionsOfTable() == 19); - assert (stat1.maxEntriesPerHash() > expAvg); - hashTable.resize(1009); - stat1 = hashTable.currentState(true); - - expAvg = 1024.0/ 1009; - - assert (stat1.avgEntriesPerHash() < (expAvg + relax) && stat1.avgEntriesPerHash() > (expAvg - relax)); - assert (stat1.maxPositionsOfTable() == 1009); - assert (stat1.maxEntriesPerHash() > expAvg); -} - - - - -void HashTest::setUp() -{ -} - - -void HashTest::tearDown() -{ -} - - -CppUnit::Test* HashTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("HashTest"); - - CppUnit_addTest(pSuite, HashTest, testInsert); - CppUnit_addTest(pSuite, HashTest, testUpdate); - CppUnit_addTest(pSuite, HashTest, testOverflow); - CppUnit_addTest(pSuite, HashTest, testSize); - CppUnit_addTest(pSuite, HashTest, testResize); - CppUnit_addTest(pSuite, HashTest, testStatistic); - - return pSuite; -} +// +// HashTest.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/HashTest.cpp#2 $ +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "HashTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/HashTable.h" +#include "Poco/NumberFormatter.h" + + +using namespace Poco; + + +HashTest::HashTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +HashTest::~HashTest() +{ +} + + +void HashTest::testInsert() +{ + std::string s1("str1"); + std::string s2("str2"); + HashTable hashTable; + assert (!hashTable.exists(s1)); + hashTable.insert(s1, 13); + assert (hashTable.exists(s1)); + assert (hashTable.get(s1) == 13); + int retVal = 0; + + assert (hashTable.get(s1, retVal)); + assert (retVal == 13); + try + { + hashTable.insert(s1, 22); + failmsg ("duplicate insert must fail"); + } + catch (Exception&){} + try + { + hashTable.get(s2); + failmsg ("getting a non inserted item must fail"); + } + catch (Exception&){} + + assert (!hashTable.exists(s2)); + hashTable.insert(s2, 13); + assert (hashTable.exists(s2)); +} + + +void HashTest::testUpdate() +{ + // add code for second test here + std::string s1("str1"); + std::string s2("str2"); + HashTable hashTable; + hashTable.insert(s1, 13); + hashTable.update(s1, 14); + assert (hashTable.exists(s1)); + assert (hashTable.get(s1) == 14); + int retVal = 0; + + assert (hashTable.get(s1, retVal)); + assert (retVal == 14); + + // updating a non existing item must work too + hashTable.update(s2, 15); + assert (hashTable.get(s2) == 15); +} + + +void HashTest::testOverflow() +{ + HashTable hashTable(13); + for (int i = 0; i < 1024; ++i) + { + hashTable.insert(Poco::NumberFormatter::format(i), i*i); + } + + for (int i = 0; i < 1024; ++i) + { + std::string tmp = Poco::NumberFormatter::format(i); + assert (hashTable.exists(tmp)); + assert (hashTable.get(tmp) == i*i); + } +} + + +void HashTest::testSize() +{ + HashTable hashTable(13); + assert (hashTable.size() == 0); + Poco::UInt32 h1 = hashTable.insert("1", 1); + assert (hashTable.size() == 1); + Poco::UInt32 h2 = hashTable.update("2", 2); + assert (hashTable.size() == 2); + hashTable.remove("1"); + assert (hashTable.size() == 1); + hashTable.remove("3"); + assert (hashTable.size() == 1); + hashTable.removeRaw("2", h2); + assert (hashTable.size() == 0); + hashTable.insert("1", 1); + hashTable.insert("2", 2); + assert (hashTable.size() == 2); + hashTable.clear(); + assert (hashTable.size() == 0); +} + + +void HashTest::testResize() +{ + HashTable hashTable(13); + assert (hashTable.size() == 0); + hashTable.resize(19); + for (int i = 0; i < 1024; ++i) + { + hashTable.insert(Poco::NumberFormatter::format(i), i*i); + } + hashTable.resize(1009); + + for (int i = 0; i < 1024; ++i) + { + std::string tmp = Poco::NumberFormatter::format(i); + assert (hashTable.exists(tmp)); + assert (hashTable.get(tmp) == i*i); + } +} + + +void HashTest::testStatistic() +{ + double relax = 0.001; + HashTable hashTable(13); + assert (hashTable.size() == 0); + HashStatistic stat1(hashTable.currentState()); + assert (stat1.avgEntriesPerHash() < relax && stat1.avgEntriesPerHash() > -relax); + assert (stat1.maxPositionsOfTable() == 13); + assert (stat1.maxEntriesPerHash() == 0); + + hashTable.resize(19); + stat1 = hashTable.currentState(true); + assert (stat1.avgEntriesPerHash() < relax && stat1.avgEntriesPerHash() > -relax); + assert (stat1.maxPositionsOfTable() == 19); + assert (stat1.maxEntriesPerHash() == 0); + assert (stat1.detailedEntriesPerHash().size() == 19); + + for (int i = 0; i < 1024; ++i) + { + hashTable.insert(Poco::NumberFormatter::format(i), i*i); + } + stat1 = hashTable.currentState(true); + double expAvg = 1024.0/ 19; + assert (stat1.avgEntriesPerHash() < (expAvg + relax) && stat1.avgEntriesPerHash() > (expAvg - relax)); + assert (stat1.maxPositionsOfTable() == 19); + assert (stat1.maxEntriesPerHash() > expAvg); + hashTable.resize(1009); + stat1 = hashTable.currentState(true); + + expAvg = 1024.0/ 1009; + + assert (stat1.avgEntriesPerHash() < (expAvg + relax) && stat1.avgEntriesPerHash() > (expAvg - relax)); + assert (stat1.maxPositionsOfTable() == 1009); + assert (stat1.maxEntriesPerHash() > expAvg); +} + + + + +void HashTest::setUp() +{ +} + + +void HashTest::tearDown() +{ +} + + +CppUnit::Test* HashTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("HashTest"); + + CppUnit_addTest(pSuite, HashTest, testInsert); + CppUnit_addTest(pSuite, HashTest, testUpdate); + CppUnit_addTest(pSuite, HashTest, testOverflow); + CppUnit_addTest(pSuite, HashTest, testSize); + CppUnit_addTest(pSuite, HashTest, testResize); + CppUnit_addTest(pSuite, HashTest, testStatistic); + + return pSuite; +} diff --git a/Foundation/testsuite/src/HashTest.h b/Foundation/testsuite/src/HashTest.h index 33d3bc67d..c81f2b1ff 100644 --- a/Foundation/testsuite/src/HashTest.h +++ b/Foundation/testsuite/src/HashTest.h @@ -1,65 +1,65 @@ -// -// HashTest.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/HashTest.h#1 $ -// -// Definition of the HashTest class. -// -// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 HashTest_INCLUDED -#define HashTest_INCLUDED - - -#include "Poco/Foundation.h" -#include "CppUnit/TestCase.h" - - -class HashTest: public CppUnit::TestCase -{ -public: - HashTest(const std::string& name); - ~HashTest(); - - void testInsert(); - void testOverflow(); - void testUpdate(); - void testSize(); - void testResize(); - void testStatistic(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // HashTest_INCLUDED +// +// HashTest.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/HashTest.h#1 $ +// +// Definition of the HashTest class. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 HashTest_INCLUDED +#define HashTest_INCLUDED + + +#include "Poco/Foundation.h" +#include "CppUnit/TestCase.h" + + +class HashTest: public CppUnit::TestCase +{ +public: + HashTest(const std::string& name); + ~HashTest(); + + void testInsert(); + void testOverflow(); + void testUpdate(); + void testSize(); + void testResize(); + void testStatistic(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // HashTest_INCLUDED diff --git a/Foundation/testsuite/src/HexBinaryTest.cpp b/Foundation/testsuite/src/HexBinaryTest.cpp index acf4b14fe..57fd755b6 100644 --- a/Foundation/testsuite/src/HexBinaryTest.cpp +++ b/Foundation/testsuite/src/HexBinaryTest.cpp @@ -1,227 +1,227 @@ -// -// HexBinaryTest.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/HexBinaryTest.cpp#1 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "HexBinaryTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/HexBinaryEncoder.h" -#include "Poco/HexBinaryDecoder.h" -#include "Poco/Exception.h" -#include - - -using Poco::HexBinaryEncoder; -using Poco::HexBinaryDecoder; -using Poco::DataFormatException; - - -HexBinaryTest::HexBinaryTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -HexBinaryTest::~HexBinaryTest() -{ -} - - -void HexBinaryTest::testEncoder() -{ - { - std::ostringstream str; - HexBinaryEncoder encoder(str); - encoder << std::string("\00\01\02\03\04\05", 6); - encoder.close(); - assert (str.str() == "000102030405"); - } - { - std::ostringstream str; - HexBinaryEncoder encoder(str); - encoder << std::string("\00\01\02\03", 4); - encoder.close(); - assert (str.str() == "00010203"); - } - { - std::ostringstream str; - HexBinaryEncoder encoder(str); - encoder << "ABCDEF"; - encoder << char(0xaa) << char(0xbb); - encoder.close(); - assert (str.str() == "414243444546aabb"); - } - { - std::ostringstream str; - HexBinaryEncoder encoder(str); - encoder.rdbuf()->setUppercase(); - encoder << "ABCDEF"; - encoder << char(0xaa) << char(0xbb); - encoder.close(); - assert (str.str() == "414243444546AABB"); - } -} - - -void HexBinaryTest::testDecoder() -{ - { - std::istringstream istr("000102030405"); - HexBinaryDecoder decoder(istr); - assert (decoder.good() && decoder.get() == 0); - assert (decoder.good() && decoder.get() == 1); - assert (decoder.good() && decoder.get() == 2); - assert (decoder.good() && decoder.get() == 3); - assert (decoder.good() && decoder.get() == 4); - assert (decoder.good() && decoder.get() == 5); - assert (decoder.good() && decoder.get() == -1); - } - { - std::istringstream istr("0001020304"); - HexBinaryDecoder decoder(istr); - assert (decoder.good() && decoder.get() == 0); - assert (decoder.good() && decoder.get() == 1); - assert (decoder.good() && decoder.get() == 2); - assert (decoder.good() && decoder.get() == 3); - assert (decoder.good() && decoder.get() == 4); - assert (decoder.good() && decoder.get() == -1); - } - { - std::istringstream istr("0a0bcdef"); - HexBinaryDecoder decoder(istr); - assert (decoder.good() && decoder.get() == 0x0a); - assert (decoder.good() && decoder.get() == 0x0b); - assert (decoder.good() && decoder.get() == 0xcd); - assert (decoder.good() && decoder.get() == 0xef); - assert (decoder.good() && decoder.get() == -1); - } - { - std::istringstream istr("0A0BCDEF"); - HexBinaryDecoder decoder(istr); - assert (decoder.good() && decoder.get() == 0x0a); - assert (decoder.good() && decoder.get() == 0x0b); - assert (decoder.good() && decoder.get() == 0xcd); - assert (decoder.good() && decoder.get() == 0xef); - assert (decoder.good() && decoder.get() == -1); - } - { - std::istringstream istr("00 01 02 03"); - HexBinaryDecoder decoder(istr); - assert (decoder.good() && decoder.get() == 0); - assert (decoder.good() && decoder.get() == 1); - assert (decoder.good() && decoder.get() == 2); - assert (decoder.good() && decoder.get() == 3); - assert (decoder.good() && decoder.get() == -1); - } - { - std::istringstream istr("414243444546"); - HexBinaryDecoder decoder(istr); - std::string s; - decoder >> s; - assert (s == "ABCDEF"); - assert (decoder.eof()); - assert (!decoder.fail()); - } - { - std::istringstream istr("4041\r\n4243\r\n4445"); - HexBinaryDecoder decoder(istr); - std::string s; - decoder >> s; - assert (s == "@ABCDE"); - assert (decoder.eof()); - assert (!decoder.fail()); - } - { - std::istringstream istr("AABB#CCDD"); - HexBinaryDecoder decoder(istr); - std::string s; - try - { - decoder >> s; - assert (decoder.bad()); - } - catch (DataFormatException&) - { - } - assert (!decoder.eof()); - } -} - - -void HexBinaryTest::testEncodeDecode() -{ - { - std::stringstream str; - HexBinaryEncoder encoder(str); - encoder << "The quick brown fox "; - encoder << "jumped over the lazy dog."; - encoder.close(); - HexBinaryDecoder decoder(str); - std::string s; - int c = decoder.get(); - while (c != -1) { s += char(c); c = decoder.get(); } - assert (s == "The quick brown fox jumped over the lazy dog."); - } - { - std::string src; - for (int i = 0; i < 255; ++i) src += char(i); - std::stringstream str; - HexBinaryEncoder encoder(str); - encoder.write(src.data(), (std::streamsize) src.size()); - encoder.close(); - HexBinaryDecoder decoder(str); - std::string s; - int c = decoder.get(); - while (c != -1) { s += char(c); c = decoder.get(); } - assert (s == src); - } -} - - -void HexBinaryTest::setUp() -{ -} - - -void HexBinaryTest::tearDown() -{ -} - - -CppUnit::Test* HexBinaryTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("HexBinaryTest"); - - CppUnit_addTest(pSuite, HexBinaryTest, testEncoder); - CppUnit_addTest(pSuite, HexBinaryTest, testDecoder); - CppUnit_addTest(pSuite, HexBinaryTest, testEncodeDecode); - - return pSuite; -} +// +// HexBinaryTest.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/HexBinaryTest.cpp#1 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "HexBinaryTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/HexBinaryEncoder.h" +#include "Poco/HexBinaryDecoder.h" +#include "Poco/Exception.h" +#include + + +using Poco::HexBinaryEncoder; +using Poco::HexBinaryDecoder; +using Poco::DataFormatException; + + +HexBinaryTest::HexBinaryTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +HexBinaryTest::~HexBinaryTest() +{ +} + + +void HexBinaryTest::testEncoder() +{ + { + std::ostringstream str; + HexBinaryEncoder encoder(str); + encoder << std::string("\00\01\02\03\04\05", 6); + encoder.close(); + assert (str.str() == "000102030405"); + } + { + std::ostringstream str; + HexBinaryEncoder encoder(str); + encoder << std::string("\00\01\02\03", 4); + encoder.close(); + assert (str.str() == "00010203"); + } + { + std::ostringstream str; + HexBinaryEncoder encoder(str); + encoder << "ABCDEF"; + encoder << char(0xaa) << char(0xbb); + encoder.close(); + assert (str.str() == "414243444546aabb"); + } + { + std::ostringstream str; + HexBinaryEncoder encoder(str); + encoder.rdbuf()->setUppercase(); + encoder << "ABCDEF"; + encoder << char(0xaa) << char(0xbb); + encoder.close(); + assert (str.str() == "414243444546AABB"); + } +} + + +void HexBinaryTest::testDecoder() +{ + { + std::istringstream istr("000102030405"); + HexBinaryDecoder decoder(istr); + assert (decoder.good() && decoder.get() == 0); + assert (decoder.good() && decoder.get() == 1); + assert (decoder.good() && decoder.get() == 2); + assert (decoder.good() && decoder.get() == 3); + assert (decoder.good() && decoder.get() == 4); + assert (decoder.good() && decoder.get() == 5); + assert (decoder.good() && decoder.get() == -1); + } + { + std::istringstream istr("0001020304"); + HexBinaryDecoder decoder(istr); + assert (decoder.good() && decoder.get() == 0); + assert (decoder.good() && decoder.get() == 1); + assert (decoder.good() && decoder.get() == 2); + assert (decoder.good() && decoder.get() == 3); + assert (decoder.good() && decoder.get() == 4); + assert (decoder.good() && decoder.get() == -1); + } + { + std::istringstream istr("0a0bcdef"); + HexBinaryDecoder decoder(istr); + assert (decoder.good() && decoder.get() == 0x0a); + assert (decoder.good() && decoder.get() == 0x0b); + assert (decoder.good() && decoder.get() == 0xcd); + assert (decoder.good() && decoder.get() == 0xef); + assert (decoder.good() && decoder.get() == -1); + } + { + std::istringstream istr("0A0BCDEF"); + HexBinaryDecoder decoder(istr); + assert (decoder.good() && decoder.get() == 0x0a); + assert (decoder.good() && decoder.get() == 0x0b); + assert (decoder.good() && decoder.get() == 0xcd); + assert (decoder.good() && decoder.get() == 0xef); + assert (decoder.good() && decoder.get() == -1); + } + { + std::istringstream istr("00 01 02 03"); + HexBinaryDecoder decoder(istr); + assert (decoder.good() && decoder.get() == 0); + assert (decoder.good() && decoder.get() == 1); + assert (decoder.good() && decoder.get() == 2); + assert (decoder.good() && decoder.get() == 3); + assert (decoder.good() && decoder.get() == -1); + } + { + std::istringstream istr("414243444546"); + HexBinaryDecoder decoder(istr); + std::string s; + decoder >> s; + assert (s == "ABCDEF"); + assert (decoder.eof()); + assert (!decoder.fail()); + } + { + std::istringstream istr("4041\r\n4243\r\n4445"); + HexBinaryDecoder decoder(istr); + std::string s; + decoder >> s; + assert (s == "@ABCDE"); + assert (decoder.eof()); + assert (!decoder.fail()); + } + { + std::istringstream istr("AABB#CCDD"); + HexBinaryDecoder decoder(istr); + std::string s; + try + { + decoder >> s; + assert (decoder.bad()); + } + catch (DataFormatException&) + { + } + assert (!decoder.eof()); + } +} + + +void HexBinaryTest::testEncodeDecode() +{ + { + std::stringstream str; + HexBinaryEncoder encoder(str); + encoder << "The quick brown fox "; + encoder << "jumped over the lazy dog."; + encoder.close(); + HexBinaryDecoder decoder(str); + std::string s; + int c = decoder.get(); + while (c != -1) { s += char(c); c = decoder.get(); } + assert (s == "The quick brown fox jumped over the lazy dog."); + } + { + std::string src; + for (int i = 0; i < 255; ++i) src += char(i); + std::stringstream str; + HexBinaryEncoder encoder(str); + encoder.write(src.data(), (std::streamsize) src.size()); + encoder.close(); + HexBinaryDecoder decoder(str); + std::string s; + int c = decoder.get(); + while (c != -1) { s += char(c); c = decoder.get(); } + assert (s == src); + } +} + + +void HexBinaryTest::setUp() +{ +} + + +void HexBinaryTest::tearDown() +{ +} + + +CppUnit::Test* HexBinaryTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("HexBinaryTest"); + + CppUnit_addTest(pSuite, HexBinaryTest, testEncoder); + CppUnit_addTest(pSuite, HexBinaryTest, testDecoder); + CppUnit_addTest(pSuite, HexBinaryTest, testEncodeDecode); + + return pSuite; +} diff --git a/Foundation/testsuite/src/HexBinaryTest.h b/Foundation/testsuite/src/HexBinaryTest.h index c3a031c24..438920414 100644 --- a/Foundation/testsuite/src/HexBinaryTest.h +++ b/Foundation/testsuite/src/HexBinaryTest.h @@ -1,62 +1,62 @@ -// -// HexBinaryTest.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/HexBinaryTest.h#1 $ -// -// Definition of the HexBinaryTest class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 HexBinaryTest_INCLUDED -#define HexBinaryTest_INCLUDED - - -#include "Poco/Foundation.h" -#include "CppUnit/TestCase.h" - - -class HexBinaryTest: public CppUnit::TestCase -{ -public: - HexBinaryTest(const std::string& name); - ~HexBinaryTest(); - - void testEncoder(); - void testDecoder(); - void testEncodeDecode(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // HexBinaryTest_INCLUDED +// +// HexBinaryTest.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/HexBinaryTest.h#1 $ +// +// Definition of the HexBinaryTest class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 HexBinaryTest_INCLUDED +#define HexBinaryTest_INCLUDED + + +#include "Poco/Foundation.h" +#include "CppUnit/TestCase.h" + + +class HexBinaryTest: public CppUnit::TestCase +{ +public: + HexBinaryTest(const std::string& name); + ~HexBinaryTest(); + + void testEncoder(); + void testDecoder(); + void testEncodeDecode(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // HexBinaryTest_INCLUDED diff --git a/Foundation/testsuite/src/LRUCacheTest.cpp b/Foundation/testsuite/src/LRUCacheTest.cpp index e9b93edde..00e205f9d 100644 --- a/Foundation/testsuite/src/LRUCacheTest.cpp +++ b/Foundation/testsuite/src/LRUCacheTest.cpp @@ -1,240 +1,240 @@ -// -// LRUCacheTest.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/LRUCacheTest.cpp#3 $ -// -// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "LRUCacheTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/Exception.h" -#include "Poco/LRUCache.h" -#include "Poco/Bugcheck.h" - - -using namespace Poco; - - -LRUCacheTest::LRUCacheTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -LRUCacheTest::~LRUCacheTest() -{ -} - - -void LRUCacheTest::testClear() -{ - LRUCache aCache(3); - assert (aCache.size() == 0); - aCache.add(1, 2); - aCache.add(3, 4); - aCache.add(5, 6); - assert (aCache.size() == 3); - assert (aCache.has(1)); - assert (aCache.has(3)); - assert (aCache.has(5)); - assert (*aCache.get(1) == 2); - assert (*aCache.get(3) == 4); - assert (*aCache.get(5) == 6); - aCache.clear(); - assert (!aCache.has(1)); - assert (!aCache.has(3)); - assert (!aCache.has(5)); -} - - -void LRUCacheTest::testCacheSize0() -{ - // cache size 0 is illegal - try - { - LRUCache aCache(0); - failmsg ("cache size of 0 is illegal, test should fail"); - } - catch (Poco::InvalidArgumentException&) - { - } -} - - -void LRUCacheTest::testCacheSize1() -{ - LRUCache aCache(1); - aCache.add(1, 2); - assert (aCache.has(1)); - assert (*aCache.get(1) == 2); - - aCache.add(3, 4); // replaces 1 - assert (!aCache.has(1)); - assert (aCache.has(3)); - assert (*aCache.get(3) == 4); - - aCache.add(5, 6); - assert (!aCache.has(1)); - assert (!aCache.has(3)); - assert (aCache.has(5)); - assert (*aCache.get(5) == 6); - - aCache.remove(5); - assert (!aCache.has(5)); - - // removing illegal entries should work too - aCache.remove(666); -} - - -void LRUCacheTest::testCacheSize2() -{ - // 3-1 represents the cache sorted by pos, elements get replaced at the end of the list - // 3-1|5 -> 5 gets removed - LRUCache aCache(2); - aCache.add(1, 2); // 1 - assert (aCache.has(1)); - assert (*aCache.get(1) == 2); - - aCache.add(3, 4); // 3-1 - assert (aCache.has(1)); - assert (aCache.has(3)); - assert (*aCache.get(1) == 2); // 1-3 - assert (*aCache.get(3) == 4); // 3-1 - - aCache.add(5, 6); // 5-3|1 - assert (!aCache.has(1)); - assert (aCache.has(3)); - assert (aCache.has(5)); - assert (*aCache.get(5) == 6); // 5-3 - assert (*aCache.get(3) == 4); // 3-5 - - // test remove from the end and the beginning of the list - aCache.remove(5); // 3 - assert (!aCache.has(5)); - assert (*aCache.get(3) == 4); // 3 - aCache.add(5, 6); // 5-3 - assert (*aCache.get(3) == 4); // 3-5 - aCache.remove(3); // 5 - assert (!aCache.has(3)); - assert (*aCache.get(5) == 6); // 5 - - // removing illegal entries should work too - aCache.remove(666); - - aCache.clear(); - assert (!aCache.has(5)); -} - - -void LRUCacheTest::testCacheSizeN() -{ - // 3-1 represents the cache sorted by pos, elements get replaced at the end of the list - // 3-1|5 -> 5 gets removed - LRUCache aCache(3); - aCache.add(1, 2); // 1 - assert (aCache.has(1)); - assert (*aCache.get(1) == 2); - - aCache.add(3, 4); // 3-1 - assert (aCache.has(1)); - assert (aCache.has(3)); - assert (*aCache.get(1) == 2); // 1-3 - assert (*aCache.get(3) == 4); // 3-1 - - aCache.add(5, 6); // 5-3-1 - assert (aCache.has(1)); - assert (aCache.has(3)); - assert (aCache.has(5)); - assert (*aCache.get(5) == 6); // 5-3-1 - assert (*aCache.get(3) == 4); // 3-5-1 - - aCache.add(7, 8); // 7-5-3|1 - assert (!aCache.has(1)); - assert (aCache.has(7)); - assert (aCache.has(3)); - assert (aCache.has(5)); - assert (*aCache.get(5) == 6); // 5-7-3 - assert (*aCache.get(3) == 4); // 3-5-7 - assert (*aCache.get(7) == 8); // 7-3-5 - - // test remove from the end and the beginning of the list - aCache.remove(5); // 7-3 - assert (!aCache.has(5)); - assert (*aCache.get(3) == 4); // 3-7 - aCache.add(5, 6); // 5-3-7 - assert (*aCache.get(7) == 8); // 7-5-3 - aCache.remove(7); // 5-3 - assert (!aCache.has(7)); - assert (aCache.has(3)); - assert (*aCache.get(5) == 6); // 5-3 - - // removing illegal entries should work too - aCache.remove(666); - - aCache.clear(); - assert (!aCache.has(5)); - assert (!aCache.has(3)); -} - - -void LRUCacheTest::testDuplicateAdd() -{ - LRUCache aCache(3); - aCache.add(1, 2); // 1 - assert (aCache.has(1)); - assert (*aCache.get(1) == 2); - aCache.add(1, 3); - assert (aCache.has(1)); - assert (*aCache.get(1) == 3); -} - - -void LRUCacheTest::setUp() -{ -} - - -void LRUCacheTest::tearDown() -{ -} - - -CppUnit::Test* LRUCacheTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("LRUCacheTest"); - - CppUnit_addTest(pSuite, LRUCacheTest, testClear); - CppUnit_addTest(pSuite, LRUCacheTest, testCacheSize0); - CppUnit_addTest(pSuite, LRUCacheTest, testCacheSize1); - CppUnit_addTest(pSuite, LRUCacheTest, testCacheSize2); - CppUnit_addTest(pSuite, LRUCacheTest, testCacheSizeN); - CppUnit_addTest(pSuite, LRUCacheTest, testDuplicateAdd); - - return pSuite; -} +// +// LRUCacheTest.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/LRUCacheTest.cpp#3 $ +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "LRUCacheTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/Exception.h" +#include "Poco/LRUCache.h" +#include "Poco/Bugcheck.h" + + +using namespace Poco; + + +LRUCacheTest::LRUCacheTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +LRUCacheTest::~LRUCacheTest() +{ +} + + +void LRUCacheTest::testClear() +{ + LRUCache aCache(3); + assert (aCache.size() == 0); + aCache.add(1, 2); + aCache.add(3, 4); + aCache.add(5, 6); + assert (aCache.size() == 3); + assert (aCache.has(1)); + assert (aCache.has(3)); + assert (aCache.has(5)); + assert (*aCache.get(1) == 2); + assert (*aCache.get(3) == 4); + assert (*aCache.get(5) == 6); + aCache.clear(); + assert (!aCache.has(1)); + assert (!aCache.has(3)); + assert (!aCache.has(5)); +} + + +void LRUCacheTest::testCacheSize0() +{ + // cache size 0 is illegal + try + { + LRUCache aCache(0); + failmsg ("cache size of 0 is illegal, test should fail"); + } + catch (Poco::InvalidArgumentException&) + { + } +} + + +void LRUCacheTest::testCacheSize1() +{ + LRUCache aCache(1); + aCache.add(1, 2); + assert (aCache.has(1)); + assert (*aCache.get(1) == 2); + + aCache.add(3, 4); // replaces 1 + assert (!aCache.has(1)); + assert (aCache.has(3)); + assert (*aCache.get(3) == 4); + + aCache.add(5, 6); + assert (!aCache.has(1)); + assert (!aCache.has(3)); + assert (aCache.has(5)); + assert (*aCache.get(5) == 6); + + aCache.remove(5); + assert (!aCache.has(5)); + + // removing illegal entries should work too + aCache.remove(666); +} + + +void LRUCacheTest::testCacheSize2() +{ + // 3-1 represents the cache sorted by pos, elements get replaced at the end of the list + // 3-1|5 -> 5 gets removed + LRUCache aCache(2); + aCache.add(1, 2); // 1 + assert (aCache.has(1)); + assert (*aCache.get(1) == 2); + + aCache.add(3, 4); // 3-1 + assert (aCache.has(1)); + assert (aCache.has(3)); + assert (*aCache.get(1) == 2); // 1-3 + assert (*aCache.get(3) == 4); // 3-1 + + aCache.add(5, 6); // 5-3|1 + assert (!aCache.has(1)); + assert (aCache.has(3)); + assert (aCache.has(5)); + assert (*aCache.get(5) == 6); // 5-3 + assert (*aCache.get(3) == 4); // 3-5 + + // test remove from the end and the beginning of the list + aCache.remove(5); // 3 + assert (!aCache.has(5)); + assert (*aCache.get(3) == 4); // 3 + aCache.add(5, 6); // 5-3 + assert (*aCache.get(3) == 4); // 3-5 + aCache.remove(3); // 5 + assert (!aCache.has(3)); + assert (*aCache.get(5) == 6); // 5 + + // removing illegal entries should work too + aCache.remove(666); + + aCache.clear(); + assert (!aCache.has(5)); +} + + +void LRUCacheTest::testCacheSizeN() +{ + // 3-1 represents the cache sorted by pos, elements get replaced at the end of the list + // 3-1|5 -> 5 gets removed + LRUCache aCache(3); + aCache.add(1, 2); // 1 + assert (aCache.has(1)); + assert (*aCache.get(1) == 2); + + aCache.add(3, 4); // 3-1 + assert (aCache.has(1)); + assert (aCache.has(3)); + assert (*aCache.get(1) == 2); // 1-3 + assert (*aCache.get(3) == 4); // 3-1 + + aCache.add(5, 6); // 5-3-1 + assert (aCache.has(1)); + assert (aCache.has(3)); + assert (aCache.has(5)); + assert (*aCache.get(5) == 6); // 5-3-1 + assert (*aCache.get(3) == 4); // 3-5-1 + + aCache.add(7, 8); // 7-5-3|1 + assert (!aCache.has(1)); + assert (aCache.has(7)); + assert (aCache.has(3)); + assert (aCache.has(5)); + assert (*aCache.get(5) == 6); // 5-7-3 + assert (*aCache.get(3) == 4); // 3-5-7 + assert (*aCache.get(7) == 8); // 7-3-5 + + // test remove from the end and the beginning of the list + aCache.remove(5); // 7-3 + assert (!aCache.has(5)); + assert (*aCache.get(3) == 4); // 3-7 + aCache.add(5, 6); // 5-3-7 + assert (*aCache.get(7) == 8); // 7-5-3 + aCache.remove(7); // 5-3 + assert (!aCache.has(7)); + assert (aCache.has(3)); + assert (*aCache.get(5) == 6); // 5-3 + + // removing illegal entries should work too + aCache.remove(666); + + aCache.clear(); + assert (!aCache.has(5)); + assert (!aCache.has(3)); +} + + +void LRUCacheTest::testDuplicateAdd() +{ + LRUCache aCache(3); + aCache.add(1, 2); // 1 + assert (aCache.has(1)); + assert (*aCache.get(1) == 2); + aCache.add(1, 3); + assert (aCache.has(1)); + assert (*aCache.get(1) == 3); +} + + +void LRUCacheTest::setUp() +{ +} + + +void LRUCacheTest::tearDown() +{ +} + + +CppUnit::Test* LRUCacheTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("LRUCacheTest"); + + CppUnit_addTest(pSuite, LRUCacheTest, testClear); + CppUnit_addTest(pSuite, LRUCacheTest, testCacheSize0); + CppUnit_addTest(pSuite, LRUCacheTest, testCacheSize1); + CppUnit_addTest(pSuite, LRUCacheTest, testCacheSize2); + CppUnit_addTest(pSuite, LRUCacheTest, testCacheSizeN); + CppUnit_addTest(pSuite, LRUCacheTest, testDuplicateAdd); + + return pSuite; +} diff --git a/Foundation/testsuite/src/LRUCacheTest.h b/Foundation/testsuite/src/LRUCacheTest.h index 6b9b0881a..ce0b5b81c 100644 --- a/Foundation/testsuite/src/LRUCacheTest.h +++ b/Foundation/testsuite/src/LRUCacheTest.h @@ -1,61 +1,61 @@ -// -// LRUCacheTest.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/LRUCacheTest.h#1 $ -// -// Tests for LRUCache -// -// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 LRUCacheTest_INCLUDED -#define LRUCacheTest_INCLUDED - - -#include "Poco/Foundation.h" -#include "CppUnit/TestCase.h" - - -class LRUCacheTest: public CppUnit::TestCase -{ -public: - LRUCacheTest(const std::string& name); - ~LRUCacheTest(); - - void testClear(); - void testCacheSize0(); - void testCacheSize1(); - void testCacheSize2(); - void testCacheSizeN(); - void testDuplicateAdd(); - - void setUp(); - void tearDown(); - static CppUnit::Test* suite(); -}; - - -#endif // LRUCacheTest_INCLUDED +// +// LRUCacheTest.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/LRUCacheTest.h#1 $ +// +// Tests for LRUCache +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 LRUCacheTest_INCLUDED +#define LRUCacheTest_INCLUDED + + +#include "Poco/Foundation.h" +#include "CppUnit/TestCase.h" + + +class LRUCacheTest: public CppUnit::TestCase +{ +public: + LRUCacheTest(const std::string& name); + ~LRUCacheTest(); + + void testClear(); + void testCacheSize0(); + void testCacheSize1(); + void testCacheSize2(); + void testCacheSizeN(); + void testDuplicateAdd(); + + void setUp(); + void tearDown(); + static CppUnit::Test* suite(); +}; + + +#endif // LRUCacheTest_INCLUDED diff --git a/Foundation/testsuite/src/LineEndingConverterTest.cpp b/Foundation/testsuite/src/LineEndingConverterTest.cpp index 15efe4d3d..4a60fad51 100644 --- a/Foundation/testsuite/src/LineEndingConverterTest.cpp +++ b/Foundation/testsuite/src/LineEndingConverterTest.cpp @@ -1,165 +1,165 @@ -// -// LineEndingConverterTest.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/LineEndingConverterTest.cpp#1 $ -// -// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "LineEndingConverterTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/LineEndingConverter.h" -#include "Poco/StreamCopier.h" -#include - - -using Poco::LineEnding; -using Poco::InputLineEndingConverter; -using Poco::OutputLineEndingConverter; -using Poco::StreamCopier; - - -LineEndingConverterTest::LineEndingConverterTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -LineEndingConverterTest::~LineEndingConverterTest() -{ -} - - -void LineEndingConverterTest::testInputDosToUnix() -{ - std::istringstream input("line1\r\nline2\r\nline3\r\n"); - std::ostringstream output; - InputLineEndingConverter conv(input, LineEnding::NEWLINE_LF); - StreamCopier::copyStream(conv, output); - std::string result = output.str(); - assert (result == "line1\nline2\nline3\n"); -} - - -void LineEndingConverterTest::testInputUnixToDos() -{ - std::istringstream input("line1\nline2\nline3\n"); - std::ostringstream output; - InputLineEndingConverter conv(input, LineEnding::NEWLINE_CRLF); - StreamCopier::copyStream(conv, output); - std::string result = output.str(); - assert (result == "line1\r\nline2\r\nline3\r\n"); -} - - -void LineEndingConverterTest::testInputMacToUnix() -{ - std::istringstream input("line1\rline2\rline3\r"); - std::ostringstream output; - InputLineEndingConverter conv(input, LineEnding::NEWLINE_LF); - StreamCopier::copyStream(conv, output); - std::string result = output.str(); - assert (result == "line1\nline2\nline3\n"); -} - - -void LineEndingConverterTest::testInputRemove() -{ - std::istringstream input("line1\r\nline2\rline3\n"); - std::ostringstream output; - InputLineEndingConverter conv(input, ""); - StreamCopier::copyStream(conv, output); - std::string result = output.str(); - assert (result == "line1line2line3"); -} - - -void LineEndingConverterTest::testOutputDosToUnix() -{ - std::ostringstream output; - OutputLineEndingConverter conv(output, LineEnding::NEWLINE_LF); - conv << "line1\r\nline2\r\nline3\r\n" << std::flush; - std::string result = output.str(); - assert (result == "line1\nline2\nline3\n"); -} - - -void LineEndingConverterTest::testOutputUnixToDos() -{ - std::ostringstream output; - OutputLineEndingConverter conv(output, LineEnding::NEWLINE_CRLF); - conv << "line1\nline2\nline3\n" << std::flush; - std::string result = output.str(); - assert (result == "line1\r\nline2\r\nline3\r\n"); -} - - -void LineEndingConverterTest::testOutputMacToUnix() -{ - std::ostringstream output; - OutputLineEndingConverter conv(output, LineEnding::NEWLINE_LF); - conv << "line1\rline2\rline3\r" << std::flush; - std::string result = output.str(); - assert (result == "line1\nline2\nline3\n"); -} - - -void LineEndingConverterTest::testOutputRemove() -{ - std::ostringstream output; - OutputLineEndingConverter conv(output, ""); - conv << "line1\r\nline2\rline3\n" << std::flush; - std::string result = output.str(); - assert (result == "line1line2line3"); -} - - -void LineEndingConverterTest::setUp() -{ -} - - -void LineEndingConverterTest::tearDown() -{ -} - - -CppUnit::Test* LineEndingConverterTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("LineEndingConverterTest"); - - CppUnit_addTest(pSuite, LineEndingConverterTest, testInputDosToUnix); - CppUnit_addTest(pSuite, LineEndingConverterTest, testInputUnixToDos); - CppUnit_addTest(pSuite, LineEndingConverterTest, testInputMacToUnix); - CppUnit_addTest(pSuite, LineEndingConverterTest, testInputRemove); - CppUnit_addTest(pSuite, LineEndingConverterTest, testOutputDosToUnix); - CppUnit_addTest(pSuite, LineEndingConverterTest, testOutputUnixToDos); - CppUnit_addTest(pSuite, LineEndingConverterTest, testOutputMacToUnix); - CppUnit_addTest(pSuite, LineEndingConverterTest, testOutputRemove); - - return pSuite; -} +// +// LineEndingConverterTest.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/LineEndingConverterTest.cpp#1 $ +// +// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "LineEndingConverterTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/LineEndingConverter.h" +#include "Poco/StreamCopier.h" +#include + + +using Poco::LineEnding; +using Poco::InputLineEndingConverter; +using Poco::OutputLineEndingConverter; +using Poco::StreamCopier; + + +LineEndingConverterTest::LineEndingConverterTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +LineEndingConverterTest::~LineEndingConverterTest() +{ +} + + +void LineEndingConverterTest::testInputDosToUnix() +{ + std::istringstream input("line1\r\nline2\r\nline3\r\n"); + std::ostringstream output; + InputLineEndingConverter conv(input, LineEnding::NEWLINE_LF); + StreamCopier::copyStream(conv, output); + std::string result = output.str(); + assert (result == "line1\nline2\nline3\n"); +} + + +void LineEndingConverterTest::testInputUnixToDos() +{ + std::istringstream input("line1\nline2\nline3\n"); + std::ostringstream output; + InputLineEndingConverter conv(input, LineEnding::NEWLINE_CRLF); + StreamCopier::copyStream(conv, output); + std::string result = output.str(); + assert (result == "line1\r\nline2\r\nline3\r\n"); +} + + +void LineEndingConverterTest::testInputMacToUnix() +{ + std::istringstream input("line1\rline2\rline3\r"); + std::ostringstream output; + InputLineEndingConverter conv(input, LineEnding::NEWLINE_LF); + StreamCopier::copyStream(conv, output); + std::string result = output.str(); + assert (result == "line1\nline2\nline3\n"); +} + + +void LineEndingConverterTest::testInputRemove() +{ + std::istringstream input("line1\r\nline2\rline3\n"); + std::ostringstream output; + InputLineEndingConverter conv(input, ""); + StreamCopier::copyStream(conv, output); + std::string result = output.str(); + assert (result == "line1line2line3"); +} + + +void LineEndingConverterTest::testOutputDosToUnix() +{ + std::ostringstream output; + OutputLineEndingConverter conv(output, LineEnding::NEWLINE_LF); + conv << "line1\r\nline2\r\nline3\r\n" << std::flush; + std::string result = output.str(); + assert (result == "line1\nline2\nline3\n"); +} + + +void LineEndingConverterTest::testOutputUnixToDos() +{ + std::ostringstream output; + OutputLineEndingConverter conv(output, LineEnding::NEWLINE_CRLF); + conv << "line1\nline2\nline3\n" << std::flush; + std::string result = output.str(); + assert (result == "line1\r\nline2\r\nline3\r\n"); +} + + +void LineEndingConverterTest::testOutputMacToUnix() +{ + std::ostringstream output; + OutputLineEndingConverter conv(output, LineEnding::NEWLINE_LF); + conv << "line1\rline2\rline3\r" << std::flush; + std::string result = output.str(); + assert (result == "line1\nline2\nline3\n"); +} + + +void LineEndingConverterTest::testOutputRemove() +{ + std::ostringstream output; + OutputLineEndingConverter conv(output, ""); + conv << "line1\r\nline2\rline3\n" << std::flush; + std::string result = output.str(); + assert (result == "line1line2line3"); +} + + +void LineEndingConverterTest::setUp() +{ +} + + +void LineEndingConverterTest::tearDown() +{ +} + + +CppUnit::Test* LineEndingConverterTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("LineEndingConverterTest"); + + CppUnit_addTest(pSuite, LineEndingConverterTest, testInputDosToUnix); + CppUnit_addTest(pSuite, LineEndingConverterTest, testInputUnixToDos); + CppUnit_addTest(pSuite, LineEndingConverterTest, testInputMacToUnix); + CppUnit_addTest(pSuite, LineEndingConverterTest, testInputRemove); + CppUnit_addTest(pSuite, LineEndingConverterTest, testOutputDosToUnix); + CppUnit_addTest(pSuite, LineEndingConverterTest, testOutputUnixToDos); + CppUnit_addTest(pSuite, LineEndingConverterTest, testOutputMacToUnix); + CppUnit_addTest(pSuite, LineEndingConverterTest, testOutputRemove); + + return pSuite; +} diff --git a/Foundation/testsuite/src/LineEndingConverterTest.h b/Foundation/testsuite/src/LineEndingConverterTest.h index 4e61295c5..fbee59cb5 100644 --- a/Foundation/testsuite/src/LineEndingConverterTest.h +++ b/Foundation/testsuite/src/LineEndingConverterTest.h @@ -1,67 +1,67 @@ -// -// LineEndingConverterTest.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/LineEndingConverterTest.h#1 $ -// -// Definition of the LineEndingConverterTest class. -// -// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 LineEndingConverterTest_INCLUDED -#define LineEndingConverterTest_INCLUDED - - -#include "Poco/Foundation.h" -#include "CppUnit/TestCase.h" - - -class LineEndingConverterTest: public CppUnit::TestCase -{ -public: - LineEndingConverterTest(const std::string& name); - ~LineEndingConverterTest(); - - void testInputDosToUnix(); - void testInputUnixToDos(); - void testInputMacToUnix(); - void testInputRemove(); - void testOutputDosToUnix(); - void testOutputUnixToDos(); - void testOutputMacToUnix(); - void testOutputRemove(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // LineEndingConverterTest_INCLUDED +// +// LineEndingConverterTest.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/LineEndingConverterTest.h#1 $ +// +// Definition of the LineEndingConverterTest class. +// +// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 LineEndingConverterTest_INCLUDED +#define LineEndingConverterTest_INCLUDED + + +#include "Poco/Foundation.h" +#include "CppUnit/TestCase.h" + + +class LineEndingConverterTest: public CppUnit::TestCase +{ +public: + LineEndingConverterTest(const std::string& name); + ~LineEndingConverterTest(); + + void testInputDosToUnix(); + void testInputUnixToDos(); + void testInputMacToUnix(); + void testInputRemove(); + void testOutputDosToUnix(); + void testOutputUnixToDos(); + void testOutputMacToUnix(); + void testOutputRemove(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // LineEndingConverterTest_INCLUDED diff --git a/Foundation/testsuite/src/LocalDateTimeTest.cpp b/Foundation/testsuite/src/LocalDateTimeTest.cpp index 816808250..c3c755113 100644 --- a/Foundation/testsuite/src/LocalDateTimeTest.cpp +++ b/Foundation/testsuite/src/LocalDateTimeTest.cpp @@ -1,391 +1,391 @@ -// -// LocalDateTimeTest.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/LocalDateTimeTest.cpp#1 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "LocalDateTimeTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/LocalDateTime.h" -#include "Poco/DateTime.h" -#include "Poco/Timestamp.h" -#include "Poco/Timespan.h" -#include "Poco/Timezone.h" - - -using Poco::LocalDateTime; -using Poco::DateTime; -using Poco::Timestamp; -using Poco::Timespan; -using Poco::Timezone; - - -LocalDateTimeTest::LocalDateTimeTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -LocalDateTimeTest::~LocalDateTimeTest() -{ -} - - -void LocalDateTimeTest::testGregorian1() -{ - LocalDateTime dt(1970, 1, 1); - assert (dt.year() == 1970); - assert (dt.month() == 1); - assert (dt.day() == 1); - assert (dt.hour() == 0); - assert (dt.minute() == 0); - assert (dt.second() == 0); - assert (dt.millisecond() == 0); - assert (dt.dayOfWeek() == 4); - assert (dt.tzd() == Timezone::tzd()); - assert (dt.julianDay() == 2440587.5); - - dt.assign(2001, 9, 9, 1, 46, 40); - assert (dt.year() == 2001); - assert (dt.month() == 9); - assert (dt.day() == 9); - assert (dt.hour() == 1); - assert (dt.minute() == 46); - assert (dt.second() == 40); - assert (dt.millisecond() == 0); - assert (dt.dayOfWeek() == 0); - assert (dt.tzd() == Timezone::tzd()); - assertEqualDelta (dt.julianDay(), 2452161.574074, 0.000001); -} - - -void LocalDateTimeTest::testGregorian2() -{ - LocalDateTime dt(2*3600, 1970, 1, 1, 0, 0, 0, 0, 0); - assert (dt.year() == 1970); - assert (dt.month() == 1); - assert (dt.day() == 1); - assert (dt.hour() == 0); - assert (dt.minute() == 0); - assert (dt.second() == 0); - assert (dt.millisecond() == 0); - assert (dt.dayOfWeek() == 4); - assert (dt.tzd() == 2*3600); - - dt.assign(-7*3600, 2001, 9, 9, 1, 46, 40, 0, 0); - assert (dt.year() == 2001); - assert (dt.month() == 9); - assert (dt.day() == 9); - assert (dt.hour() == 1); - assert (dt.minute() == 46); - assert (dt.second() == 40); - assert (dt.millisecond() == 0); - assert (dt.dayOfWeek() == 0); - assert (dt.tzd() == -7*3600); -} - - -void LocalDateTimeTest::testConversions() -{ - LocalDateTime dt1(2*3600, 2005, 1, 28, 14, 24, 44, 234, 0); - LocalDateTime dt2(dt1.tzd(), dt1.utc()); - LocalDateTime dt3; - dt3 = dt1; - LocalDateTime dt4(dt2); - LocalDateTime dt5(-4*3600, dt1.utc()); - - assert (dt2.year() == 2005); - assert (dt2.month() == 1); - assert (dt2.day() == 28); - assert (dt2.hour() == 14); - assert (dt2.minute() == 24); - assert (dt2.second() == 44); - assert (dt2.millisecond() == 234); - assert (dt2.dayOfWeek() == 5); - assert (dt2.tzd() == 2*3600); - - assert (dt5.year() == 2005); - assert (dt5.month() == 1); - assert (dt5.day() == 28); - assert (dt5.hour() == 8); - assert (dt5.minute() == 24); - assert (dt5.second() == 44); - assert (dt5.millisecond() == 234); - assert (dt5.dayOfWeek() == 5); - assert (dt5.tzd() == -4*3600); -} - - -void LocalDateTimeTest::testCalcs() -{ - LocalDateTime dt1(2005, 1, 1); - assert (dt1.dayOfYear() == 1); - assert (dt1.week(DateTime::MONDAY) == 0); - dt1.assign(2005, 1, 3); - assert (dt1.dayOfYear() == 3); - assert (dt1.week(DateTime::MONDAY) == 1); - dt1.assign(2005, 1, 9); - assert (dt1.dayOfYear() == 9); - assert (dt1.week(DateTime::MONDAY) == 1); - dt1.assign(2005, 1, 10); - assert (dt1.dayOfYear() == 10); - assert (dt1.week(DateTime::MONDAY) == 2); - dt1.assign(2005, 2, 1); - assert (dt1.dayOfYear() == 32); - assert (dt1.week(DateTime::MONDAY) == 5); - dt1.assign(2005, 12, 31); - assert (dt1.week(DateTime::MONDAY) == 52); - dt1.assign(2007, 1, 1); - assert (dt1.week(DateTime::MONDAY) == 1); - dt1.assign(2007, 12, 31); - assert (dt1.week(DateTime::MONDAY) == 53); - - // Jan 1 is Mon - dt1.assign(2001, 1, 1); - assert (dt1.week() == 1); - dt1.assign(2001, 1, 7); - assert (dt1.week() == 1); - dt1.assign(2001, 1, 8); - assert (dt1.week() == 2); - dt1.assign(2001, 1, 21); - assert (dt1.week() == 3); - dt1.assign(2001, 1, 22); - assert (dt1.week() == 4); - - // Jan 1 is Tue - dt1.assign(2002, 1, 1); - assert (dt1.week() == 1); - dt1.assign(2002, 1, 6); - assert (dt1.week() == 1); - dt1.assign(2002, 1, 7); - assert (dt1.week() == 2); - dt1.assign(2002, 1, 20); - assert (dt1.week() == 3); - dt1.assign(2002, 1, 21); - assert (dt1.week() == 4); - - // Jan 1 is Wed - dt1.assign(2003, 1, 1); - assert (dt1.week() == 1); - dt1.assign(2003, 1, 5); - assert (dt1.week() == 1); - dt1.assign(2003, 1, 6); - assert (dt1.week() == 2); - dt1.assign(2003, 1, 19); - assert (dt1.week() == 3); - dt1.assign(2003, 1, 20); - assert (dt1.week() == 4); - - // Jan 1 is Thu - dt1.assign(2004, 1, 1); - assert (dt1.week() == 1); - dt1.assign(2004, 1, 4); - assert (dt1.week() == 1); - dt1.assign(2004, 1, 5); - assert (dt1.week() == 2); - dt1.assign(2004, 1, 18); - assert (dt1.week() == 3); - dt1.assign(2004, 1, 19); - assert (dt1.week() == 4); - - // Jan 1 is Fri - dt1.assign(1999, 1, 1); - assert (dt1.week() == 0); - dt1.assign(1999, 1, 3); - assert (dt1.week() == 0); - dt1.assign(1999, 1, 4); - assert (dt1.week() == 1); - dt1.assign(1999, 1, 17); - assert (dt1.week() == 2); - dt1.assign(1999, 1, 18); - assert (dt1.week() == 3); - - // Jan 1 is Sat - dt1.assign(2000, 1, 1); - assert (dt1.week() == 0); - dt1.assign(2000, 1, 2); - assert (dt1.week() == 0); - dt1.assign(2000, 1, 3); - assert (dt1.week() == 1); - dt1.assign(2000, 1, 16); - assert (dt1.week() == 2); - dt1.assign(2000, 1, 17); - assert (dt1.week() == 3); - - // Jan 1 is Sun - dt1.assign(1995, 1, 1); - assert (dt1.week() == 0); - dt1.assign(1995, 1, 2); - assert (dt1.week() == 1); - dt1.assign(1995, 1, 3); - assert (dt1.week() == 1); - dt1.assign(1995, 1, 15); - assert (dt1.week() == 2); - dt1.assign(1995, 1, 16); - assert (dt1.week() == 3); -} - - -void LocalDateTimeTest::testAMPM() -{ - LocalDateTime dt1(2005, 1, 1, 0, 15, 30); - assert (dt1.isAM()); - assert (!dt1.isPM()); - assert (dt1.hourAMPM() == 12); - - dt1.assign(2005, 1, 1, 12, 15, 30); - assert (!dt1.isAM()); - assert (dt1.isPM()); - assert (dt1.hourAMPM() == 12); - - dt1.assign(2005, 1, 1, 13, 15, 30); - assert (!dt1.isAM()); - assert (dt1.isPM()); - assert (dt1.hourAMPM() == 1); -} - - -void LocalDateTimeTest::testRelational1() -{ - LocalDateTime dt1(2005, 1, 1, 0, 15, 30); - LocalDateTime dt2(2005, 1, 2, 0, 15, 30); - LocalDateTime dt3(dt1); - - assert (dt1 < dt2); - assert (dt1 <= dt2); - assert (dt2 > dt1); - assert (dt2 >= dt1); - assert (dt1 != dt2); - assert (!(dt1 == dt2)); - - assert (dt1 == dt3); - assert (!(dt1 != dt3)); - assert (dt1 >= dt3); - assert (dt1 <= dt3); - assert (!(dt1 > dt3)); - assert (!(dt1 < dt3)); -} - - -void LocalDateTimeTest::testRelational2() -{ - LocalDateTime dt1(2*3600, 2005, 1, 1, 15, 30, 0, 0, 0); - LocalDateTime dt2(2*3600, 2005, 1, 1, 17, 30, 0, 0, 0); - LocalDateTime dt3(5*3600, 2005, 1, 1, 18, 30, 0, 0, 0); - - assert (dt1 < dt2); - assert (dt1 <= dt2); - assert (dt2 > dt1); - assert (dt2 >= dt1); - assert (dt1 != dt2); - assert (!(dt1 == dt2)); - - assert (dt1 == dt3); - assert (!(dt1 != dt3)); - assert (dt1 >= dt3); - assert (dt1 <= dt3); - assert (!(dt1 > dt3)); - assert (!(dt1 < dt3)); -} - - -void LocalDateTimeTest::testArithmetics1() -{ - LocalDateTime dt1(2005, 1, 1, 0, 15, 30); - LocalDateTime dt2(2005, 1, 2, 0, 15, 30); - - Timespan s = dt2 - dt1; - assert (s.days() == 1); - - LocalDateTime dt3 = dt1 + s; - assert (dt3 == dt2); - - dt3 -= s; - assert (dt3 == dt1); - dt1 += s; - assert (dt1 == dt2); -} - - -void LocalDateTimeTest::testArithmetics2() -{ - LocalDateTime dt1(2*3600, 2005, 1, 1, 15, 30, 0, 0, 0); - LocalDateTime dt2(5*3600, 2005, 1, 2, 18, 30, 0, 0, 0); - - Timespan s = dt2 - dt1; - assert (s.days() == 1); - - LocalDateTime dt3 = dt1 + s; - assert (dt3 == dt2); - - dt3 -= s; - assert (dt3 == dt1); - dt1 += s; - assert (dt1 == dt2); -} - - -void LocalDateTimeTest::testSwap() -{ - LocalDateTime dt1(2005, 1, 1, 0, 15, 30); - LocalDateTime dt2(2005, 1, 2, 0, 15, 30); - - assert (dt1 < dt2); - dt1.swap(dt2); - assert (dt2 < dt1); -} - - -void LocalDateTimeTest::setUp() -{ -} - - -void LocalDateTimeTest::tearDown() -{ -} - - -CppUnit::Test* LocalDateTimeTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("LocalDateTimeTest"); - - CppUnit_addTest(pSuite, LocalDateTimeTest, testGregorian1); - CppUnit_addTest(pSuite, LocalDateTimeTest, testGregorian2); - CppUnit_addTest(pSuite, LocalDateTimeTest, testConversions); - CppUnit_addTest(pSuite, LocalDateTimeTest, testCalcs); - CppUnit_addTest(pSuite, LocalDateTimeTest, testAMPM); - CppUnit_addTest(pSuite, LocalDateTimeTest, testRelational1); - CppUnit_addTest(pSuite, LocalDateTimeTest, testRelational2); - CppUnit_addTest(pSuite, LocalDateTimeTest, testArithmetics1); - CppUnit_addTest(pSuite, LocalDateTimeTest, testArithmetics2); - CppUnit_addTest(pSuite, LocalDateTimeTest, testSwap); - - return pSuite; -} +// +// LocalDateTimeTest.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/LocalDateTimeTest.cpp#1 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "LocalDateTimeTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/LocalDateTime.h" +#include "Poco/DateTime.h" +#include "Poco/Timestamp.h" +#include "Poco/Timespan.h" +#include "Poco/Timezone.h" + + +using Poco::LocalDateTime; +using Poco::DateTime; +using Poco::Timestamp; +using Poco::Timespan; +using Poco::Timezone; + + +LocalDateTimeTest::LocalDateTimeTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +LocalDateTimeTest::~LocalDateTimeTest() +{ +} + + +void LocalDateTimeTest::testGregorian1() +{ + LocalDateTime dt(1970, 1, 1); + assert (dt.year() == 1970); + assert (dt.month() == 1); + assert (dt.day() == 1); + assert (dt.hour() == 0); + assert (dt.minute() == 0); + assert (dt.second() == 0); + assert (dt.millisecond() == 0); + assert (dt.dayOfWeek() == 4); + assert (dt.tzd() == Timezone::tzd()); + assert (dt.julianDay() == 2440587.5); + + dt.assign(2001, 9, 9, 1, 46, 40); + assert (dt.year() == 2001); + assert (dt.month() == 9); + assert (dt.day() == 9); + assert (dt.hour() == 1); + assert (dt.minute() == 46); + assert (dt.second() == 40); + assert (dt.millisecond() == 0); + assert (dt.dayOfWeek() == 0); + assert (dt.tzd() == Timezone::tzd()); + assertEqualDelta (dt.julianDay(), 2452161.574074, 0.000001); +} + + +void LocalDateTimeTest::testGregorian2() +{ + LocalDateTime dt(2*3600, 1970, 1, 1, 0, 0, 0, 0, 0); + assert (dt.year() == 1970); + assert (dt.month() == 1); + assert (dt.day() == 1); + assert (dt.hour() == 0); + assert (dt.minute() == 0); + assert (dt.second() == 0); + assert (dt.millisecond() == 0); + assert (dt.dayOfWeek() == 4); + assert (dt.tzd() == 2*3600); + + dt.assign(-7*3600, 2001, 9, 9, 1, 46, 40, 0, 0); + assert (dt.year() == 2001); + assert (dt.month() == 9); + assert (dt.day() == 9); + assert (dt.hour() == 1); + assert (dt.minute() == 46); + assert (dt.second() == 40); + assert (dt.millisecond() == 0); + assert (dt.dayOfWeek() == 0); + assert (dt.tzd() == -7*3600); +} + + +void LocalDateTimeTest::testConversions() +{ + LocalDateTime dt1(2*3600, 2005, 1, 28, 14, 24, 44, 234, 0); + LocalDateTime dt2(dt1.tzd(), dt1.utc()); + LocalDateTime dt3; + dt3 = dt1; + LocalDateTime dt4(dt2); + LocalDateTime dt5(-4*3600, dt1.utc()); + + assert (dt2.year() == 2005); + assert (dt2.month() == 1); + assert (dt2.day() == 28); + assert (dt2.hour() == 14); + assert (dt2.minute() == 24); + assert (dt2.second() == 44); + assert (dt2.millisecond() == 234); + assert (dt2.dayOfWeek() == 5); + assert (dt2.tzd() == 2*3600); + + assert (dt5.year() == 2005); + assert (dt5.month() == 1); + assert (dt5.day() == 28); + assert (dt5.hour() == 8); + assert (dt5.minute() == 24); + assert (dt5.second() == 44); + assert (dt5.millisecond() == 234); + assert (dt5.dayOfWeek() == 5); + assert (dt5.tzd() == -4*3600); +} + + +void LocalDateTimeTest::testCalcs() +{ + LocalDateTime dt1(2005, 1, 1); + assert (dt1.dayOfYear() == 1); + assert (dt1.week(DateTime::MONDAY) == 0); + dt1.assign(2005, 1, 3); + assert (dt1.dayOfYear() == 3); + assert (dt1.week(DateTime::MONDAY) == 1); + dt1.assign(2005, 1, 9); + assert (dt1.dayOfYear() == 9); + assert (dt1.week(DateTime::MONDAY) == 1); + dt1.assign(2005, 1, 10); + assert (dt1.dayOfYear() == 10); + assert (dt1.week(DateTime::MONDAY) == 2); + dt1.assign(2005, 2, 1); + assert (dt1.dayOfYear() == 32); + assert (dt1.week(DateTime::MONDAY) == 5); + dt1.assign(2005, 12, 31); + assert (dt1.week(DateTime::MONDAY) == 52); + dt1.assign(2007, 1, 1); + assert (dt1.week(DateTime::MONDAY) == 1); + dt1.assign(2007, 12, 31); + assert (dt1.week(DateTime::MONDAY) == 53); + + // Jan 1 is Mon + dt1.assign(2001, 1, 1); + assert (dt1.week() == 1); + dt1.assign(2001, 1, 7); + assert (dt1.week() == 1); + dt1.assign(2001, 1, 8); + assert (dt1.week() == 2); + dt1.assign(2001, 1, 21); + assert (dt1.week() == 3); + dt1.assign(2001, 1, 22); + assert (dt1.week() == 4); + + // Jan 1 is Tue + dt1.assign(2002, 1, 1); + assert (dt1.week() == 1); + dt1.assign(2002, 1, 6); + assert (dt1.week() == 1); + dt1.assign(2002, 1, 7); + assert (dt1.week() == 2); + dt1.assign(2002, 1, 20); + assert (dt1.week() == 3); + dt1.assign(2002, 1, 21); + assert (dt1.week() == 4); + + // Jan 1 is Wed + dt1.assign(2003, 1, 1); + assert (dt1.week() == 1); + dt1.assign(2003, 1, 5); + assert (dt1.week() == 1); + dt1.assign(2003, 1, 6); + assert (dt1.week() == 2); + dt1.assign(2003, 1, 19); + assert (dt1.week() == 3); + dt1.assign(2003, 1, 20); + assert (dt1.week() == 4); + + // Jan 1 is Thu + dt1.assign(2004, 1, 1); + assert (dt1.week() == 1); + dt1.assign(2004, 1, 4); + assert (dt1.week() == 1); + dt1.assign(2004, 1, 5); + assert (dt1.week() == 2); + dt1.assign(2004, 1, 18); + assert (dt1.week() == 3); + dt1.assign(2004, 1, 19); + assert (dt1.week() == 4); + + // Jan 1 is Fri + dt1.assign(1999, 1, 1); + assert (dt1.week() == 0); + dt1.assign(1999, 1, 3); + assert (dt1.week() == 0); + dt1.assign(1999, 1, 4); + assert (dt1.week() == 1); + dt1.assign(1999, 1, 17); + assert (dt1.week() == 2); + dt1.assign(1999, 1, 18); + assert (dt1.week() == 3); + + // Jan 1 is Sat + dt1.assign(2000, 1, 1); + assert (dt1.week() == 0); + dt1.assign(2000, 1, 2); + assert (dt1.week() == 0); + dt1.assign(2000, 1, 3); + assert (dt1.week() == 1); + dt1.assign(2000, 1, 16); + assert (dt1.week() == 2); + dt1.assign(2000, 1, 17); + assert (dt1.week() == 3); + + // Jan 1 is Sun + dt1.assign(1995, 1, 1); + assert (dt1.week() == 0); + dt1.assign(1995, 1, 2); + assert (dt1.week() == 1); + dt1.assign(1995, 1, 3); + assert (dt1.week() == 1); + dt1.assign(1995, 1, 15); + assert (dt1.week() == 2); + dt1.assign(1995, 1, 16); + assert (dt1.week() == 3); +} + + +void LocalDateTimeTest::testAMPM() +{ + LocalDateTime dt1(2005, 1, 1, 0, 15, 30); + assert (dt1.isAM()); + assert (!dt1.isPM()); + assert (dt1.hourAMPM() == 12); + + dt1.assign(2005, 1, 1, 12, 15, 30); + assert (!dt1.isAM()); + assert (dt1.isPM()); + assert (dt1.hourAMPM() == 12); + + dt1.assign(2005, 1, 1, 13, 15, 30); + assert (!dt1.isAM()); + assert (dt1.isPM()); + assert (dt1.hourAMPM() == 1); +} + + +void LocalDateTimeTest::testRelational1() +{ + LocalDateTime dt1(2005, 1, 1, 0, 15, 30); + LocalDateTime dt2(2005, 1, 2, 0, 15, 30); + LocalDateTime dt3(dt1); + + assert (dt1 < dt2); + assert (dt1 <= dt2); + assert (dt2 > dt1); + assert (dt2 >= dt1); + assert (dt1 != dt2); + assert (!(dt1 == dt2)); + + assert (dt1 == dt3); + assert (!(dt1 != dt3)); + assert (dt1 >= dt3); + assert (dt1 <= dt3); + assert (!(dt1 > dt3)); + assert (!(dt1 < dt3)); +} + + +void LocalDateTimeTest::testRelational2() +{ + LocalDateTime dt1(2*3600, 2005, 1, 1, 15, 30, 0, 0, 0); + LocalDateTime dt2(2*3600, 2005, 1, 1, 17, 30, 0, 0, 0); + LocalDateTime dt3(5*3600, 2005, 1, 1, 18, 30, 0, 0, 0); + + assert (dt1 < dt2); + assert (dt1 <= dt2); + assert (dt2 > dt1); + assert (dt2 >= dt1); + assert (dt1 != dt2); + assert (!(dt1 == dt2)); + + assert (dt1 == dt3); + assert (!(dt1 != dt3)); + assert (dt1 >= dt3); + assert (dt1 <= dt3); + assert (!(dt1 > dt3)); + assert (!(dt1 < dt3)); +} + + +void LocalDateTimeTest::testArithmetics1() +{ + LocalDateTime dt1(2005, 1, 1, 0, 15, 30); + LocalDateTime dt2(2005, 1, 2, 0, 15, 30); + + Timespan s = dt2 - dt1; + assert (s.days() == 1); + + LocalDateTime dt3 = dt1 + s; + assert (dt3 == dt2); + + dt3 -= s; + assert (dt3 == dt1); + dt1 += s; + assert (dt1 == dt2); +} + + +void LocalDateTimeTest::testArithmetics2() +{ + LocalDateTime dt1(2*3600, 2005, 1, 1, 15, 30, 0, 0, 0); + LocalDateTime dt2(5*3600, 2005, 1, 2, 18, 30, 0, 0, 0); + + Timespan s = dt2 - dt1; + assert (s.days() == 1); + + LocalDateTime dt3 = dt1 + s; + assert (dt3 == dt2); + + dt3 -= s; + assert (dt3 == dt1); + dt1 += s; + assert (dt1 == dt2); +} + + +void LocalDateTimeTest::testSwap() +{ + LocalDateTime dt1(2005, 1, 1, 0, 15, 30); + LocalDateTime dt2(2005, 1, 2, 0, 15, 30); + + assert (dt1 < dt2); + dt1.swap(dt2); + assert (dt2 < dt1); +} + + +void LocalDateTimeTest::setUp() +{ +} + + +void LocalDateTimeTest::tearDown() +{ +} + + +CppUnit::Test* LocalDateTimeTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("LocalDateTimeTest"); + + CppUnit_addTest(pSuite, LocalDateTimeTest, testGregorian1); + CppUnit_addTest(pSuite, LocalDateTimeTest, testGregorian2); + CppUnit_addTest(pSuite, LocalDateTimeTest, testConversions); + CppUnit_addTest(pSuite, LocalDateTimeTest, testCalcs); + CppUnit_addTest(pSuite, LocalDateTimeTest, testAMPM); + CppUnit_addTest(pSuite, LocalDateTimeTest, testRelational1); + CppUnit_addTest(pSuite, LocalDateTimeTest, testRelational2); + CppUnit_addTest(pSuite, LocalDateTimeTest, testArithmetics1); + CppUnit_addTest(pSuite, LocalDateTimeTest, testArithmetics2); + CppUnit_addTest(pSuite, LocalDateTimeTest, testSwap); + + return pSuite; +} diff --git a/Foundation/testsuite/src/LocalDateTimeTest.h b/Foundation/testsuite/src/LocalDateTimeTest.h index e3bcb0d1d..e5213492a 100644 --- a/Foundation/testsuite/src/LocalDateTimeTest.h +++ b/Foundation/testsuite/src/LocalDateTimeTest.h @@ -1,69 +1,69 @@ -// -// LocalDateTimeTest.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/LocalDateTimeTest.h#1 $ -// -// Definition of the LocalDateTimeTest class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 LocalDateTimeTest_INCLUDED -#define LocalDateTimeTest_INCLUDED - - -#include "Poco/Foundation.h" -#include "CppUnit/TestCase.h" - - -class LocalDateTimeTest: public CppUnit::TestCase -{ -public: - LocalDateTimeTest(const std::string& name); - ~LocalDateTimeTest(); - - void testGregorian1(); - void testGregorian2(); - void testConversions(); - void testCalcs(); - void testAMPM(); - void testRelational1(); - void testRelational2(); - void testArithmetics1(); - void testArithmetics2(); - void testSwap(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // LocalDateTimeTest_INCLUDED +// +// LocalDateTimeTest.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/LocalDateTimeTest.h#1 $ +// +// Definition of the LocalDateTimeTest class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 LocalDateTimeTest_INCLUDED +#define LocalDateTimeTest_INCLUDED + + +#include "Poco/Foundation.h" +#include "CppUnit/TestCase.h" + + +class LocalDateTimeTest: public CppUnit::TestCase +{ +public: + LocalDateTimeTest(const std::string& name); + ~LocalDateTimeTest(); + + void testGregorian1(); + void testGregorian2(); + void testConversions(); + void testCalcs(); + void testAMPM(); + void testRelational1(); + void testRelational2(); + void testArithmetics1(); + void testArithmetics2(); + void testSwap(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // LocalDateTimeTest_INCLUDED diff --git a/Foundation/testsuite/src/LogStreamTest.cpp b/Foundation/testsuite/src/LogStreamTest.cpp index 0ef4e451f..ae84d6fd0 100644 --- a/Foundation/testsuite/src/LogStreamTest.cpp +++ b/Foundation/testsuite/src/LogStreamTest.cpp @@ -1,109 +1,109 @@ -// -// LogStreamTest.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/LogStreamTest.cpp#1 $ -// -// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. -// 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. -// -// 3. Redistributions in any form must be accompanied by information on -// how to obtain complete source code for this software and any -// accompanying software that uses this software. The source code -// must either be included in the distribution or be available for no -// more than the cost of distribution plus a nominal fee, and must be -// freely redistributable under reasonable conditions. For an -// executable file, complete source code means the source code for all -// modules it contains. It does not include source code for modules or -// files that typically accompany the major components of the operating -// system on which the executable file runs. -// -// 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. -// - - -#include "LogStreamTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/Logger.h" -#include "Poco/LogStream.h" -#include "Poco/AutoPtr.h" -#include "TestChannel.h" - - -using Poco::Logger; -using Poco::LogStream; -using Poco::Channel; -using Poco::Message; -using Poco::AutoPtr; - - -LogStreamTest::LogStreamTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -LogStreamTest::~LogStreamTest() -{ -} - - -void LogStreamTest::testLogStream() -{ - AutoPtr pChannel = new TestChannel; - Logger& root = Logger::root(); - root.setChannel(pChannel.get()); - - LogStream ls(root); - - ls << "information" << ' ' << 1 << std::endl; - assert (pChannel->list().begin()->getPriority() == Message::PRIO_INFORMATION); - assert (pChannel->list().begin()->getText() == "information 1"); - pChannel->list().clear(); - - ls.error() << "error" << std::endl; - assert (pChannel->list().begin()->getPriority() == Message::PRIO_ERROR); - assert (pChannel->list().begin()->getText() == "error"); - pChannel->list().clear(); -} - - -void LogStreamTest::setUp() -{ -} - - -void LogStreamTest::tearDown() -{ -} - - -CppUnit::Test* LogStreamTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("LogStreamTest"); - - CppUnit_addTest(pSuite, LogStreamTest, testLogStream); - - return pSuite; -} +// +// LogStreamTest.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/LogStreamTest.cpp#1 $ +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// 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. +// +// 3. Redistributions in any form must be accompanied by information on +// how to obtain complete source code for this software and any +// accompanying software that uses this software. The source code +// must either be included in the distribution or be available for no +// more than the cost of distribution plus a nominal fee, and must be +// freely redistributable under reasonable conditions. For an +// executable file, complete source code means the source code for all +// modules it contains. It does not include source code for modules or +// files that typically accompany the major components of the operating +// system on which the executable file runs. +// +// 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. +// + + +#include "LogStreamTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/Logger.h" +#include "Poco/LogStream.h" +#include "Poco/AutoPtr.h" +#include "TestChannel.h" + + +using Poco::Logger; +using Poco::LogStream; +using Poco::Channel; +using Poco::Message; +using Poco::AutoPtr; + + +LogStreamTest::LogStreamTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +LogStreamTest::~LogStreamTest() +{ +} + + +void LogStreamTest::testLogStream() +{ + AutoPtr pChannel = new TestChannel; + Logger& root = Logger::root(); + root.setChannel(pChannel.get()); + + LogStream ls(root); + + ls << "information" << ' ' << 1 << std::endl; + assert (pChannel->list().begin()->getPriority() == Message::PRIO_INFORMATION); + assert (pChannel->list().begin()->getText() == "information 1"); + pChannel->list().clear(); + + ls.error() << "error" << std::endl; + assert (pChannel->list().begin()->getPriority() == Message::PRIO_ERROR); + assert (pChannel->list().begin()->getText() == "error"); + pChannel->list().clear(); +} + + +void LogStreamTest::setUp() +{ +} + + +void LogStreamTest::tearDown() +{ +} + + +CppUnit::Test* LogStreamTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("LogStreamTest"); + + CppUnit_addTest(pSuite, LogStreamTest, testLogStream); + + return pSuite; +} diff --git a/Foundation/testsuite/src/LogStreamTest.h b/Foundation/testsuite/src/LogStreamTest.h index a0c8cb6f0..a39773a80 100644 --- a/Foundation/testsuite/src/LogStreamTest.h +++ b/Foundation/testsuite/src/LogStreamTest.h @@ -1,73 +1,73 @@ -// -// LogStreamTest.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/LogStreamTest.h#1 $ -// -// Definition of the LogStreamTest class. -// -// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. -// 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. -// -// 3. Redistributions in any form must be accompanied by information on -// how to obtain complete source code for this software and any -// accompanying software that uses this software. The source code -// must either be included in the distribution or be available for no -// more than the cost of distribution plus a nominal fee, and must be -// freely redistributable under reasonable conditions. For an -// executable file, complete source code means the source code for all -// modules it contains. It does not include source code for modules or -// files that typically accompany the major components of the operating -// system on which the executable file runs. -// -// 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 LogStreamTest_INCLUDED -#define LogStreamTest_INCLUDED - - -#include "Poco/Foundation.h" -#include "CppUnit/TestCase.h" - - -class LogStreamTest: public CppUnit::TestCase -{ -public: - LogStreamTest(const std::string& name); - ~LogStreamTest(); - - void testLogStream(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // LogStreamTest_INCLUDED +// +// LogStreamTest.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/LogStreamTest.h#1 $ +// +// Definition of the LogStreamTest class. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// 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. +// +// 3. Redistributions in any form must be accompanied by information on +// how to obtain complete source code for this software and any +// accompanying software that uses this software. The source code +// must either be included in the distribution or be available for no +// more than the cost of distribution plus a nominal fee, and must be +// freely redistributable under reasonable conditions. For an +// executable file, complete source code means the source code for all +// modules it contains. It does not include source code for modules or +// files that typically accompany the major components of the operating +// system on which the executable file runs. +// +// 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 LogStreamTest_INCLUDED +#define LogStreamTest_INCLUDED + + +#include "Poco/Foundation.h" +#include "CppUnit/TestCase.h" + + +class LogStreamTest: public CppUnit::TestCase +{ +public: + LogStreamTest(const std::string& name); + ~LogStreamTest(); + + void testLogStream(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // LogStreamTest_INCLUDED diff --git a/Foundation/testsuite/src/LoggerTest.cpp b/Foundation/testsuite/src/LoggerTest.cpp index 983d0a84f..128b30f56 100644 --- a/Foundation/testsuite/src/LoggerTest.cpp +++ b/Foundation/testsuite/src/LoggerTest.cpp @@ -1,251 +1,251 @@ -// -// LoggerTest.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/LoggerTest.cpp#2 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "LoggerTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/Logger.h" -#include "Poco/AutoPtr.h" -#include "TestChannel.h" - - -using Poco::Logger; -using Poco::Channel; -using Poco::Message; -using Poco::AutoPtr; - - -LoggerTest::LoggerTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -LoggerTest::~LoggerTest() -{ -} - - -void LoggerTest::testLogger() -{ - AutoPtr pChannel = new TestChannel; - Logger& root = Logger::root(); - root.setChannel(pChannel.get()); - assert (root.getLevel() == Message::PRIO_INFORMATION); - assert (root.is(Message::PRIO_INFORMATION)); - assert (root.fatal()); - assert (root.critical()); - assert (root.error()); - assert (root.warning()); - assert (root.notice()); - assert (root.information()); - assert (!root.debug()); - assert (!root.trace()); - - root.information("Informational message"); - assert (pChannel->list().size() == 1); - root.warning("Warning message"); - assert (pChannel->list().size() == 2); - root.debug("Debug message"); - assert (pChannel->list().size() == 2); - - Logger& logger1 = Logger::get("Logger1"); - Logger& logger2 = Logger::get("Logger2"); - Logger& logger11 = Logger::get("Logger1.Logger1"); - Logger& logger12 = Logger::get("Logger1.Logger2"); - Logger& logger21 = Logger::get("Logger2.Logger1"); - Logger& logger22 = Logger::get("Logger2.Logger2"); - - std::vector loggers; - Logger::names(loggers); - assert (loggers.size() == 7); - assert (loggers[0] == ""); - assert (loggers[1] == "Logger1"); - assert (loggers[2] == "Logger1.Logger1"); - assert (loggers[3] == "Logger1.Logger2"); - assert (loggers[4] == "Logger2"); - assert (loggers[5] == "Logger2.Logger1"); - assert (loggers[6] == "Logger2.Logger2"); - - Logger::setLevel("Logger1", Message::PRIO_DEBUG); - assert (logger1.is(Message::PRIO_DEBUG)); - assert (logger11.is(Message::PRIO_DEBUG)); - assert (logger12.is(Message::PRIO_DEBUG)); - assert (!logger2.is(Message::PRIO_DEBUG)); - assert (!logger21.is(Message::PRIO_DEBUG)); - assert (!logger22.is(Message::PRIO_DEBUG)); - assert (logger11.is(Message::PRIO_INFORMATION)); - assert (logger12.is(Message::PRIO_INFORMATION)); - assert (logger21.is(Message::PRIO_INFORMATION)); - assert (logger22.is(Message::PRIO_INFORMATION)); - - Logger::setLevel("Logger2.Logger1", Message::PRIO_ERROR); - assert (logger1.is(Message::PRIO_DEBUG)); - assert (logger11.is(Message::PRIO_DEBUG)); - assert (logger12.is(Message::PRIO_DEBUG)); - assert (!logger21.is(Message::PRIO_DEBUG)); - assert (!logger22.is(Message::PRIO_DEBUG)); - assert (logger11.is(Message::PRIO_INFORMATION)); - assert (logger12.is(Message::PRIO_INFORMATION)); - assert (logger21.is(Message::PRIO_ERROR)); - assert (logger22.is(Message::PRIO_INFORMATION)); - - Logger::setLevel("", Message::PRIO_WARNING); - assert (root.getLevel() == Message::PRIO_WARNING); - assert (logger1.getLevel() == Message::PRIO_WARNING); - assert (logger11.getLevel() == Message::PRIO_WARNING); - assert (logger12.getLevel() == Message::PRIO_WARNING); - assert (logger1.getLevel() == Message::PRIO_WARNING); - assert (logger21.getLevel() == Message::PRIO_WARNING); - assert (logger22.getLevel() == Message::PRIO_WARNING); - - AutoPtr pChannel2 = new TestChannel; - Logger::setChannel("Logger2", pChannel2.get()); - assert (pChannel == root.getChannel()); - assert (pChannel == logger1.getChannel()); - assert (pChannel == logger11.getChannel()); - assert (pChannel == logger12.getChannel()); - assert (pChannel2 == logger2.getChannel()); - assert (pChannel2 == logger21.getChannel()); - assert (pChannel2 == logger22.getChannel()); - - root.setLevel(Message::PRIO_TRACE); - pChannel->list().clear(); - root.trace("trace"); - assert (pChannel->list().begin()->getPriority() == Message::PRIO_TRACE); - pChannel->list().clear(); - root.debug("debug"); - assert (pChannel->list().begin()->getPriority() == Message::PRIO_DEBUG); - pChannel->list().clear(); - root.information("information"); - assert (pChannel->list().begin()->getPriority() == Message::PRIO_INFORMATION); - pChannel->list().clear(); - root.notice("notice"); - assert (pChannel->list().begin()->getPriority() == Message::PRIO_NOTICE); - pChannel->list().clear(); - root.warning("warning"); - assert (pChannel->list().begin()->getPriority() == Message::PRIO_WARNING); - pChannel->list().clear(); - root.error("error"); - assert (pChannel->list().begin()->getPriority() == Message::PRIO_ERROR); - pChannel->list().clear(); - root.critical("critical"); - assert (pChannel->list().begin()->getPriority() == Message::PRIO_CRITICAL); - pChannel->list().clear(); - root.fatal("fatal"); - assert (pChannel->list().begin()->getPriority() == Message::PRIO_FATAL); -} - - -void LoggerTest::testFormat() -{ - std::string str = Logger::format("$0$1", "foo", "bar"); - assert (str == "foobar"); - str = Logger::format("foo$0", "bar"); - assert (str == "foobar"); - str = Logger::format("the amount is $$ $0", "100"); - assert (str == "the amount is $ 100"); - str = Logger::format("$0$1$2", "foo", "bar"); - assert (str == "foobar"); - str = Logger::format("$foo$0", "bar"); - assert (str == "$foobar"); - str = Logger::format("$0", "1"); - assert (str == "1"); - str = Logger::format("$0$1", "1", "2"); - assert (str == "12"); - str = Logger::format("$0$1$2", "1", "2", "3"); - assert (str == "123"); - str = Logger::format("$0$1$2$3", "1", "2", "3", "4"); - assert (str == "1234"); -} - - -void LoggerTest::testDump() -{ - AutoPtr pChannel = new TestChannel; - Logger& root = Logger::root(); - root.setChannel(pChannel.get()); - root.setLevel(Message::PRIO_INFORMATION); - - char buffer1[] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05}; - root.dump("test", buffer1, sizeof(buffer1)); - assert (pChannel->list().empty()); - - root.setLevel(Message::PRIO_DEBUG); - root.dump("test", buffer1, sizeof(buffer1)); - - std::string msg = pChannel->list().begin()->getText(); - assert (msg == "test\n0000 00 01 02 03 04 05 ......"); - pChannel->clear(); - - char buffer2[] = { - 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, - 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f - }; - root.dump("", buffer2, sizeof(buffer2)); - msg = pChannel->list().begin()->getText(); - assert (msg == "0000 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F ................"); - pChannel->clear(); - - char buffer3[] = { - 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, - 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, - 0x20, 0x41, 0x42, 0x1f, 0x7f, 0x7e - }; - root.dump("", buffer3, sizeof(buffer3)); - msg = pChannel->list().begin()->getText(); - assert (msg == "0000 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F ................\n" - "0010 20 41 42 1F 7F 7E AB..~"); - pChannel->clear(); -} - - -void LoggerTest::setUp() -{ - Logger::shutdown(); -} - - -void LoggerTest::tearDown() -{ -} - - -CppUnit::Test* LoggerTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("LoggerTest"); - - CppUnit_addTest(pSuite, LoggerTest, testLogger); - CppUnit_addTest(pSuite, LoggerTest, testFormat); - CppUnit_addTest(pSuite, LoggerTest, testDump); - - return pSuite; -} +// +// LoggerTest.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/LoggerTest.cpp#2 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "LoggerTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/Logger.h" +#include "Poco/AutoPtr.h" +#include "TestChannel.h" + + +using Poco::Logger; +using Poco::Channel; +using Poco::Message; +using Poco::AutoPtr; + + +LoggerTest::LoggerTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +LoggerTest::~LoggerTest() +{ +} + + +void LoggerTest::testLogger() +{ + AutoPtr pChannel = new TestChannel; + Logger& root = Logger::root(); + root.setChannel(pChannel.get()); + assert (root.getLevel() == Message::PRIO_INFORMATION); + assert (root.is(Message::PRIO_INFORMATION)); + assert (root.fatal()); + assert (root.critical()); + assert (root.error()); + assert (root.warning()); + assert (root.notice()); + assert (root.information()); + assert (!root.debug()); + assert (!root.trace()); + + root.information("Informational message"); + assert (pChannel->list().size() == 1); + root.warning("Warning message"); + assert (pChannel->list().size() == 2); + root.debug("Debug message"); + assert (pChannel->list().size() == 2); + + Logger& logger1 = Logger::get("Logger1"); + Logger& logger2 = Logger::get("Logger2"); + Logger& logger11 = Logger::get("Logger1.Logger1"); + Logger& logger12 = Logger::get("Logger1.Logger2"); + Logger& logger21 = Logger::get("Logger2.Logger1"); + Logger& logger22 = Logger::get("Logger2.Logger2"); + + std::vector loggers; + Logger::names(loggers); + assert (loggers.size() == 7); + assert (loggers[0] == ""); + assert (loggers[1] == "Logger1"); + assert (loggers[2] == "Logger1.Logger1"); + assert (loggers[3] == "Logger1.Logger2"); + assert (loggers[4] == "Logger2"); + assert (loggers[5] == "Logger2.Logger1"); + assert (loggers[6] == "Logger2.Logger2"); + + Logger::setLevel("Logger1", Message::PRIO_DEBUG); + assert (logger1.is(Message::PRIO_DEBUG)); + assert (logger11.is(Message::PRIO_DEBUG)); + assert (logger12.is(Message::PRIO_DEBUG)); + assert (!logger2.is(Message::PRIO_DEBUG)); + assert (!logger21.is(Message::PRIO_DEBUG)); + assert (!logger22.is(Message::PRIO_DEBUG)); + assert (logger11.is(Message::PRIO_INFORMATION)); + assert (logger12.is(Message::PRIO_INFORMATION)); + assert (logger21.is(Message::PRIO_INFORMATION)); + assert (logger22.is(Message::PRIO_INFORMATION)); + + Logger::setLevel("Logger2.Logger1", Message::PRIO_ERROR); + assert (logger1.is(Message::PRIO_DEBUG)); + assert (logger11.is(Message::PRIO_DEBUG)); + assert (logger12.is(Message::PRIO_DEBUG)); + assert (!logger21.is(Message::PRIO_DEBUG)); + assert (!logger22.is(Message::PRIO_DEBUG)); + assert (logger11.is(Message::PRIO_INFORMATION)); + assert (logger12.is(Message::PRIO_INFORMATION)); + assert (logger21.is(Message::PRIO_ERROR)); + assert (logger22.is(Message::PRIO_INFORMATION)); + + Logger::setLevel("", Message::PRIO_WARNING); + assert (root.getLevel() == Message::PRIO_WARNING); + assert (logger1.getLevel() == Message::PRIO_WARNING); + assert (logger11.getLevel() == Message::PRIO_WARNING); + assert (logger12.getLevel() == Message::PRIO_WARNING); + assert (logger1.getLevel() == Message::PRIO_WARNING); + assert (logger21.getLevel() == Message::PRIO_WARNING); + assert (logger22.getLevel() == Message::PRIO_WARNING); + + AutoPtr pChannel2 = new TestChannel; + Logger::setChannel("Logger2", pChannel2.get()); + assert (pChannel == root.getChannel()); + assert (pChannel == logger1.getChannel()); + assert (pChannel == logger11.getChannel()); + assert (pChannel == logger12.getChannel()); + assert (pChannel2 == logger2.getChannel()); + assert (pChannel2 == logger21.getChannel()); + assert (pChannel2 == logger22.getChannel()); + + root.setLevel(Message::PRIO_TRACE); + pChannel->list().clear(); + root.trace("trace"); + assert (pChannel->list().begin()->getPriority() == Message::PRIO_TRACE); + pChannel->list().clear(); + root.debug("debug"); + assert (pChannel->list().begin()->getPriority() == Message::PRIO_DEBUG); + pChannel->list().clear(); + root.information("information"); + assert (pChannel->list().begin()->getPriority() == Message::PRIO_INFORMATION); + pChannel->list().clear(); + root.notice("notice"); + assert (pChannel->list().begin()->getPriority() == Message::PRIO_NOTICE); + pChannel->list().clear(); + root.warning("warning"); + assert (pChannel->list().begin()->getPriority() == Message::PRIO_WARNING); + pChannel->list().clear(); + root.error("error"); + assert (pChannel->list().begin()->getPriority() == Message::PRIO_ERROR); + pChannel->list().clear(); + root.critical("critical"); + assert (pChannel->list().begin()->getPriority() == Message::PRIO_CRITICAL); + pChannel->list().clear(); + root.fatal("fatal"); + assert (pChannel->list().begin()->getPriority() == Message::PRIO_FATAL); +} + + +void LoggerTest::testFormat() +{ + std::string str = Logger::format("$0$1", "foo", "bar"); + assert (str == "foobar"); + str = Logger::format("foo$0", "bar"); + assert (str == "foobar"); + str = Logger::format("the amount is $$ $0", "100"); + assert (str == "the amount is $ 100"); + str = Logger::format("$0$1$2", "foo", "bar"); + assert (str == "foobar"); + str = Logger::format("$foo$0", "bar"); + assert (str == "$foobar"); + str = Logger::format("$0", "1"); + assert (str == "1"); + str = Logger::format("$0$1", "1", "2"); + assert (str == "12"); + str = Logger::format("$0$1$2", "1", "2", "3"); + assert (str == "123"); + str = Logger::format("$0$1$2$3", "1", "2", "3", "4"); + assert (str == "1234"); +} + + +void LoggerTest::testDump() +{ + AutoPtr pChannel = new TestChannel; + Logger& root = Logger::root(); + root.setChannel(pChannel.get()); + root.setLevel(Message::PRIO_INFORMATION); + + char buffer1[] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05}; + root.dump("test", buffer1, sizeof(buffer1)); + assert (pChannel->list().empty()); + + root.setLevel(Message::PRIO_DEBUG); + root.dump("test", buffer1, sizeof(buffer1)); + + std::string msg = pChannel->list().begin()->getText(); + assert (msg == "test\n0000 00 01 02 03 04 05 ......"); + pChannel->clear(); + + char buffer2[] = { + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, + 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f + }; + root.dump("", buffer2, sizeof(buffer2)); + msg = pChannel->list().begin()->getText(); + assert (msg == "0000 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F ................"); + pChannel->clear(); + + char buffer3[] = { + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, + 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, + 0x20, 0x41, 0x42, 0x1f, 0x7f, 0x7e + }; + root.dump("", buffer3, sizeof(buffer3)); + msg = pChannel->list().begin()->getText(); + assert (msg == "0000 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F ................\n" + "0010 20 41 42 1F 7F 7E AB..~"); + pChannel->clear(); +} + + +void LoggerTest::setUp() +{ + Logger::shutdown(); +} + + +void LoggerTest::tearDown() +{ +} + + +CppUnit::Test* LoggerTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("LoggerTest"); + + CppUnit_addTest(pSuite, LoggerTest, testLogger); + CppUnit_addTest(pSuite, LoggerTest, testFormat); + CppUnit_addTest(pSuite, LoggerTest, testDump); + + return pSuite; +} diff --git a/Foundation/testsuite/src/LoggerTest.h b/Foundation/testsuite/src/LoggerTest.h index 62c61ce55..05e7b95a8 100644 --- a/Foundation/testsuite/src/LoggerTest.h +++ b/Foundation/testsuite/src/LoggerTest.h @@ -1,62 +1,62 @@ -// -// LoggerTest.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/LoggerTest.h#1 $ -// -// Definition of the LoggerTest class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 LoggerTest_INCLUDED -#define LoggerTest_INCLUDED - - -#include "Poco/Foundation.h" -#include "CppUnit/TestCase.h" - - -class LoggerTest: public CppUnit::TestCase -{ -public: - LoggerTest(const std::string& name); - ~LoggerTest(); - - void testLogger(); - void testFormat(); - void testDump(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // LoggerTest_INCLUDED +// +// LoggerTest.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/LoggerTest.h#1 $ +// +// Definition of the LoggerTest class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 LoggerTest_INCLUDED +#define LoggerTest_INCLUDED + + +#include "Poco/Foundation.h" +#include "CppUnit/TestCase.h" + + +class LoggerTest: public CppUnit::TestCase +{ +public: + LoggerTest(const std::string& name); + ~LoggerTest(); + + void testLogger(); + void testFormat(); + void testDump(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // LoggerTest_INCLUDED diff --git a/Foundation/testsuite/src/LoggingFactoryTest.cpp b/Foundation/testsuite/src/LoggingFactoryTest.cpp index 2402acfc0..e50d8c33e 100644 --- a/Foundation/testsuite/src/LoggingFactoryTest.cpp +++ b/Foundation/testsuite/src/LoggingFactoryTest.cpp @@ -1,160 +1,160 @@ -// -// LoggingFactoryTest.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/LoggingFactoryTest.cpp#1 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "LoggingFactoryTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/LoggingFactory.h" -#include "Poco/Instantiator.h" -#include "Poco/Channel.h" -#include "Poco/ConsoleChannel.h" -#include "Poco/FileChannel.h" -#include "Poco/SplitterChannel.h" -#include "Poco/Formatter.h" -#include "Poco/PatternFormatter.h" -#include "Poco/Message.h" -#include "Poco/AutoPtr.h" -#include "Poco/Exception.h" -#include - - -using Poco::LoggingFactory; -using Poco::Channel; -using Poco::ConsoleChannel; -using Poco::FileChannel; -using Poco::SplitterChannel; -using Poco::Formatter; -using Poco::PatternFormatter; -using Poco::Message; -using Poco::AutoPtr; -using Poco::Instantiator; - - -namespace -{ - class CustomChannel: public Channel - { - public: - void log(const Message& msg) - { - } - }; - - class CustomFormatter: public Formatter - { - void format(const Message& msg, std::string& text) - { - } - }; -} - - -LoggingFactoryTest::LoggingFactoryTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -LoggingFactoryTest::~LoggingFactoryTest() -{ -} - - -void LoggingFactoryTest::testBuiltins() -{ - LoggingFactory& fact = LoggingFactory::defaultFactory(); - - AutoPtr pConsoleChannel = fact.createChannel("ConsoleChannel"); - assert (dynamic_cast(pConsoleChannel.get()) != 0); - - AutoPtr pFileChannel = fact.createChannel("FileChannel"); - assert (dynamic_cast(pFileChannel.get()) != 0); - - AutoPtr pSplitterChannel = fact.createChannel("SplitterChannel"); - assert (dynamic_cast(pSplitterChannel.get()) != 0); - - try - { - AutoPtr pUnknownChannel = fact.createChannel("UnknownChannel"); - fail("unknown class - must throw"); - } - catch (Poco::NotFoundException&) - { - } - - AutoPtr pPatternFormatter = fact.createFormatter("PatternFormatter"); - assert (dynamic_cast(pPatternFormatter.get()) != 0); - - try - { - AutoPtr pUnknownFormatter = fact.createFormatter("UnknownFormatter"); - fail("unknown class - must throw"); - } - catch (Poco::NotFoundException&) - { - } -} - - -void LoggingFactoryTest::testCustom() -{ - std::auto_ptr fact(new LoggingFactory); - - fact->registerChannelClass("CustomChannel", new Instantiator); - fact->registerFormatterClass("CustomFormatter", new Instantiator); - - AutoPtr pCustomChannel = fact->createChannel("CustomChannel"); - assert (dynamic_cast(pCustomChannel.get()) != 0); - - AutoPtr pCustomFormatter = fact->createFormatter("CustomFormatter"); - assert (dynamic_cast(pCustomFormatter.get()) != 0); -} - - -void LoggingFactoryTest::setUp() -{ -} - - -void LoggingFactoryTest::tearDown() -{ -} - - -CppUnit::Test* LoggingFactoryTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("LoggingFactoryTest"); - - CppUnit_addTest(pSuite, LoggingFactoryTest, testBuiltins); - CppUnit_addTest(pSuite, LoggingFactoryTest, testCustom); - - return pSuite; -} +// +// LoggingFactoryTest.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/LoggingFactoryTest.cpp#1 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "LoggingFactoryTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/LoggingFactory.h" +#include "Poco/Instantiator.h" +#include "Poco/Channel.h" +#include "Poco/ConsoleChannel.h" +#include "Poco/FileChannel.h" +#include "Poco/SplitterChannel.h" +#include "Poco/Formatter.h" +#include "Poco/PatternFormatter.h" +#include "Poco/Message.h" +#include "Poco/AutoPtr.h" +#include "Poco/Exception.h" +#include + + +using Poco::LoggingFactory; +using Poco::Channel; +using Poco::ConsoleChannel; +using Poco::FileChannel; +using Poco::SplitterChannel; +using Poco::Formatter; +using Poco::PatternFormatter; +using Poco::Message; +using Poco::AutoPtr; +using Poco::Instantiator; + + +namespace +{ + class CustomChannel: public Channel + { + public: + void log(const Message& msg) + { + } + }; + + class CustomFormatter: public Formatter + { + void format(const Message& msg, std::string& text) + { + } + }; +} + + +LoggingFactoryTest::LoggingFactoryTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +LoggingFactoryTest::~LoggingFactoryTest() +{ +} + + +void LoggingFactoryTest::testBuiltins() +{ + LoggingFactory& fact = LoggingFactory::defaultFactory(); + + AutoPtr pConsoleChannel = fact.createChannel("ConsoleChannel"); + assert (dynamic_cast(pConsoleChannel.get()) != 0); + + AutoPtr pFileChannel = fact.createChannel("FileChannel"); + assert (dynamic_cast(pFileChannel.get()) != 0); + + AutoPtr pSplitterChannel = fact.createChannel("SplitterChannel"); + assert (dynamic_cast(pSplitterChannel.get()) != 0); + + try + { + AutoPtr pUnknownChannel = fact.createChannel("UnknownChannel"); + fail("unknown class - must throw"); + } + catch (Poco::NotFoundException&) + { + } + + AutoPtr pPatternFormatter = fact.createFormatter("PatternFormatter"); + assert (dynamic_cast(pPatternFormatter.get()) != 0); + + try + { + AutoPtr pUnknownFormatter = fact.createFormatter("UnknownFormatter"); + fail("unknown class - must throw"); + } + catch (Poco::NotFoundException&) + { + } +} + + +void LoggingFactoryTest::testCustom() +{ + std::auto_ptr fact(new LoggingFactory); + + fact->registerChannelClass("CustomChannel", new Instantiator); + fact->registerFormatterClass("CustomFormatter", new Instantiator); + + AutoPtr pCustomChannel = fact->createChannel("CustomChannel"); + assert (dynamic_cast(pCustomChannel.get()) != 0); + + AutoPtr pCustomFormatter = fact->createFormatter("CustomFormatter"); + assert (dynamic_cast(pCustomFormatter.get()) != 0); +} + + +void LoggingFactoryTest::setUp() +{ +} + + +void LoggingFactoryTest::tearDown() +{ +} + + +CppUnit::Test* LoggingFactoryTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("LoggingFactoryTest"); + + CppUnit_addTest(pSuite, LoggingFactoryTest, testBuiltins); + CppUnit_addTest(pSuite, LoggingFactoryTest, testCustom); + + return pSuite; +} diff --git a/Foundation/testsuite/src/LoggingFactoryTest.h b/Foundation/testsuite/src/LoggingFactoryTest.h index 0a67f60c1..0f63b49ea 100644 --- a/Foundation/testsuite/src/LoggingFactoryTest.h +++ b/Foundation/testsuite/src/LoggingFactoryTest.h @@ -1,61 +1,61 @@ -// -// LoggingFactoryTest.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/LoggingFactoryTest.h#1 $ -// -// Definition of the LoggingFactoryTest class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 LoggingFactoryTest_INCLUDED -#define LoggingFactoryTest_INCLUDED - - -#include "Poco/Foundation.h" -#include "CppUnit/TestCase.h" - - -class LoggingFactoryTest: public CppUnit::TestCase -{ -public: - LoggingFactoryTest(const std::string& name); - ~LoggingFactoryTest(); - - void testBuiltins(); - void testCustom(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // LoggingFactoryTest_INCLUDED +// +// LoggingFactoryTest.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/LoggingFactoryTest.h#1 $ +// +// Definition of the LoggingFactoryTest class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 LoggingFactoryTest_INCLUDED +#define LoggingFactoryTest_INCLUDED + + +#include "Poco/Foundation.h" +#include "CppUnit/TestCase.h" + + +class LoggingFactoryTest: public CppUnit::TestCase +{ +public: + LoggingFactoryTest(const std::string& name); + ~LoggingFactoryTest(); + + void testBuiltins(); + void testCustom(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // LoggingFactoryTest_INCLUDED diff --git a/Foundation/testsuite/src/LoggingRegistryTest.cpp b/Foundation/testsuite/src/LoggingRegistryTest.cpp index c0dd154b1..918c53150 100644 --- a/Foundation/testsuite/src/LoggingRegistryTest.cpp +++ b/Foundation/testsuite/src/LoggingRegistryTest.cpp @@ -1,188 +1,188 @@ -// -// LoggingRegistryTest.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/LoggingRegistryTest.cpp#1 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "LoggingRegistryTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/LoggingRegistry.h" -#include "Poco/ConsoleChannel.h" -#include "Poco/PatternFormatter.h" -#include "Poco/AutoPtr.h" - - -using Poco::LoggingRegistry; -using Poco::Channel; -using Poco::ConsoleChannel; -using Poco::Formatter; -using Poco::PatternFormatter; -using Poco::AutoPtr; - - -LoggingRegistryTest::LoggingRegistryTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -LoggingRegistryTest::~LoggingRegistryTest() -{ -} - - -void LoggingRegistryTest::testRegister() -{ - LoggingRegistry& reg = LoggingRegistry::defaultRegistry(); - - reg.clear(); - - AutoPtr pC1 = new ConsoleChannel(); - AutoPtr pC2 = new ConsoleChannel(); - AutoPtr pF1 = new PatternFormatter(""); - AutoPtr pF2 = new PatternFormatter(""); - - reg.registerChannel("c1", pC1); - reg.registerChannel("c2", pC2); - reg.registerFormatter("f1", pF1); - reg.registerFormatter("f2", pF2); - - Channel* pC = reg.channelForName("c1"); - assert (pC1 == pC); - pC = reg.channelForName("c2"); - assert (pC2 == pC); - - Formatter* pF = reg.formatterForName("f1"); - assert (pF1 == pF); - pF = reg.formatterForName("f2"); - assert (pF2 == pF); - - try - { - pC = reg.channelForName("c3"); - fail("not found - must throw"); - } - catch (Poco::NotFoundException&) - { - } -} - - -void LoggingRegistryTest::testReregister() -{ - LoggingRegistry& reg = LoggingRegistry::defaultRegistry(); - - reg.clear(); - - AutoPtr pC1 = new ConsoleChannel(); - AutoPtr pC2 = new ConsoleChannel(); - AutoPtr pC1b = new ConsoleChannel(); - AutoPtr pF1 = new PatternFormatter(""); - AutoPtr pF2 = new PatternFormatter(""); - AutoPtr pF1b = new PatternFormatter(""); - - reg.registerChannel("c1", pC1); - reg.registerChannel("c2", pC2); - reg.registerFormatter("f1", pF1); - reg.registerFormatter("f2", pF2); - - reg.registerChannel("c1", pC1b); - Channel* pC = reg.channelForName("c1"); - assert (pC1b == pC); - pC = reg.channelForName("c2"); - assert (pC2 == pC); - - reg.registerFormatter("f1", pF1b); - Formatter* pF = reg.formatterForName("f1"); - assert (pF1b == pF); - pF = reg.formatterForName("f2"); - assert (pF2 == pF); - -} - - -void LoggingRegistryTest::testUnregister() -{ - LoggingRegistry& reg = LoggingRegistry::defaultRegistry(); - - reg.clear(); - - AutoPtr pC1 = new ConsoleChannel(); - AutoPtr pC2 = new ConsoleChannel(); - AutoPtr pF1 = new PatternFormatter(""); - AutoPtr pF2 = new PatternFormatter(""); - - reg.registerChannel("c1", pC1); - reg.registerChannel("c2", pC2); - reg.registerFormatter("f1", pF1); - reg.registerFormatter("f2", pF2); - - reg.unregisterChannel("c1"); - reg.unregisterFormatter("f2"); - - try - { - Channel* pC = reg.channelForName("c1"); - fail("unregistered - must throw"); - } - catch (Poco::NotFoundException&) - { - } - - try - { - Formatter* pF = reg.formatterForName("f2"); - fail("unregistered - must throw"); - } - catch (Poco::NotFoundException&) - { - } -} - - -void LoggingRegistryTest::setUp() -{ -} - - -void LoggingRegistryTest::tearDown() -{ -} - - -CppUnit::Test* LoggingRegistryTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("LoggingRegistryTest"); - - CppUnit_addTest(pSuite, LoggingRegistryTest, testRegister); - CppUnit_addTest(pSuite, LoggingRegistryTest, testReregister); - CppUnit_addTest(pSuite, LoggingRegistryTest, testUnregister); - - return pSuite; -} +// +// LoggingRegistryTest.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/LoggingRegistryTest.cpp#1 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "LoggingRegistryTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/LoggingRegistry.h" +#include "Poco/ConsoleChannel.h" +#include "Poco/PatternFormatter.h" +#include "Poco/AutoPtr.h" + + +using Poco::LoggingRegistry; +using Poco::Channel; +using Poco::ConsoleChannel; +using Poco::Formatter; +using Poco::PatternFormatter; +using Poco::AutoPtr; + + +LoggingRegistryTest::LoggingRegistryTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +LoggingRegistryTest::~LoggingRegistryTest() +{ +} + + +void LoggingRegistryTest::testRegister() +{ + LoggingRegistry& reg = LoggingRegistry::defaultRegistry(); + + reg.clear(); + + AutoPtr pC1 = new ConsoleChannel(); + AutoPtr pC2 = new ConsoleChannel(); + AutoPtr pF1 = new PatternFormatter(""); + AutoPtr pF2 = new PatternFormatter(""); + + reg.registerChannel("c1", pC1); + reg.registerChannel("c2", pC2); + reg.registerFormatter("f1", pF1); + reg.registerFormatter("f2", pF2); + + Channel* pC = reg.channelForName("c1"); + assert (pC1 == pC); + pC = reg.channelForName("c2"); + assert (pC2 == pC); + + Formatter* pF = reg.formatterForName("f1"); + assert (pF1 == pF); + pF = reg.formatterForName("f2"); + assert (pF2 == pF); + + try + { + pC = reg.channelForName("c3"); + fail("not found - must throw"); + } + catch (Poco::NotFoundException&) + { + } +} + + +void LoggingRegistryTest::testReregister() +{ + LoggingRegistry& reg = LoggingRegistry::defaultRegistry(); + + reg.clear(); + + AutoPtr pC1 = new ConsoleChannel(); + AutoPtr pC2 = new ConsoleChannel(); + AutoPtr pC1b = new ConsoleChannel(); + AutoPtr pF1 = new PatternFormatter(""); + AutoPtr pF2 = new PatternFormatter(""); + AutoPtr pF1b = new PatternFormatter(""); + + reg.registerChannel("c1", pC1); + reg.registerChannel("c2", pC2); + reg.registerFormatter("f1", pF1); + reg.registerFormatter("f2", pF2); + + reg.registerChannel("c1", pC1b); + Channel* pC = reg.channelForName("c1"); + assert (pC1b == pC); + pC = reg.channelForName("c2"); + assert (pC2 == pC); + + reg.registerFormatter("f1", pF1b); + Formatter* pF = reg.formatterForName("f1"); + assert (pF1b == pF); + pF = reg.formatterForName("f2"); + assert (pF2 == pF); + +} + + +void LoggingRegistryTest::testUnregister() +{ + LoggingRegistry& reg = LoggingRegistry::defaultRegistry(); + + reg.clear(); + + AutoPtr pC1 = new ConsoleChannel(); + AutoPtr pC2 = new ConsoleChannel(); + AutoPtr pF1 = new PatternFormatter(""); + AutoPtr pF2 = new PatternFormatter(""); + + reg.registerChannel("c1", pC1); + reg.registerChannel("c2", pC2); + reg.registerFormatter("f1", pF1); + reg.registerFormatter("f2", pF2); + + reg.unregisterChannel("c1"); + reg.unregisterFormatter("f2"); + + try + { + Channel* pC = reg.channelForName("c1"); + fail("unregistered - must throw"); + } + catch (Poco::NotFoundException&) + { + } + + try + { + Formatter* pF = reg.formatterForName("f2"); + fail("unregistered - must throw"); + } + catch (Poco::NotFoundException&) + { + } +} + + +void LoggingRegistryTest::setUp() +{ +} + + +void LoggingRegistryTest::tearDown() +{ +} + + +CppUnit::Test* LoggingRegistryTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("LoggingRegistryTest"); + + CppUnit_addTest(pSuite, LoggingRegistryTest, testRegister); + CppUnit_addTest(pSuite, LoggingRegistryTest, testReregister); + CppUnit_addTest(pSuite, LoggingRegistryTest, testUnregister); + + return pSuite; +} diff --git a/Foundation/testsuite/src/LoggingRegistryTest.h b/Foundation/testsuite/src/LoggingRegistryTest.h index b91e6403f..ffdfa698e 100644 --- a/Foundation/testsuite/src/LoggingRegistryTest.h +++ b/Foundation/testsuite/src/LoggingRegistryTest.h @@ -1,62 +1,62 @@ -// -// LoggingRegistryTest.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/LoggingRegistryTest.h#1 $ -// -// Definition of the LoggingRegistryTest class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 LoggingRegistryTest_INCLUDED -#define LoggingRegistryTest_INCLUDED - - -#include "Poco/Foundation.h" -#include "CppUnit/TestCase.h" - - -class LoggingRegistryTest: public CppUnit::TestCase -{ -public: - LoggingRegistryTest(const std::string& name); - ~LoggingRegistryTest(); - - void testRegister(); - void testReregister(); - void testUnregister(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // LoggingRegistryTest_INCLUDED +// +// LoggingRegistryTest.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/LoggingRegistryTest.h#1 $ +// +// Definition of the LoggingRegistryTest class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 LoggingRegistryTest_INCLUDED +#define LoggingRegistryTest_INCLUDED + + +#include "Poco/Foundation.h" +#include "CppUnit/TestCase.h" + + +class LoggingRegistryTest: public CppUnit::TestCase +{ +public: + LoggingRegistryTest(const std::string& name); + ~LoggingRegistryTest(); + + void testRegister(); + void testReregister(); + void testUnregister(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // LoggingRegistryTest_INCLUDED diff --git a/Foundation/testsuite/src/LoggingTestSuite.cpp b/Foundation/testsuite/src/LoggingTestSuite.cpp index 0ca07457a..d6cbfee9f 100644 --- a/Foundation/testsuite/src/LoggingTestSuite.cpp +++ b/Foundation/testsuite/src/LoggingTestSuite.cpp @@ -1,58 +1,58 @@ -// -// LoggingTestSuite.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/LoggingTestSuite.cpp#1 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "LoggingTestSuite.h" -#include "LoggerTest.h" -#include "ChannelTest.h" -#include "PatternFormatterTest.h" -#include "FileChannelTest.h" -#include "SimpleFileChannelTest.h" -#include "LoggingFactoryTest.h" -#include "LoggingRegistryTest.h" -#include "LogStreamTest.h" - - -CppUnit::Test* LoggingTestSuite::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("LoggingTestSuite"); - - pSuite->addTest(LoggerTest::suite()); - pSuite->addTest(ChannelTest::suite()); - pSuite->addTest(PatternFormatterTest::suite()); - pSuite->addTest(FileChannelTest::suite()); - pSuite->addTest(SimpleFileChannelTest::suite()); - pSuite->addTest(LoggingFactoryTest::suite()); - pSuite->addTest(LoggingRegistryTest::suite()); - pSuite->addTest(LogStreamTest::suite()); - - return pSuite; -} +// +// LoggingTestSuite.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/LoggingTestSuite.cpp#1 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "LoggingTestSuite.h" +#include "LoggerTest.h" +#include "ChannelTest.h" +#include "PatternFormatterTest.h" +#include "FileChannelTest.h" +#include "SimpleFileChannelTest.h" +#include "LoggingFactoryTest.h" +#include "LoggingRegistryTest.h" +#include "LogStreamTest.h" + + +CppUnit::Test* LoggingTestSuite::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("LoggingTestSuite"); + + pSuite->addTest(LoggerTest::suite()); + pSuite->addTest(ChannelTest::suite()); + pSuite->addTest(PatternFormatterTest::suite()); + pSuite->addTest(FileChannelTest::suite()); + pSuite->addTest(SimpleFileChannelTest::suite()); + pSuite->addTest(LoggingFactoryTest::suite()); + pSuite->addTest(LoggingRegistryTest::suite()); + pSuite->addTest(LogStreamTest::suite()); + + return pSuite; +} diff --git a/Foundation/testsuite/src/LoggingTestSuite.h b/Foundation/testsuite/src/LoggingTestSuite.h index 285831422..04ecbf3b0 100644 --- a/Foundation/testsuite/src/LoggingTestSuite.h +++ b/Foundation/testsuite/src/LoggingTestSuite.h @@ -1,49 +1,49 @@ -// -// LoggingTestSuite.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/LoggingTestSuite.h#1 $ -// -// Definition of the LoggingTestSuite class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 LoggingTestSuite_INCLUDED -#define LoggingTestSuite_INCLUDED - - -#include "CppUnit/TestSuite.h" - - -class LoggingTestSuite -{ -public: - static CppUnit::Test* suite(); -}; - - -#endif // LoggingTestSuite_INCLUDED +// +// LoggingTestSuite.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/LoggingTestSuite.h#1 $ +// +// Definition of the LoggingTestSuite class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 LoggingTestSuite_INCLUDED +#define LoggingTestSuite_INCLUDED + + +#include "CppUnit/TestSuite.h" + + +class LoggingTestSuite +{ +public: + static CppUnit::Test* suite(); +}; + + +#endif // LoggingTestSuite_INCLUDED diff --git a/Foundation/testsuite/src/MD2EngineTest.cpp b/Foundation/testsuite/src/MD2EngineTest.cpp index 060301edf..2ba46f492 100644 --- a/Foundation/testsuite/src/MD2EngineTest.cpp +++ b/Foundation/testsuite/src/MD2EngineTest.cpp @@ -1,100 +1,100 @@ -// -// MD2EngineTest.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/MD2EngineTest.cpp#1 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "MD2EngineTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/MD2Engine.h" - - -using Poco::MD2Engine; -using Poco::DigestEngine; - - -MD2EngineTest::MD2EngineTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -MD2EngineTest::~MD2EngineTest() -{ -} - - -void MD2EngineTest::testMD2() -{ - MD2Engine engine; - - // test vectors from RFC 1319 - - engine.update(""); - assert (DigestEngine::digestToHex(engine.digest()) == "8350e5a3e24c153df2275c9f80692773"); - - engine.update("a"); - assert (DigestEngine::digestToHex(engine.digest()) == "32ec01ec4a6dac72c0ab96fb34c0b5d1"); - - engine.update("abc"); - assert (DigestEngine::digestToHex(engine.digest()) == "da853b0d3f88d99b30283a69e6ded6bb"); - - engine.update("message digest"); - assert (DigestEngine::digestToHex(engine.digest()) == "ab4f496bfb2a530b219ff33031fe06b0"); - - engine.update("abcdefghijklmnopqrstuvwxyz"); - assert (DigestEngine::digestToHex(engine.digest()) == "4e8ddff3650292ab5a4108c3aa47940b"); - - engine.update("ABCDEFGHIJKLMNOPQRSTUVWXYZ"); - engine.update("abcdefghijklmnopqrstuvwxyz0123456789"); - assert (DigestEngine::digestToHex(engine.digest()) == "da33def2a42df13975352846c30338cd"); - - engine.update("12345678901234567890123456789012345678901234567890123456789012345678901234567890"); - assert (DigestEngine::digestToHex(engine.digest()) == "d5976f79d83d3a0dc9806c3c66f3efd8"); -} - - -void MD2EngineTest::setUp() -{ -} - - -void MD2EngineTest::tearDown() -{ -} - - -CppUnit::Test* MD2EngineTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("MD2EngineTest"); - - CppUnit_addTest(pSuite, MD2EngineTest, testMD2); - - return pSuite; -} +// +// MD2EngineTest.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/MD2EngineTest.cpp#1 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "MD2EngineTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/MD2Engine.h" + + +using Poco::MD2Engine; +using Poco::DigestEngine; + + +MD2EngineTest::MD2EngineTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +MD2EngineTest::~MD2EngineTest() +{ +} + + +void MD2EngineTest::testMD2() +{ + MD2Engine engine; + + // test vectors from RFC 1319 + + engine.update(""); + assert (DigestEngine::digestToHex(engine.digest()) == "8350e5a3e24c153df2275c9f80692773"); + + engine.update("a"); + assert (DigestEngine::digestToHex(engine.digest()) == "32ec01ec4a6dac72c0ab96fb34c0b5d1"); + + engine.update("abc"); + assert (DigestEngine::digestToHex(engine.digest()) == "da853b0d3f88d99b30283a69e6ded6bb"); + + engine.update("message digest"); + assert (DigestEngine::digestToHex(engine.digest()) == "ab4f496bfb2a530b219ff33031fe06b0"); + + engine.update("abcdefghijklmnopqrstuvwxyz"); + assert (DigestEngine::digestToHex(engine.digest()) == "4e8ddff3650292ab5a4108c3aa47940b"); + + engine.update("ABCDEFGHIJKLMNOPQRSTUVWXYZ"); + engine.update("abcdefghijklmnopqrstuvwxyz0123456789"); + assert (DigestEngine::digestToHex(engine.digest()) == "da33def2a42df13975352846c30338cd"); + + engine.update("12345678901234567890123456789012345678901234567890123456789012345678901234567890"); + assert (DigestEngine::digestToHex(engine.digest()) == "d5976f79d83d3a0dc9806c3c66f3efd8"); +} + + +void MD2EngineTest::setUp() +{ +} + + +void MD2EngineTest::tearDown() +{ +} + + +CppUnit::Test* MD2EngineTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("MD2EngineTest"); + + CppUnit_addTest(pSuite, MD2EngineTest, testMD2); + + return pSuite; +} diff --git a/Foundation/testsuite/src/MD2EngineTest.h b/Foundation/testsuite/src/MD2EngineTest.h index 7a164594c..b8fdaa9c5 100644 --- a/Foundation/testsuite/src/MD2EngineTest.h +++ b/Foundation/testsuite/src/MD2EngineTest.h @@ -1,60 +1,60 @@ -// -// MD2EngineTest.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/MD2EngineTest.h#1 $ -// -// Definition of the MD2EngineTest class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 MD2EngineTest_INCLUDED -#define MD2EngineTest_INCLUDED - - -#include "Poco/Foundation.h" -#include "CppUnit/TestCase.h" - - -class MD2EngineTest: public CppUnit::TestCase -{ -public: - MD2EngineTest(const std::string& name); - ~MD2EngineTest(); - - void testMD2(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // MD2EngineTest_INCLUDED +// +// MD2EngineTest.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/MD2EngineTest.h#1 $ +// +// Definition of the MD2EngineTest class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 MD2EngineTest_INCLUDED +#define MD2EngineTest_INCLUDED + + +#include "Poco/Foundation.h" +#include "CppUnit/TestCase.h" + + +class MD2EngineTest: public CppUnit::TestCase +{ +public: + MD2EngineTest(const std::string& name); + ~MD2EngineTest(); + + void testMD2(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // MD2EngineTest_INCLUDED diff --git a/Foundation/testsuite/src/MD4EngineTest.cpp b/Foundation/testsuite/src/MD4EngineTest.cpp index eea6064e9..ff254b87d 100644 --- a/Foundation/testsuite/src/MD4EngineTest.cpp +++ b/Foundation/testsuite/src/MD4EngineTest.cpp @@ -1,100 +1,100 @@ -// -// MD4EngineTest.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/MD4EngineTest.cpp#1 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "MD4EngineTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/MD4Engine.h" - - -using Poco::MD4Engine; -using Poco::DigestEngine; - - -MD4EngineTest::MD4EngineTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -MD4EngineTest::~MD4EngineTest() -{ -} - - -void MD4EngineTest::testMD4() -{ - MD4Engine engine; - - // test vectors from RFC 1320 - - engine.update(""); - assert (DigestEngine::digestToHex(engine.digest()) == "31d6cfe0d16ae931b73c59d7e0c089c0"); - - engine.update("a"); - assert (DigestEngine::digestToHex(engine.digest()) == "bde52cb31de33e46245e05fbdbd6fb24"); - - engine.update("abc"); - assert (DigestEngine::digestToHex(engine.digest()) == "a448017aaf21d8525fc10ae87aa6729d"); - - engine.update("message digest"); - assert (DigestEngine::digestToHex(engine.digest()) == "d9130a8164549fe818874806e1c7014b"); - - engine.update("abcdefghijklmnopqrstuvwxyz"); - assert (DigestEngine::digestToHex(engine.digest()) == "d79e1c308aa5bbcdeea8ed63df412da9"); - - engine.update("ABCDEFGHIJKLMNOPQRSTUVWXYZ"); - engine.update("abcdefghijklmnopqrstuvwxyz0123456789"); - assert (DigestEngine::digestToHex(engine.digest()) == "043f8582f241db351ce627e153e7f0e4"); - - engine.update("12345678901234567890123456789012345678901234567890123456789012345678901234567890"); - assert (DigestEngine::digestToHex(engine.digest()) == "e33b4ddc9c38f2199c3e7b164fcc0536"); -} - - -void MD4EngineTest::setUp() -{ -} - - -void MD4EngineTest::tearDown() -{ -} - - -CppUnit::Test* MD4EngineTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("MD4EngineTest"); - - CppUnit_addTest(pSuite, MD4EngineTest, testMD4); - - return pSuite; -} +// +// MD4EngineTest.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/MD4EngineTest.cpp#1 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "MD4EngineTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/MD4Engine.h" + + +using Poco::MD4Engine; +using Poco::DigestEngine; + + +MD4EngineTest::MD4EngineTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +MD4EngineTest::~MD4EngineTest() +{ +} + + +void MD4EngineTest::testMD4() +{ + MD4Engine engine; + + // test vectors from RFC 1320 + + engine.update(""); + assert (DigestEngine::digestToHex(engine.digest()) == "31d6cfe0d16ae931b73c59d7e0c089c0"); + + engine.update("a"); + assert (DigestEngine::digestToHex(engine.digest()) == "bde52cb31de33e46245e05fbdbd6fb24"); + + engine.update("abc"); + assert (DigestEngine::digestToHex(engine.digest()) == "a448017aaf21d8525fc10ae87aa6729d"); + + engine.update("message digest"); + assert (DigestEngine::digestToHex(engine.digest()) == "d9130a8164549fe818874806e1c7014b"); + + engine.update("abcdefghijklmnopqrstuvwxyz"); + assert (DigestEngine::digestToHex(engine.digest()) == "d79e1c308aa5bbcdeea8ed63df412da9"); + + engine.update("ABCDEFGHIJKLMNOPQRSTUVWXYZ"); + engine.update("abcdefghijklmnopqrstuvwxyz0123456789"); + assert (DigestEngine::digestToHex(engine.digest()) == "043f8582f241db351ce627e153e7f0e4"); + + engine.update("12345678901234567890123456789012345678901234567890123456789012345678901234567890"); + assert (DigestEngine::digestToHex(engine.digest()) == "e33b4ddc9c38f2199c3e7b164fcc0536"); +} + + +void MD4EngineTest::setUp() +{ +} + + +void MD4EngineTest::tearDown() +{ +} + + +CppUnit::Test* MD4EngineTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("MD4EngineTest"); + + CppUnit_addTest(pSuite, MD4EngineTest, testMD4); + + return pSuite; +} diff --git a/Foundation/testsuite/src/MD4EngineTest.h b/Foundation/testsuite/src/MD4EngineTest.h index 4941725ea..da0e43c20 100644 --- a/Foundation/testsuite/src/MD4EngineTest.h +++ b/Foundation/testsuite/src/MD4EngineTest.h @@ -1,60 +1,60 @@ -// -// MD4EngineTest.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/MD4EngineTest.h#1 $ -// -// Definition of the MD4EngineTest class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 MD4EngineTest_INCLUDED -#define MD4EngineTest_INCLUDED - - -#include "Poco/Foundation.h" -#include "CppUnit/TestCase.h" - - -class MD4EngineTest: public CppUnit::TestCase -{ -public: - MD4EngineTest(const std::string& name); - ~MD4EngineTest(); - - void testMD4(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // MD4EngineTest_INCLUDED +// +// MD4EngineTest.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/MD4EngineTest.h#1 $ +// +// Definition of the MD4EngineTest class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 MD4EngineTest_INCLUDED +#define MD4EngineTest_INCLUDED + + +#include "Poco/Foundation.h" +#include "CppUnit/TestCase.h" + + +class MD4EngineTest: public CppUnit::TestCase +{ +public: + MD4EngineTest(const std::string& name); + ~MD4EngineTest(); + + void testMD4(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // MD4EngineTest_INCLUDED diff --git a/Foundation/testsuite/src/MD5EngineTest.cpp b/Foundation/testsuite/src/MD5EngineTest.cpp index 5d3f74b67..8b5197dfa 100644 --- a/Foundation/testsuite/src/MD5EngineTest.cpp +++ b/Foundation/testsuite/src/MD5EngineTest.cpp @@ -1,100 +1,100 @@ -// -// MD5EngineTest.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/MD5EngineTest.cpp#1 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "MD5EngineTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/MD5Engine.h" - - -using Poco::MD5Engine; -using Poco::DigestEngine; - - -MD5EngineTest::MD5EngineTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -MD5EngineTest::~MD5EngineTest() -{ -} - - -void MD5EngineTest::testMD5() -{ - MD5Engine engine; - - // test vectors from RFC 1321 - - engine.update(""); - assert (DigestEngine::digestToHex(engine.digest()) == "d41d8cd98f00b204e9800998ecf8427e"); - - engine.update("a"); - assert (DigestEngine::digestToHex(engine.digest()) == "0cc175b9c0f1b6a831c399e269772661"); - - engine.update("abc"); - assert (DigestEngine::digestToHex(engine.digest()) == "900150983cd24fb0d6963f7d28e17f72"); - - engine.update("message digest"); - assert (DigestEngine::digestToHex(engine.digest()) == "f96b697d7cb7938d525a2f31aaf161d0"); - - engine.update("abcdefghijklmnopqrstuvwxyz"); - assert (DigestEngine::digestToHex(engine.digest()) == "c3fcd3d76192e4007dfb496cca67e13b"); - - engine.update("ABCDEFGHIJKLMNOPQRSTUVWXYZ"); - engine.update("abcdefghijklmnopqrstuvwxyz0123456789"); - assert (DigestEngine::digestToHex(engine.digest()) == "d174ab98d277d9f5a5611c2c9f419d9f"); - - engine.update("12345678901234567890123456789012345678901234567890123456789012345678901234567890"); - assert (DigestEngine::digestToHex(engine.digest()) == "57edf4a22be3c955ac49da2e2107b67a"); -} - - -void MD5EngineTest::setUp() -{ -} - - -void MD5EngineTest::tearDown() -{ -} - - -CppUnit::Test* MD5EngineTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("MD5EngineTest"); - - CppUnit_addTest(pSuite, MD5EngineTest, testMD5); - - return pSuite; -} +// +// MD5EngineTest.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/MD5EngineTest.cpp#1 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "MD5EngineTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/MD5Engine.h" + + +using Poco::MD5Engine; +using Poco::DigestEngine; + + +MD5EngineTest::MD5EngineTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +MD5EngineTest::~MD5EngineTest() +{ +} + + +void MD5EngineTest::testMD5() +{ + MD5Engine engine; + + // test vectors from RFC 1321 + + engine.update(""); + assert (DigestEngine::digestToHex(engine.digest()) == "d41d8cd98f00b204e9800998ecf8427e"); + + engine.update("a"); + assert (DigestEngine::digestToHex(engine.digest()) == "0cc175b9c0f1b6a831c399e269772661"); + + engine.update("abc"); + assert (DigestEngine::digestToHex(engine.digest()) == "900150983cd24fb0d6963f7d28e17f72"); + + engine.update("message digest"); + assert (DigestEngine::digestToHex(engine.digest()) == "f96b697d7cb7938d525a2f31aaf161d0"); + + engine.update("abcdefghijklmnopqrstuvwxyz"); + assert (DigestEngine::digestToHex(engine.digest()) == "c3fcd3d76192e4007dfb496cca67e13b"); + + engine.update("ABCDEFGHIJKLMNOPQRSTUVWXYZ"); + engine.update("abcdefghijklmnopqrstuvwxyz0123456789"); + assert (DigestEngine::digestToHex(engine.digest()) == "d174ab98d277d9f5a5611c2c9f419d9f"); + + engine.update("12345678901234567890123456789012345678901234567890123456789012345678901234567890"); + assert (DigestEngine::digestToHex(engine.digest()) == "57edf4a22be3c955ac49da2e2107b67a"); +} + + +void MD5EngineTest::setUp() +{ +} + + +void MD5EngineTest::tearDown() +{ +} + + +CppUnit::Test* MD5EngineTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("MD5EngineTest"); + + CppUnit_addTest(pSuite, MD5EngineTest, testMD5); + + return pSuite; +} diff --git a/Foundation/testsuite/src/MD5EngineTest.h b/Foundation/testsuite/src/MD5EngineTest.h index c07db526c..f67ebf5bb 100644 --- a/Foundation/testsuite/src/MD5EngineTest.h +++ b/Foundation/testsuite/src/MD5EngineTest.h @@ -1,60 +1,60 @@ -// -// MD5EngineTest.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/MD5EngineTest.h#1 $ -// -// Definition of the MD5EngineTest class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 MD5EngineTest_INCLUDED -#define MD5EngineTest_INCLUDED - - -#include "Poco/Foundation.h" -#include "CppUnit/TestCase.h" - - -class MD5EngineTest: public CppUnit::TestCase -{ -public: - MD5EngineTest(const std::string& name); - ~MD5EngineTest(); - - void testMD5(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // MD5EngineTest_INCLUDED +// +// MD5EngineTest.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/MD5EngineTest.h#1 $ +// +// Definition of the MD5EngineTest class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 MD5EngineTest_INCLUDED +#define MD5EngineTest_INCLUDED + + +#include "Poco/Foundation.h" +#include "CppUnit/TestCase.h" + + +class MD5EngineTest: public CppUnit::TestCase +{ +public: + MD5EngineTest(const std::string& name); + ~MD5EngineTest(); + + void testMD5(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // MD5EngineTest_INCLUDED diff --git a/Foundation/testsuite/src/ManifestTest.cpp b/Foundation/testsuite/src/ManifestTest.cpp index 3c57174c0..f48cea655 100644 --- a/Foundation/testsuite/src/ManifestTest.cpp +++ b/Foundation/testsuite/src/ManifestTest.cpp @@ -1,136 +1,136 @@ -// -// ManifestTest.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/ManifestTest.cpp#1 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "ManifestTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/Manifest.h" -#include "Poco/MetaObject.h" -#include - - -using Poco::Manifest; -using Poco::MetaObject; - - -class MfTestBase -{ -}; - - -class MfTestObject: public MfTestBase -{ -}; - - -ManifestTest::ManifestTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -ManifestTest::~ManifestTest() -{ -} - - -void ManifestTest::testManifest() -{ - Manifest manifest; - assert (manifest.empty()); - assert (manifest.size() == 0); - assert (manifest.insert(new MetaObject("MfTestObject1"))); - assert (!manifest.empty()); - assert (manifest.size() == 1); - assert (manifest.insert(new MetaObject("MfTestObject2"))); - MetaObject* pMeta = new MetaObject("MfTestObject2"); - assert (!manifest.insert(pMeta)); - delete pMeta; - assert (!manifest.empty()); - assert (manifest.size() == 2); - assert (manifest.insert(new MetaObject("MfTestObject3"))); - assert (manifest.size() == 3); - - assert (manifest.find("MfTestObject1") != manifest.end()); - assert (manifest.find("MfTestObject2") != manifest.end()); - assert (manifest.find("MfTestObject3") != manifest.end()); - assert (manifest.find("MfTestObject4") == manifest.end()); - - std::set classes; - - Manifest::Iterator it = manifest.begin(); - assert (it != manifest.end()); - classes.insert(it->name()); - ++it; - assert (it != manifest.end()); - classes.insert(it->name()); - ++it; - assert (it != manifest.end()); - classes.insert(it->name()); - it++; - assert (it == manifest.end()); - - assert (classes.find("MfTestObject1") != classes.end()); - assert (classes.find("MfTestObject2") != classes.end()); - assert (classes.find("MfTestObject3") != classes.end()); - - manifest.clear(); - assert (manifest.empty()); - assert (manifest.size() == 0); - assert (manifest.insert(new MetaObject("MfTestObject4"))); - assert (!manifest.empty()); - assert (manifest.size() == 1); - it = manifest.begin(); - assert (it != manifest.end()); - assert (std::string(it->name()) == "MfTestObject4"); - ++it; - assert (it == manifest.end()); -} - - -void ManifestTest::setUp() -{ -} - - -void ManifestTest::tearDown() -{ -} - - -CppUnit::Test* ManifestTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("ManifestTest"); - - CppUnit_addTest(pSuite, ManifestTest, testManifest); - - return pSuite; -} +// +// ManifestTest.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/ManifestTest.cpp#1 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "ManifestTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/Manifest.h" +#include "Poco/MetaObject.h" +#include + + +using Poco::Manifest; +using Poco::MetaObject; + + +class MfTestBase +{ +}; + + +class MfTestObject: public MfTestBase +{ +}; + + +ManifestTest::ManifestTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +ManifestTest::~ManifestTest() +{ +} + + +void ManifestTest::testManifest() +{ + Manifest manifest; + assert (manifest.empty()); + assert (manifest.size() == 0); + assert (manifest.insert(new MetaObject("MfTestObject1"))); + assert (!manifest.empty()); + assert (manifest.size() == 1); + assert (manifest.insert(new MetaObject("MfTestObject2"))); + MetaObject* pMeta = new MetaObject("MfTestObject2"); + assert (!manifest.insert(pMeta)); + delete pMeta; + assert (!manifest.empty()); + assert (manifest.size() == 2); + assert (manifest.insert(new MetaObject("MfTestObject3"))); + assert (manifest.size() == 3); + + assert (manifest.find("MfTestObject1") != manifest.end()); + assert (manifest.find("MfTestObject2") != manifest.end()); + assert (manifest.find("MfTestObject3") != manifest.end()); + assert (manifest.find("MfTestObject4") == manifest.end()); + + std::set classes; + + Manifest::Iterator it = manifest.begin(); + assert (it != manifest.end()); + classes.insert(it->name()); + ++it; + assert (it != manifest.end()); + classes.insert(it->name()); + ++it; + assert (it != manifest.end()); + classes.insert(it->name()); + it++; + assert (it == manifest.end()); + + assert (classes.find("MfTestObject1") != classes.end()); + assert (classes.find("MfTestObject2") != classes.end()); + assert (classes.find("MfTestObject3") != classes.end()); + + manifest.clear(); + assert (manifest.empty()); + assert (manifest.size() == 0); + assert (manifest.insert(new MetaObject("MfTestObject4"))); + assert (!manifest.empty()); + assert (manifest.size() == 1); + it = manifest.begin(); + assert (it != manifest.end()); + assert (std::string(it->name()) == "MfTestObject4"); + ++it; + assert (it == manifest.end()); +} + + +void ManifestTest::setUp() +{ +} + + +void ManifestTest::tearDown() +{ +} + + +CppUnit::Test* ManifestTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("ManifestTest"); + + CppUnit_addTest(pSuite, ManifestTest, testManifest); + + return pSuite; +} diff --git a/Foundation/testsuite/src/ManifestTest.h b/Foundation/testsuite/src/ManifestTest.h index e5aa2005e..756ed884a 100644 --- a/Foundation/testsuite/src/ManifestTest.h +++ b/Foundation/testsuite/src/ManifestTest.h @@ -1,60 +1,60 @@ -// -// ManifestTest.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/ManifestTest.h#1 $ -// -// Definition of the ManifestTest class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 ManifestTest_INCLUDED -#define ManifestTest_INCLUDED - - -#include "Poco/Foundation.h" -#include "CppUnit/TestCase.h" - - -class ManifestTest: public CppUnit::TestCase -{ -public: - ManifestTest(const std::string& name); - ~ManifestTest(); - - void testManifest(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // ManifestTest_INCLUDED +// +// ManifestTest.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/ManifestTest.h#1 $ +// +// Definition of the ManifestTest class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 ManifestTest_INCLUDED +#define ManifestTest_INCLUDED + + +#include "Poco/Foundation.h" +#include "CppUnit/TestCase.h" + + +class ManifestTest: public CppUnit::TestCase +{ +public: + ManifestTest(const std::string& name); + ~ManifestTest(); + + void testManifest(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // ManifestTest_INCLUDED diff --git a/Foundation/testsuite/src/MemoryPoolTest.cpp b/Foundation/testsuite/src/MemoryPoolTest.cpp index 3a3d1a899..be43c56bd 100644 --- a/Foundation/testsuite/src/MemoryPoolTest.cpp +++ b/Foundation/testsuite/src/MemoryPoolTest.cpp @@ -1,110 +1,110 @@ -// -// MemoryPoolTest.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/MemoryPoolTest.cpp#1 $ -// -// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "MemoryPoolTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/MemoryPool.h" -#include - - -using Poco::MemoryPool; - - -MemoryPoolTest::MemoryPoolTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -MemoryPoolTest::~MemoryPoolTest() -{ -} - - -void MemoryPoolTest::testMemoryPool() -{ - MemoryPool pool1(100, 0, 10); - - assert (pool1.blockSize() == 100); - assert (pool1.allocated() == 0); - assert (pool1.available() == 0); - - std::vector ptrs; - for (int i = 0; i < 10; ++i) - { - ptrs.push_back(pool1.get()); - assert (pool1.allocated() == i + 1); - assert (pool1.available() == 0); - } - - try - { - pool1.get(); - fail("pool exhausted - must throw exception"); - } - catch (Poco::OutOfMemoryException&) - { - } - - int av = 0; - for (std::vector::iterator it = ptrs.begin(); it != ptrs.end(); ++it) - { - pool1.release(*it); - ++av; - assert (pool1.available() == av); - } - - MemoryPool pool2(32, 5, 10); - assert (pool2.available() == 5); - assert (pool2.blockSize() == 32); - assert (pool2.allocated() == 5); -} - - -void MemoryPoolTest::setUp() -{ -} - - -void MemoryPoolTest::tearDown() -{ -} - - -CppUnit::Test* MemoryPoolTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("MemoryPoolTest"); - - CppUnit_addTest(pSuite, MemoryPoolTest, testMemoryPool); - - return pSuite; -} +// +// MemoryPoolTest.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/MemoryPoolTest.cpp#1 $ +// +// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "MemoryPoolTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/MemoryPool.h" +#include + + +using Poco::MemoryPool; + + +MemoryPoolTest::MemoryPoolTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +MemoryPoolTest::~MemoryPoolTest() +{ +} + + +void MemoryPoolTest::testMemoryPool() +{ + MemoryPool pool1(100, 0, 10); + + assert (pool1.blockSize() == 100); + assert (pool1.allocated() == 0); + assert (pool1.available() == 0); + + std::vector ptrs; + for (int i = 0; i < 10; ++i) + { + ptrs.push_back(pool1.get()); + assert (pool1.allocated() == i + 1); + assert (pool1.available() == 0); + } + + try + { + pool1.get(); + fail("pool exhausted - must throw exception"); + } + catch (Poco::OutOfMemoryException&) + { + } + + int av = 0; + for (std::vector::iterator it = ptrs.begin(); it != ptrs.end(); ++it) + { + pool1.release(*it); + ++av; + assert (pool1.available() == av); + } + + MemoryPool pool2(32, 5, 10); + assert (pool2.available() == 5); + assert (pool2.blockSize() == 32); + assert (pool2.allocated() == 5); +} + + +void MemoryPoolTest::setUp() +{ +} + + +void MemoryPoolTest::tearDown() +{ +} + + +CppUnit::Test* MemoryPoolTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("MemoryPoolTest"); + + CppUnit_addTest(pSuite, MemoryPoolTest, testMemoryPool); + + return pSuite; +} diff --git a/Foundation/testsuite/src/MemoryPoolTest.h b/Foundation/testsuite/src/MemoryPoolTest.h index 30b1dfc3e..bed6a932c 100644 --- a/Foundation/testsuite/src/MemoryPoolTest.h +++ b/Foundation/testsuite/src/MemoryPoolTest.h @@ -1,60 +1,60 @@ -// -// MemoryPoolTest.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/MemoryPoolTest.h#1 $ -// -// Definition of the MemoryPoolTest class. -// -// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 MemoryPoolTest_INCLUDED -#define MemoryPoolTest_INCLUDED - - -#include "Poco/Foundation.h" -#include "CppUnit/TestCase.h" - - -class MemoryPoolTest: public CppUnit::TestCase -{ -public: - MemoryPoolTest(const std::string& name); - ~MemoryPoolTest(); - - void testMemoryPool(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // MemoryPoolTest_INCLUDED +// +// MemoryPoolTest.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/MemoryPoolTest.h#1 $ +// +// Definition of the MemoryPoolTest class. +// +// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 MemoryPoolTest_INCLUDED +#define MemoryPoolTest_INCLUDED + + +#include "Poco/Foundation.h" +#include "CppUnit/TestCase.h" + + +class MemoryPoolTest: public CppUnit::TestCase +{ +public: + MemoryPoolTest(const std::string& name); + ~MemoryPoolTest(); + + void testMemoryPool(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // MemoryPoolTest_INCLUDED diff --git a/Foundation/testsuite/src/NDCTest.cpp b/Foundation/testsuite/src/NDCTest.cpp index eb0a8c5bd..0ef05d228 100644 --- a/Foundation/testsuite/src/NDCTest.cpp +++ b/Foundation/testsuite/src/NDCTest.cpp @@ -1,107 +1,107 @@ -// -// NDCTest.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/NDCTest.cpp#1 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "NDCTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/NestedDiagnosticContext.h" -#include - - -using Poco::NDC; - - -NDCTest::NDCTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -NDCTest::~NDCTest() -{ -} - - -void NDCTest::testNDC() -{ - NDC ndc; - assert (ndc.depth() == 0); - ndc.push("item1"); - assert (ndc.toString() == "item1"); - assert (ndc.depth() == 1); - ndc.push("item2"); - assert (ndc.toString() == "item1:item2"); - assert (ndc.depth() == 2); - ndc.pop(); - assert (ndc.depth() == 1); - assert (ndc.toString() == "item1"); - ndc.pop(); - assert (ndc.depth() == 0); -} - - -void NDCTest::testNDCScope() -{ - poco_ndc("item1"); - assert (NDC::current().depth() == 1); - { - poco_ndc("item2"); - assert (NDC::current().depth() == 2); - { - poco_ndc("item3"); - assert (NDC::current().depth() == 3); - NDC::current().dump(std::cout); - } - assert (NDC::current().depth() == 2); - } - assert (NDC::current().depth() == 1); -} - - -void NDCTest::setUp() -{ -} - - -void NDCTest::tearDown() -{ -} - - -CppUnit::Test* NDCTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("NDCTest"); - - CppUnit_addTest(pSuite, NDCTest, testNDC); - CppUnit_addTest(pSuite, NDCTest, testNDCScope); - - return pSuite; -} +// +// NDCTest.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/NDCTest.cpp#1 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "NDCTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/NestedDiagnosticContext.h" +#include + + +using Poco::NDC; + + +NDCTest::NDCTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +NDCTest::~NDCTest() +{ +} + + +void NDCTest::testNDC() +{ + NDC ndc; + assert (ndc.depth() == 0); + ndc.push("item1"); + assert (ndc.toString() == "item1"); + assert (ndc.depth() == 1); + ndc.push("item2"); + assert (ndc.toString() == "item1:item2"); + assert (ndc.depth() == 2); + ndc.pop(); + assert (ndc.depth() == 1); + assert (ndc.toString() == "item1"); + ndc.pop(); + assert (ndc.depth() == 0); +} + + +void NDCTest::testNDCScope() +{ + poco_ndc("item1"); + assert (NDC::current().depth() == 1); + { + poco_ndc("item2"); + assert (NDC::current().depth() == 2); + { + poco_ndc("item3"); + assert (NDC::current().depth() == 3); + NDC::current().dump(std::cout); + } + assert (NDC::current().depth() == 2); + } + assert (NDC::current().depth() == 1); +} + + +void NDCTest::setUp() +{ +} + + +void NDCTest::tearDown() +{ +} + + +CppUnit::Test* NDCTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("NDCTest"); + + CppUnit_addTest(pSuite, NDCTest, testNDC); + CppUnit_addTest(pSuite, NDCTest, testNDCScope); + + return pSuite; +} diff --git a/Foundation/testsuite/src/NDCTest.h b/Foundation/testsuite/src/NDCTest.h index c95e2de2c..d21e83130 100644 --- a/Foundation/testsuite/src/NDCTest.h +++ b/Foundation/testsuite/src/NDCTest.h @@ -1,61 +1,61 @@ -// -// NDCTest.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/NDCTest.h#1 $ -// -// Definition of the NDCTest class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 NDCTest_INCLUDED -#define NDCTest_INCLUDED - - -#include "Poco/Foundation.h" -#include "CppUnit/TestCase.h" - - -class NDCTest: public CppUnit::TestCase -{ -public: - NDCTest(const std::string& name); - ~NDCTest(); - - void testNDC(); - void testNDCScope(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // NDCTest_INCLUDED +// +// NDCTest.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/NDCTest.h#1 $ +// +// Definition of the NDCTest class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 NDCTest_INCLUDED +#define NDCTest_INCLUDED + + +#include "Poco/Foundation.h" +#include "CppUnit/TestCase.h" + + +class NDCTest: public CppUnit::TestCase +{ +public: + NDCTest(const std::string& name); + ~NDCTest(); + + void testNDC(); + void testNDCScope(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // NDCTest_INCLUDED diff --git a/Foundation/testsuite/src/NamedEventTest.cpp b/Foundation/testsuite/src/NamedEventTest.cpp index 9fd8eb9bc..047fac692 100644 --- a/Foundation/testsuite/src/NamedEventTest.cpp +++ b/Foundation/testsuite/src/NamedEventTest.cpp @@ -1,122 +1,122 @@ -// -// NamedEventTest.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/NamedEventTest.cpp#1 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "NamedEventTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/NamedEvent.h" -#include "Poco/Thread.h" -#include "Poco/Runnable.h" -#include "Poco/Timestamp.h" - - -using Poco::NamedEvent; -using Poco::Thread; -using Poco::Runnable; -using Poco::Timestamp; - - -static NamedEvent testEvent("TestEvent"); - - -namespace -{ - class TestEvent: public Runnable - { - public: - void run() - { - - testEvent.wait(); - _timestamp.update(); - } - - const Timestamp& timestamp() const - { - return _timestamp; - } - - private: - Timestamp _timestamp; - }; -} - - -NamedEventTest::NamedEventTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -NamedEventTest::~NamedEventTest() -{ -} - - -void NamedEventTest::testNamedEvent() -{ - Thread thr1; - TestEvent te; - thr1.start(te); - Timestamp now; - Thread::sleep(2000); - testEvent.set(); - thr1.join(); - assert (te.timestamp() > now); - - Thread thr2; - thr2.start(te); - now.update(); - Thread::sleep(2000); - testEvent.set(); - thr2.join(); - assert (te.timestamp() > now); -} - - -void NamedEventTest::setUp() -{ -} - - -void NamedEventTest::tearDown() -{ -} - - -CppUnit::Test* NamedEventTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("NamedEventTest"); - - CppUnit_addTest(pSuite, NamedEventTest, testNamedEvent); - - return pSuite; -} +// +// NamedEventTest.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/NamedEventTest.cpp#1 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "NamedEventTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/NamedEvent.h" +#include "Poco/Thread.h" +#include "Poco/Runnable.h" +#include "Poco/Timestamp.h" + + +using Poco::NamedEvent; +using Poco::Thread; +using Poco::Runnable; +using Poco::Timestamp; + + +static NamedEvent testEvent("TestEvent"); + + +namespace +{ + class TestEvent: public Runnable + { + public: + void run() + { + + testEvent.wait(); + _timestamp.update(); + } + + const Timestamp& timestamp() const + { + return _timestamp; + } + + private: + Timestamp _timestamp; + }; +} + + +NamedEventTest::NamedEventTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +NamedEventTest::~NamedEventTest() +{ +} + + +void NamedEventTest::testNamedEvent() +{ + Thread thr1; + TestEvent te; + thr1.start(te); + Timestamp now; + Thread::sleep(2000); + testEvent.set(); + thr1.join(); + assert (te.timestamp() > now); + + Thread thr2; + thr2.start(te); + now.update(); + Thread::sleep(2000); + testEvent.set(); + thr2.join(); + assert (te.timestamp() > now); +} + + +void NamedEventTest::setUp() +{ +} + + +void NamedEventTest::tearDown() +{ +} + + +CppUnit::Test* NamedEventTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("NamedEventTest"); + + CppUnit_addTest(pSuite, NamedEventTest, testNamedEvent); + + return pSuite; +} diff --git a/Foundation/testsuite/src/NamedEventTest.h b/Foundation/testsuite/src/NamedEventTest.h index 85468426a..d358f9eb1 100644 --- a/Foundation/testsuite/src/NamedEventTest.h +++ b/Foundation/testsuite/src/NamedEventTest.h @@ -1,60 +1,60 @@ -// -// NamedEventTest.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/NamedEventTest.h#1 $ -// -// Definition of the NamedEventTest class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 NamedEventTest_INCLUDED -#define NamedEventTest_INCLUDED - - -#include "Poco/Foundation.h" -#include "CppUnit/TestCase.h" - - -class NamedEventTest: public CppUnit::TestCase -{ -public: - NamedEventTest(const std::string& name); - ~NamedEventTest(); - - void testNamedEvent(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // NamedEventTest_INCLUDED +// +// NamedEventTest.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/NamedEventTest.h#1 $ +// +// Definition of the NamedEventTest class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 NamedEventTest_INCLUDED +#define NamedEventTest_INCLUDED + + +#include "Poco/Foundation.h" +#include "CppUnit/TestCase.h" + + +class NamedEventTest: public CppUnit::TestCase +{ +public: + NamedEventTest(const std::string& name); + ~NamedEventTest(); + + void testNamedEvent(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // NamedEventTest_INCLUDED diff --git a/Foundation/testsuite/src/NamedMutexTest.cpp b/Foundation/testsuite/src/NamedMutexTest.cpp index 950c3b34a..0bd6b82f8 100644 --- a/Foundation/testsuite/src/NamedMutexTest.cpp +++ b/Foundation/testsuite/src/NamedMutexTest.cpp @@ -1,160 +1,160 @@ -// -// NamedMutexTest.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/NamedMutexTest.cpp#1 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "NamedMutexTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/NamedMutex.h" -#include "Poco/Thread.h" -#include "Poco/Runnable.h" -#include "Poco/Timestamp.h" - - -using Poco::NamedMutex; -using Poco::Thread; -using Poco::Runnable; -using Poco::Timestamp; - - -static NamedMutex testMutex("TestMutex"); - - -namespace -{ - class TestLock: public Runnable - { - public: - void run() - { - - testMutex.lock(); - _timestamp.update(); - testMutex.unlock(); - } - - const Timestamp& timestamp() const - { - return _timestamp; - } - - private: - Timestamp _timestamp; - }; - - class TestTryLock: public Runnable - { - public: - TestTryLock(): _locked(false) - { - } - - void run() - { - if (testMutex.tryLock()) - { - _locked = true; - testMutex.unlock(); - } - } - - bool locked() const - { - return _locked; - } - - private: - bool _locked; - }; -} - - -NamedMutexTest::NamedMutexTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -NamedMutexTest::~NamedMutexTest() -{ -} - - -void NamedMutexTest::testLock() -{ - testMutex.lock(); - Thread thr; - TestLock tl; - thr.start(tl); - Timestamp now; - Thread::sleep(2000); - testMutex.unlock(); - thr.join(); - assert (tl.timestamp() > now); -} - - -void NamedMutexTest::testTryLock() -{ - Thread thr1; - TestTryLock ttl1; - thr1.start(ttl1); - thr1.join(); - assert (ttl1.locked()); - - testMutex.lock(); - Thread thr2; - TestTryLock ttl2; - thr2.start(ttl2); - thr2.join(); - testMutex.unlock(); - assert (!ttl2.locked()); -} - - -void NamedMutexTest::setUp() -{ -} - - -void NamedMutexTest::tearDown() -{ -} - - -CppUnit::Test* NamedMutexTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("NamedMutexTest"); - - CppUnit_addTest(pSuite, NamedMutexTest, testLock); - CppUnit_addTest(pSuite, NamedMutexTest, testTryLock); - - return pSuite; -} +// +// NamedMutexTest.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/NamedMutexTest.cpp#1 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "NamedMutexTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/NamedMutex.h" +#include "Poco/Thread.h" +#include "Poco/Runnable.h" +#include "Poco/Timestamp.h" + + +using Poco::NamedMutex; +using Poco::Thread; +using Poco::Runnable; +using Poco::Timestamp; + + +static NamedMutex testMutex("TestMutex"); + + +namespace +{ + class TestLock: public Runnable + { + public: + void run() + { + + testMutex.lock(); + _timestamp.update(); + testMutex.unlock(); + } + + const Timestamp& timestamp() const + { + return _timestamp; + } + + private: + Timestamp _timestamp; + }; + + class TestTryLock: public Runnable + { + public: + TestTryLock(): _locked(false) + { + } + + void run() + { + if (testMutex.tryLock()) + { + _locked = true; + testMutex.unlock(); + } + } + + bool locked() const + { + return _locked; + } + + private: + bool _locked; + }; +} + + +NamedMutexTest::NamedMutexTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +NamedMutexTest::~NamedMutexTest() +{ +} + + +void NamedMutexTest::testLock() +{ + testMutex.lock(); + Thread thr; + TestLock tl; + thr.start(tl); + Timestamp now; + Thread::sleep(2000); + testMutex.unlock(); + thr.join(); + assert (tl.timestamp() > now); +} + + +void NamedMutexTest::testTryLock() +{ + Thread thr1; + TestTryLock ttl1; + thr1.start(ttl1); + thr1.join(); + assert (ttl1.locked()); + + testMutex.lock(); + Thread thr2; + TestTryLock ttl2; + thr2.start(ttl2); + thr2.join(); + testMutex.unlock(); + assert (!ttl2.locked()); +} + + +void NamedMutexTest::setUp() +{ +} + + +void NamedMutexTest::tearDown() +{ +} + + +CppUnit::Test* NamedMutexTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("NamedMutexTest"); + + CppUnit_addTest(pSuite, NamedMutexTest, testLock); + CppUnit_addTest(pSuite, NamedMutexTest, testTryLock); + + return pSuite; +} diff --git a/Foundation/testsuite/src/NamedMutexTest.h b/Foundation/testsuite/src/NamedMutexTest.h index e9c9638c2..03763e33c 100644 --- a/Foundation/testsuite/src/NamedMutexTest.h +++ b/Foundation/testsuite/src/NamedMutexTest.h @@ -1,61 +1,61 @@ -// -// NamedMutexTest.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/NamedMutexTest.h#1 $ -// -// Definition of the NamedMutexTest class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 NamedMutexTest_INCLUDED -#define NamedMutexTest_INCLUDED - - -#include "Poco/Foundation.h" -#include "CppUnit/TestCase.h" - - -class NamedMutexTest: public CppUnit::TestCase -{ -public: - NamedMutexTest(const std::string& name); - ~NamedMutexTest(); - - void testLock(); - void testTryLock(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // NamedMutexTest_INCLUDED +// +// NamedMutexTest.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/NamedMutexTest.h#1 $ +// +// Definition of the NamedMutexTest class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 NamedMutexTest_INCLUDED +#define NamedMutexTest_INCLUDED + + +#include "Poco/Foundation.h" +#include "CppUnit/TestCase.h" + + +class NamedMutexTest: public CppUnit::TestCase +{ +public: + NamedMutexTest(const std::string& name); + ~NamedMutexTest(); + + void testLock(); + void testTryLock(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // NamedMutexTest_INCLUDED diff --git a/Foundation/testsuite/src/NotificationCenterTest.cpp b/Foundation/testsuite/src/NotificationCenterTest.cpp index a47e5dac6..6217e300b 100644 --- a/Foundation/testsuite/src/NotificationCenterTest.cpp +++ b/Foundation/testsuite/src/NotificationCenterTest.cpp @@ -1,220 +1,220 @@ -// -// NotificationCenterTest.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/NotificationCenterTest.cpp#2 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "NotificationCenterTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/NotificationCenter.h" -#include "Poco/Observer.h" -#include "Poco/NObserver.h" -#include "Poco/AutoPtr.h" - - -using Poco::NotificationCenter; -using Poco::Observer; -using Poco::NObserver; -using Poco::Notification; -using Poco::AutoPtr; - - -class TestNotification: public Notification -{ -}; - - -NotificationCenterTest::NotificationCenterTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -NotificationCenterTest::~NotificationCenterTest() -{ -} - - -void NotificationCenterTest::test1() -{ - NotificationCenter nc; - nc.postNotification(new Notification); -} - - -void NotificationCenterTest::test2() -{ - NotificationCenter nc; - nc.addObserver(Observer(*this, &NotificationCenterTest::handle1)); - nc.postNotification(new Notification); - assert (_set.size() == 1); - assert (_set.find("handle1") != _set.end()); - nc.removeObserver(Observer(*this, &NotificationCenterTest::handle1)); -} - - -void NotificationCenterTest::test3() -{ - NotificationCenter nc; - nc.addObserver(Observer(*this, &NotificationCenterTest::handle1)); - nc.addObserver(Observer(*this, &NotificationCenterTest::handle2)); - nc.postNotification(new Notification); - assert (_set.size() == 2); - assert (_set.find("handle1") != _set.end()); - assert (_set.find("handle2") != _set.end()); - nc.removeObserver(Observer(*this, &NotificationCenterTest::handle1)); - nc.removeObserver(Observer(*this, &NotificationCenterTest::handle2)); -} - - -void NotificationCenterTest::test4() -{ - NotificationCenter nc; - nc.addObserver(Observer(*this, &NotificationCenterTest::handle1)); - nc.addObserver(Observer(*this, &NotificationCenterTest::handle2)); - nc.postNotification(new Notification); - assert (_set.size() == 2); - assert (_set.find("handle1") != _set.end()); - assert (_set.find("handle2") != _set.end()); - nc.removeObserver(Observer(*this, &NotificationCenterTest::handle1)); - nc.removeObserver(Observer(*this, &NotificationCenterTest::handle2)); - _set.clear(); - nc.postNotification(new Notification); - assert (_set.empty()); - nc.addObserver(Observer(*this, &NotificationCenterTest::handle3)); - nc.postNotification(new Notification); - assert (_set.size() == 1); - assert (_set.find("handle3") != _set.end()); - nc.removeObserver(Observer(*this, &NotificationCenterTest::handle3)); -} - - -void NotificationCenterTest::test5() -{ - NotificationCenter nc; - nc.addObserver(Observer(*this, &NotificationCenterTest::handle1)); - nc.addObserver(Observer(*this, &NotificationCenterTest::handleTest)); - nc.postNotification(new Notification); - assert (_set.size() == 1); - assert (_set.find("handle1") != _set.end()); - _set.clear(); - nc.postNotification(new TestNotification); - assert (_set.size() == 2); - assert (_set.find("handle1") != _set.end()); - assert (_set.find("handleTest") != _set.end()); - nc.removeObserver(Observer(*this, &NotificationCenterTest::handle1)); - nc.removeObserver(Observer(*this, &NotificationCenterTest::handleTest)); -} - - -void NotificationCenterTest::testAuto() -{ - NotificationCenter nc; - nc.addObserver(NObserver(*this, &NotificationCenterTest::handleAuto)); - nc.postNotification(new Notification); - assert (_set.size() == 1); - assert (_set.find("handleAuto") != _set.end()); - nc.removeObserver(NObserver(*this, &NotificationCenterTest::handleAuto)); -} - - -void NotificationCenterTest::testDefaultCenter() -{ - NotificationCenter& nc = NotificationCenter::defaultCenter(); - nc.addObserver(Observer(*this, &NotificationCenterTest::handle1)); - nc.postNotification(new Notification); - assert (_set.size() == 1); - assert (_set.find("handle1") != _set.end()); - nc.removeObserver(Observer(*this, &NotificationCenterTest::handle1)); -} - - -void NotificationCenterTest::handle1(Poco::Notification* pNf) -{ - poco_check_ptr (pNf); - AutoPtr nf = pNf; - _set.insert("handle1"); -} - - -void NotificationCenterTest::handle2(Poco::Notification* pNf) -{ - poco_check_ptr (pNf); - AutoPtr nf = pNf; - _set.insert("handle2"); -} - - -void NotificationCenterTest::handle3(Poco::Notification* pNf) -{ - poco_check_ptr (pNf); - AutoPtr nf = pNf; - _set.insert("handle3"); -} - - -void NotificationCenterTest::handleTest(TestNotification* pNf) -{ - poco_check_ptr (pNf); - AutoPtr nf = pNf; - _set.insert("handleTest"); -} - - -void NotificationCenterTest::handleAuto(const AutoPtr& pNf) -{ - _set.insert("handleAuto"); -} - - -void NotificationCenterTest::setUp() -{ - _set.clear(); -} - - -void NotificationCenterTest::tearDown() -{ -} - - -CppUnit::Test* NotificationCenterTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("NotificationCenterTest"); - - CppUnit_addTest(pSuite, NotificationCenterTest, test1); - CppUnit_addTest(pSuite, NotificationCenterTest, test2); - CppUnit_addTest(pSuite, NotificationCenterTest, test3); - CppUnit_addTest(pSuite, NotificationCenterTest, test4); - CppUnit_addTest(pSuite, NotificationCenterTest, test5); - CppUnit_addTest(pSuite, NotificationCenterTest, testAuto); - CppUnit_addTest(pSuite, NotificationCenterTest, testDefaultCenter); - - return pSuite; -} +// +// NotificationCenterTest.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/NotificationCenterTest.cpp#2 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "NotificationCenterTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/NotificationCenter.h" +#include "Poco/Observer.h" +#include "Poco/NObserver.h" +#include "Poco/AutoPtr.h" + + +using Poco::NotificationCenter; +using Poco::Observer; +using Poco::NObserver; +using Poco::Notification; +using Poco::AutoPtr; + + +class TestNotification: public Notification +{ +}; + + +NotificationCenterTest::NotificationCenterTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +NotificationCenterTest::~NotificationCenterTest() +{ +} + + +void NotificationCenterTest::test1() +{ + NotificationCenter nc; + nc.postNotification(new Notification); +} + + +void NotificationCenterTest::test2() +{ + NotificationCenter nc; + nc.addObserver(Observer(*this, &NotificationCenterTest::handle1)); + nc.postNotification(new Notification); + assert (_set.size() == 1); + assert (_set.find("handle1") != _set.end()); + nc.removeObserver(Observer(*this, &NotificationCenterTest::handle1)); +} + + +void NotificationCenterTest::test3() +{ + NotificationCenter nc; + nc.addObserver(Observer(*this, &NotificationCenterTest::handle1)); + nc.addObserver(Observer(*this, &NotificationCenterTest::handle2)); + nc.postNotification(new Notification); + assert (_set.size() == 2); + assert (_set.find("handle1") != _set.end()); + assert (_set.find("handle2") != _set.end()); + nc.removeObserver(Observer(*this, &NotificationCenterTest::handle1)); + nc.removeObserver(Observer(*this, &NotificationCenterTest::handle2)); +} + + +void NotificationCenterTest::test4() +{ + NotificationCenter nc; + nc.addObserver(Observer(*this, &NotificationCenterTest::handle1)); + nc.addObserver(Observer(*this, &NotificationCenterTest::handle2)); + nc.postNotification(new Notification); + assert (_set.size() == 2); + assert (_set.find("handle1") != _set.end()); + assert (_set.find("handle2") != _set.end()); + nc.removeObserver(Observer(*this, &NotificationCenterTest::handle1)); + nc.removeObserver(Observer(*this, &NotificationCenterTest::handle2)); + _set.clear(); + nc.postNotification(new Notification); + assert (_set.empty()); + nc.addObserver(Observer(*this, &NotificationCenterTest::handle3)); + nc.postNotification(new Notification); + assert (_set.size() == 1); + assert (_set.find("handle3") != _set.end()); + nc.removeObserver(Observer(*this, &NotificationCenterTest::handle3)); +} + + +void NotificationCenterTest::test5() +{ + NotificationCenter nc; + nc.addObserver(Observer(*this, &NotificationCenterTest::handle1)); + nc.addObserver(Observer(*this, &NotificationCenterTest::handleTest)); + nc.postNotification(new Notification); + assert (_set.size() == 1); + assert (_set.find("handle1") != _set.end()); + _set.clear(); + nc.postNotification(new TestNotification); + assert (_set.size() == 2); + assert (_set.find("handle1") != _set.end()); + assert (_set.find("handleTest") != _set.end()); + nc.removeObserver(Observer(*this, &NotificationCenterTest::handle1)); + nc.removeObserver(Observer(*this, &NotificationCenterTest::handleTest)); +} + + +void NotificationCenterTest::testAuto() +{ + NotificationCenter nc; + nc.addObserver(NObserver(*this, &NotificationCenterTest::handleAuto)); + nc.postNotification(new Notification); + assert (_set.size() == 1); + assert (_set.find("handleAuto") != _set.end()); + nc.removeObserver(NObserver(*this, &NotificationCenterTest::handleAuto)); +} + + +void NotificationCenterTest::testDefaultCenter() +{ + NotificationCenter& nc = NotificationCenter::defaultCenter(); + nc.addObserver(Observer(*this, &NotificationCenterTest::handle1)); + nc.postNotification(new Notification); + assert (_set.size() == 1); + assert (_set.find("handle1") != _set.end()); + nc.removeObserver(Observer(*this, &NotificationCenterTest::handle1)); +} + + +void NotificationCenterTest::handle1(Poco::Notification* pNf) +{ + poco_check_ptr (pNf); + AutoPtr nf = pNf; + _set.insert("handle1"); +} + + +void NotificationCenterTest::handle2(Poco::Notification* pNf) +{ + poco_check_ptr (pNf); + AutoPtr nf = pNf; + _set.insert("handle2"); +} + + +void NotificationCenterTest::handle3(Poco::Notification* pNf) +{ + poco_check_ptr (pNf); + AutoPtr nf = pNf; + _set.insert("handle3"); +} + + +void NotificationCenterTest::handleTest(TestNotification* pNf) +{ + poco_check_ptr (pNf); + AutoPtr nf = pNf; + _set.insert("handleTest"); +} + + +void NotificationCenterTest::handleAuto(const AutoPtr& pNf) +{ + _set.insert("handleAuto"); +} + + +void NotificationCenterTest::setUp() +{ + _set.clear(); +} + + +void NotificationCenterTest::tearDown() +{ +} + + +CppUnit::Test* NotificationCenterTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("NotificationCenterTest"); + + CppUnit_addTest(pSuite, NotificationCenterTest, test1); + CppUnit_addTest(pSuite, NotificationCenterTest, test2); + CppUnit_addTest(pSuite, NotificationCenterTest, test3); + CppUnit_addTest(pSuite, NotificationCenterTest, test4); + CppUnit_addTest(pSuite, NotificationCenterTest, test5); + CppUnit_addTest(pSuite, NotificationCenterTest, testAuto); + CppUnit_addTest(pSuite, NotificationCenterTest, testDefaultCenter); + + return pSuite; +} diff --git a/Foundation/testsuite/src/NotificationCenterTest.h b/Foundation/testsuite/src/NotificationCenterTest.h index 933fb33a7..c2d15f602 100644 --- a/Foundation/testsuite/src/NotificationCenterTest.h +++ b/Foundation/testsuite/src/NotificationCenterTest.h @@ -1,80 +1,80 @@ -// -// NotificationCenterTest.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/NotificationCenterTest.h#2 $ -// -// Definition of the NotificationCenterTest class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 NotificationCenterTest_INCLUDED -#define NotificationCenterTest_INCLUDED - - -#include "Poco/Foundation.h" -#include "CppUnit/TestCase.h" -#include "Poco/Notification.h" -#include "Poco/AutoPtr.h" -#include - - -class TestNotification; - - -class NotificationCenterTest: public CppUnit::TestCase -{ -public: - NotificationCenterTest(const std::string& name); - ~NotificationCenterTest(); - - void test1(); - void test2(); - void test3(); - void test4(); - void test5(); - void testAuto(); - void testDefaultCenter(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -protected: - void handle1(Poco::Notification* pNf); - void handle2(Poco::Notification* pNf); - void handle3(Poco::Notification* pNf); - void handleTest(TestNotification* pNf); - void handleAuto(const Poco::AutoPtr& pNf); - -private: - std::set _set; -}; - - -#endif // NotificationCenterTest_INCLUDED +// +// NotificationCenterTest.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/NotificationCenterTest.h#2 $ +// +// Definition of the NotificationCenterTest class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 NotificationCenterTest_INCLUDED +#define NotificationCenterTest_INCLUDED + + +#include "Poco/Foundation.h" +#include "CppUnit/TestCase.h" +#include "Poco/Notification.h" +#include "Poco/AutoPtr.h" +#include + + +class TestNotification; + + +class NotificationCenterTest: public CppUnit::TestCase +{ +public: + NotificationCenterTest(const std::string& name); + ~NotificationCenterTest(); + + void test1(); + void test2(); + void test3(); + void test4(); + void test5(); + void testAuto(); + void testDefaultCenter(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +protected: + void handle1(Poco::Notification* pNf); + void handle2(Poco::Notification* pNf); + void handle3(Poco::Notification* pNf); + void handleTest(TestNotification* pNf); + void handleAuto(const Poco::AutoPtr& pNf); + +private: + std::set _set; +}; + + +#endif // NotificationCenterTest_INCLUDED diff --git a/Foundation/testsuite/src/NotificationQueueTest.cpp b/Foundation/testsuite/src/NotificationQueueTest.cpp index 5515ab9bc..2b6fa6551 100644 --- a/Foundation/testsuite/src/NotificationQueueTest.cpp +++ b/Foundation/testsuite/src/NotificationQueueTest.cpp @@ -1,245 +1,245 @@ -// -// NotificationQueueTest.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/NotificationQueueTest.cpp#1 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "NotificationQueueTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/NotificationQueue.h" -#include "Poco/Notification.h" -#include "Poco/Thread.h" -#include "Poco/Runnable.h" -#include "Poco/RunnableAdapter.h" - - -using Poco::NotificationQueue; -using Poco::Notification; -using Poco::Thread; -using Poco::RunnableAdapter; - - -class QTestNotification: public Notification -{ -public: - QTestNotification(const std::string& data): _data(data) - { - } - ~QTestNotification() - { - } - const std::string& data() const - { - return _data; - } - -private: - std::string _data; -}; - - -NotificationQueueTest::NotificationQueueTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -NotificationQueueTest::~NotificationQueueTest() -{ -} - - -void NotificationQueueTest::testQueueDequeue() -{ - NotificationQueue queue; - assert (queue.empty()); - assert (queue.size() == 0); - Notification* pNf = queue.dequeueNotification(); - assertNullPtr(pNf); - queue.enqueueNotification(new Notification); - assert (!queue.empty()); - assert (queue.size() == 1); - pNf = queue.dequeueNotification(); - assertNotNullPtr(pNf); - assert (queue.empty()); - assert (queue.size() == 0); - pNf->release(); - - queue.enqueueNotification(new QTestNotification("first")); - queue.enqueueNotification(new QTestNotification("second")); - assert (!queue.empty()); - assert (queue.size() == 2); - QTestNotification* pTNf = dynamic_cast(queue.dequeueNotification()); - assertNotNullPtr(pTNf); - assert (pTNf->data() == "first"); - pTNf->release(); - assert (!queue.empty()); - assert (queue.size() == 1); - pTNf = dynamic_cast(queue.dequeueNotification()); - assertNotNullPtr(pTNf); - assert (pTNf->data() == "second"); - pTNf->release(); - assert (queue.empty()); - assert (queue.size() == 0); - - pNf = queue.dequeueNotification(); - assertNullPtr(pNf); -} - - -void NotificationQueueTest::testQueueDequeueUrgent() -{ - NotificationQueue queue; - queue.enqueueNotification(new QTestNotification("first")); - queue.enqueueNotification(new QTestNotification("second")); - queue.enqueueUrgentNotification(new QTestNotification("third")); - assert (!queue.empty()); - assert (queue.size() == 3); - QTestNotification* pTNf = dynamic_cast(queue.dequeueNotification()); - assertNotNullPtr(pTNf); - assert (pTNf->data() == "third"); - pTNf->release(); - assert (!queue.empty()); - assert (queue.size() == 2); - pTNf = dynamic_cast(queue.dequeueNotification()); - assert (pTNf->data() == "first"); - pTNf->release(); - assert (!queue.empty()); - assert (queue.size() == 1); - pTNf = dynamic_cast(queue.dequeueNotification()); - assertNotNullPtr(pTNf); - assert (pTNf->data() == "second"); - pTNf->release(); - assert (queue.empty()); - assert (queue.size() == 0); - - Notification* pNf = queue.dequeueNotification(); - assertNullPtr(pNf); -} - - -void NotificationQueueTest::testWaitDequeue() -{ - NotificationQueue queue; - queue.enqueueNotification(new QTestNotification("third")); - queue.enqueueNotification(new QTestNotification("fourth")); - assert (!queue.empty()); - assert (queue.size() == 2); - QTestNotification* pTNf = dynamic_cast(queue.waitDequeueNotification(10)); - assertNotNullPtr(pTNf); - assert (pTNf->data() == "third"); - pTNf->release(); - assert (!queue.empty()); - assert (queue.size() == 1); - pTNf = dynamic_cast(queue.waitDequeueNotification(10)); - assertNotNullPtr(pTNf); - assert (pTNf->data() == "fourth"); - pTNf->release(); - assert (queue.empty()); - assert (queue.size() == 0); - - Notification* pNf = queue.waitDequeueNotification(10); - assertNullPtr(pNf); -} - - -void NotificationQueueTest::testThreads() -{ - Thread t1("thread1"); - Thread t2("thread2"); - Thread t3("thread3"); - - RunnableAdapter ra(*this, &NotificationQueueTest::work); - t1.start(ra); - t2.start(ra); - t3.start(ra); - for (int i = 0; i < 5000; ++i) - { - _queue.enqueueNotification(new Notification); - } - while (!_queue.empty()) Thread::sleep(50); - Thread::sleep(20); - _queue.wakeUpAll(); - t1.join(); - t2.join(); - t3.join(); - assert (_handled.size() == 5000); - assert (_handled.count("thread1") > 50); - assert (_handled.count("thread2") > 50); - assert (_handled.count("thread3") > 10); -} - - -void NotificationQueueTest::testDefaultQueue() -{ - NotificationQueue& queue = NotificationQueue::defaultQueue(); - assert (queue.empty()); - assert (queue.size() == 0); -} - - -void NotificationQueueTest::setUp() -{ - _handled.clear(); -} - - -void NotificationQueueTest::tearDown() -{ -} - - -void NotificationQueueTest::work() -{ - Thread::sleep(50); - Notification* pNf = _queue.waitDequeueNotification(); - while (pNf) - { - pNf->release(); - _mutex.lock(); - _handled.insert(Thread::current()->name()); - _mutex.unlock(); - Thread::yield(); - pNf = _queue.waitDequeueNotification(); - } -} - - -CppUnit::Test* NotificationQueueTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("NotificationQueueTest"); - - CppUnit_addTest(pSuite, NotificationQueueTest, testQueueDequeue); - CppUnit_addTest(pSuite, NotificationQueueTest, testQueueDequeueUrgent); - CppUnit_addTest(pSuite, NotificationQueueTest, testWaitDequeue); - CppUnit_addTest(pSuite, NotificationQueueTest, testThreads); - CppUnit_addTest(pSuite, NotificationQueueTest, testDefaultQueue); - - return pSuite; -} +// +// NotificationQueueTest.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/NotificationQueueTest.cpp#1 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "NotificationQueueTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/NotificationQueue.h" +#include "Poco/Notification.h" +#include "Poco/Thread.h" +#include "Poco/Runnable.h" +#include "Poco/RunnableAdapter.h" + + +using Poco::NotificationQueue; +using Poco::Notification; +using Poco::Thread; +using Poco::RunnableAdapter; + + +class QTestNotification: public Notification +{ +public: + QTestNotification(const std::string& data): _data(data) + { + } + ~QTestNotification() + { + } + const std::string& data() const + { + return _data; + } + +private: + std::string _data; +}; + + +NotificationQueueTest::NotificationQueueTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +NotificationQueueTest::~NotificationQueueTest() +{ +} + + +void NotificationQueueTest::testQueueDequeue() +{ + NotificationQueue queue; + assert (queue.empty()); + assert (queue.size() == 0); + Notification* pNf = queue.dequeueNotification(); + assertNullPtr(pNf); + queue.enqueueNotification(new Notification); + assert (!queue.empty()); + assert (queue.size() == 1); + pNf = queue.dequeueNotification(); + assertNotNullPtr(pNf); + assert (queue.empty()); + assert (queue.size() == 0); + pNf->release(); + + queue.enqueueNotification(new QTestNotification("first")); + queue.enqueueNotification(new QTestNotification("second")); + assert (!queue.empty()); + assert (queue.size() == 2); + QTestNotification* pTNf = dynamic_cast(queue.dequeueNotification()); + assertNotNullPtr(pTNf); + assert (pTNf->data() == "first"); + pTNf->release(); + assert (!queue.empty()); + assert (queue.size() == 1); + pTNf = dynamic_cast(queue.dequeueNotification()); + assertNotNullPtr(pTNf); + assert (pTNf->data() == "second"); + pTNf->release(); + assert (queue.empty()); + assert (queue.size() == 0); + + pNf = queue.dequeueNotification(); + assertNullPtr(pNf); +} + + +void NotificationQueueTest::testQueueDequeueUrgent() +{ + NotificationQueue queue; + queue.enqueueNotification(new QTestNotification("first")); + queue.enqueueNotification(new QTestNotification("second")); + queue.enqueueUrgentNotification(new QTestNotification("third")); + assert (!queue.empty()); + assert (queue.size() == 3); + QTestNotification* pTNf = dynamic_cast(queue.dequeueNotification()); + assertNotNullPtr(pTNf); + assert (pTNf->data() == "third"); + pTNf->release(); + assert (!queue.empty()); + assert (queue.size() == 2); + pTNf = dynamic_cast(queue.dequeueNotification()); + assert (pTNf->data() == "first"); + pTNf->release(); + assert (!queue.empty()); + assert (queue.size() == 1); + pTNf = dynamic_cast(queue.dequeueNotification()); + assertNotNullPtr(pTNf); + assert (pTNf->data() == "second"); + pTNf->release(); + assert (queue.empty()); + assert (queue.size() == 0); + + Notification* pNf = queue.dequeueNotification(); + assertNullPtr(pNf); +} + + +void NotificationQueueTest::testWaitDequeue() +{ + NotificationQueue queue; + queue.enqueueNotification(new QTestNotification("third")); + queue.enqueueNotification(new QTestNotification("fourth")); + assert (!queue.empty()); + assert (queue.size() == 2); + QTestNotification* pTNf = dynamic_cast(queue.waitDequeueNotification(10)); + assertNotNullPtr(pTNf); + assert (pTNf->data() == "third"); + pTNf->release(); + assert (!queue.empty()); + assert (queue.size() == 1); + pTNf = dynamic_cast(queue.waitDequeueNotification(10)); + assertNotNullPtr(pTNf); + assert (pTNf->data() == "fourth"); + pTNf->release(); + assert (queue.empty()); + assert (queue.size() == 0); + + Notification* pNf = queue.waitDequeueNotification(10); + assertNullPtr(pNf); +} + + +void NotificationQueueTest::testThreads() +{ + Thread t1("thread1"); + Thread t2("thread2"); + Thread t3("thread3"); + + RunnableAdapter ra(*this, &NotificationQueueTest::work); + t1.start(ra); + t2.start(ra); + t3.start(ra); + for (int i = 0; i < 5000; ++i) + { + _queue.enqueueNotification(new Notification); + } + while (!_queue.empty()) Thread::sleep(50); + Thread::sleep(20); + _queue.wakeUpAll(); + t1.join(); + t2.join(); + t3.join(); + assert (_handled.size() == 5000); + assert (_handled.count("thread1") > 50); + assert (_handled.count("thread2") > 50); + assert (_handled.count("thread3") > 10); +} + + +void NotificationQueueTest::testDefaultQueue() +{ + NotificationQueue& queue = NotificationQueue::defaultQueue(); + assert (queue.empty()); + assert (queue.size() == 0); +} + + +void NotificationQueueTest::setUp() +{ + _handled.clear(); +} + + +void NotificationQueueTest::tearDown() +{ +} + + +void NotificationQueueTest::work() +{ + Thread::sleep(50); + Notification* pNf = _queue.waitDequeueNotification(); + while (pNf) + { + pNf->release(); + _mutex.lock(); + _handled.insert(Thread::current()->name()); + _mutex.unlock(); + Thread::yield(); + pNf = _queue.waitDequeueNotification(); + } +} + + +CppUnit::Test* NotificationQueueTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("NotificationQueueTest"); + + CppUnit_addTest(pSuite, NotificationQueueTest, testQueueDequeue); + CppUnit_addTest(pSuite, NotificationQueueTest, testQueueDequeueUrgent); + CppUnit_addTest(pSuite, NotificationQueueTest, testWaitDequeue); + CppUnit_addTest(pSuite, NotificationQueueTest, testThreads); + CppUnit_addTest(pSuite, NotificationQueueTest, testDefaultQueue); + + return pSuite; +} diff --git a/Foundation/testsuite/src/NotificationQueueTest.h b/Foundation/testsuite/src/NotificationQueueTest.h index 6950f2a37..e6c5ac4ad 100644 --- a/Foundation/testsuite/src/NotificationQueueTest.h +++ b/Foundation/testsuite/src/NotificationQueueTest.h @@ -1,73 +1,73 @@ -// -// NotificationQueueTest.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/NotificationQueueTest.h#1 $ -// -// Definition of the NotificationQueueTest class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 NotificationQueueTest_INCLUDED -#define NotificationQueueTest_INCLUDED - - -#include "Poco/Foundation.h" -#include "CppUnit/TestCase.h" -#include "Poco/NotificationQueue.h" -#include "Poco/Mutex.h" -#include - - -class NotificationQueueTest: public CppUnit::TestCase -{ -public: - NotificationQueueTest(const std::string& name); - ~NotificationQueueTest(); - - void testQueueDequeue(); - void testQueueDequeueUrgent(); - void testWaitDequeue(); - void testThreads(); - void testDefaultQueue(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -protected: - void work(); - -private: - Poco::NotificationQueue _queue; - std::multiset _handled; - Poco::FastMutex _mutex; -}; - - -#endif // NotificationQueueTest_INCLUDED +// +// NotificationQueueTest.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/NotificationQueueTest.h#1 $ +// +// Definition of the NotificationQueueTest class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 NotificationQueueTest_INCLUDED +#define NotificationQueueTest_INCLUDED + + +#include "Poco/Foundation.h" +#include "CppUnit/TestCase.h" +#include "Poco/NotificationQueue.h" +#include "Poco/Mutex.h" +#include + + +class NotificationQueueTest: public CppUnit::TestCase +{ +public: + NotificationQueueTest(const std::string& name); + ~NotificationQueueTest(); + + void testQueueDequeue(); + void testQueueDequeueUrgent(); + void testWaitDequeue(); + void testThreads(); + void testDefaultQueue(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +protected: + void work(); + +private: + Poco::NotificationQueue _queue; + std::multiset _handled; + Poco::FastMutex _mutex; +}; + + +#endif // NotificationQueueTest_INCLUDED diff --git a/Foundation/testsuite/src/NotificationsTestSuite.cpp b/Foundation/testsuite/src/NotificationsTestSuite.cpp index 9e43fd945..d8cba869a 100644 --- a/Foundation/testsuite/src/NotificationsTestSuite.cpp +++ b/Foundation/testsuite/src/NotificationsTestSuite.cpp @@ -1,46 +1,46 @@ -// -// NotificationsTestSuite.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/NotificationsTestSuite.cpp#1 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "NotificationsTestSuite.h" -#include "NotificationCenterTest.h" -#include "NotificationQueueTest.h" - - -CppUnit::Test* NotificationsTestSuite::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("NotificationsTestSuite"); - - pSuite->addTest(NotificationCenterTest::suite()); - pSuite->addTest(NotificationQueueTest::suite()); - - return pSuite; -} +// +// NotificationsTestSuite.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/NotificationsTestSuite.cpp#1 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "NotificationsTestSuite.h" +#include "NotificationCenterTest.h" +#include "NotificationQueueTest.h" + + +CppUnit::Test* NotificationsTestSuite::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("NotificationsTestSuite"); + + pSuite->addTest(NotificationCenterTest::suite()); + pSuite->addTest(NotificationQueueTest::suite()); + + return pSuite; +} diff --git a/Foundation/testsuite/src/NotificationsTestSuite.h b/Foundation/testsuite/src/NotificationsTestSuite.h index 3307ca6ea..58b686b36 100644 --- a/Foundation/testsuite/src/NotificationsTestSuite.h +++ b/Foundation/testsuite/src/NotificationsTestSuite.h @@ -1,49 +1,49 @@ -// -// NotificationsTestSuite.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/NotificationsTestSuite.h#1 $ -// -// Definition of the NotificationsTestSuite class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 NotificationsTestSuite_INCLUDED -#define NotificationsTestSuite_INCLUDED - - -#include "CppUnit/TestSuite.h" - - -class NotificationsTestSuite -{ -public: - static CppUnit::Test* suite(); -}; - - -#endif // NotificationsTestSuite_INCLUDED +// +// NotificationsTestSuite.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/NotificationsTestSuite.h#1 $ +// +// Definition of the NotificationsTestSuite class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 NotificationsTestSuite_INCLUDED +#define NotificationsTestSuite_INCLUDED + + +#include "CppUnit/TestSuite.h" + + +class NotificationsTestSuite +{ +public: + static CppUnit::Test* suite(); +}; + + +#endif // NotificationsTestSuite_INCLUDED diff --git a/Foundation/testsuite/src/NullStreamTest.cpp b/Foundation/testsuite/src/NullStreamTest.cpp index 6636017a5..9764de198 100644 --- a/Foundation/testsuite/src/NullStreamTest.cpp +++ b/Foundation/testsuite/src/NullStreamTest.cpp @@ -1,91 +1,91 @@ -// -// NullStreamTest.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/NullStreamTest.cpp#1 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "NullStreamTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/NullStream.h" - - -using Poco::NullInputStream; -using Poco::NullOutputStream; - - -NullStreamTest::NullStreamTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -NullStreamTest::~NullStreamTest() -{ -} - - -void NullStreamTest::testInput() -{ - NullInputStream istr; - assert (istr.good()); - assert (!istr.eof()); - int c = istr.get(); - assert (c == -1); - assert (istr.eof()); -} - - -void NullStreamTest::testOutput() -{ - NullOutputStream ostr; - assert (ostr.good()); - ostr << "Hello, world!"; - assert (ostr.good()); -} - - -void NullStreamTest::setUp() -{ -} - - -void NullStreamTest::tearDown() -{ -} - - -CppUnit::Test* NullStreamTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("NullStreamTest"); - - CppUnit_addTest(pSuite, NullStreamTest, testInput); - CppUnit_addTest(pSuite, NullStreamTest, testOutput); - - return pSuite; -} +// +// NullStreamTest.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/NullStreamTest.cpp#1 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "NullStreamTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/NullStream.h" + + +using Poco::NullInputStream; +using Poco::NullOutputStream; + + +NullStreamTest::NullStreamTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +NullStreamTest::~NullStreamTest() +{ +} + + +void NullStreamTest::testInput() +{ + NullInputStream istr; + assert (istr.good()); + assert (!istr.eof()); + int c = istr.get(); + assert (c == -1); + assert (istr.eof()); +} + + +void NullStreamTest::testOutput() +{ + NullOutputStream ostr; + assert (ostr.good()); + ostr << "Hello, world!"; + assert (ostr.good()); +} + + +void NullStreamTest::setUp() +{ +} + + +void NullStreamTest::tearDown() +{ +} + + +CppUnit::Test* NullStreamTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("NullStreamTest"); + + CppUnit_addTest(pSuite, NullStreamTest, testInput); + CppUnit_addTest(pSuite, NullStreamTest, testOutput); + + return pSuite; +} diff --git a/Foundation/testsuite/src/NullStreamTest.h b/Foundation/testsuite/src/NullStreamTest.h index 2e3857c68..da87e5223 100644 --- a/Foundation/testsuite/src/NullStreamTest.h +++ b/Foundation/testsuite/src/NullStreamTest.h @@ -1,61 +1,61 @@ -// -// NullStreamTest.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/NullStreamTest.h#1 $ -// -// Definition of the NullStreamTest class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 NullStreamTest_INCLUDED -#define NullStreamTest_INCLUDED - - -#include "Poco/Foundation.h" -#include "CppUnit/TestCase.h" - - -class NullStreamTest: public CppUnit::TestCase -{ -public: - NullStreamTest(const std::string& name); - ~NullStreamTest(); - - void testInput(); - void testOutput(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // NullStreamTest_INCLUDED +// +// NullStreamTest.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/NullStreamTest.h#1 $ +// +// Definition of the NullStreamTest class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 NullStreamTest_INCLUDED +#define NullStreamTest_INCLUDED + + +#include "Poco/Foundation.h" +#include "CppUnit/TestCase.h" + + +class NullStreamTest: public CppUnit::TestCase +{ +public: + NullStreamTest(const std::string& name); + ~NullStreamTest(); + + void testInput(); + void testOutput(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // NullStreamTest_INCLUDED diff --git a/Foundation/testsuite/src/NumberFormatterTest.cpp b/Foundation/testsuite/src/NumberFormatterTest.cpp index 6947e7ec9..4383756da 100644 --- a/Foundation/testsuite/src/NumberFormatterTest.cpp +++ b/Foundation/testsuite/src/NumberFormatterTest.cpp @@ -1,166 +1,166 @@ -// -// NumberFormatterTest.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/NumberFormatterTest.cpp#1 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "NumberFormatterTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/NumberFormatter.h" - - -using Poco::NumberFormatter; -using Poco::Int64; -using Poco::UInt64; - - -NumberFormatterTest::NumberFormatterTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -NumberFormatterTest::~NumberFormatterTest() -{ -} - - -void NumberFormatterTest::testFormat() -{ - assert (NumberFormatter::format(123) == "123"); - assert (NumberFormatter::format(-123) == "-123"); - assert (NumberFormatter::format(-123, 5) == " -123"); - - assert (NumberFormatter::format((unsigned) 123) == "123"); - assert (NumberFormatter::format((unsigned) 123, 5) == " 123"); - assert (NumberFormatter::format0((unsigned) 123, 5) == "00123"); - - assert (NumberFormatter::format((long) 123) == "123"); - assert (NumberFormatter::format((long) -123) == "-123"); - assert (NumberFormatter::format((long) -123, 5) == " -123"); - - assert (NumberFormatter::format((unsigned long) 123) == "123"); - assert (NumberFormatter::format((unsigned long) 123, 5) == " 123"); - -#if defined(POCO_HAVE_INT64) - assert (NumberFormatter::format((Int64) 123) == "123"); - assert (NumberFormatter::format((Int64) -123) == "-123"); - assert (NumberFormatter::format((Int64) -123, 5) == " -123"); - - assert (NumberFormatter::format((UInt64) 123) == "123"); - assert (NumberFormatter::format((UInt64) 123, 5) == " 123"); -#endif - - if (sizeof(void*) == 4) - { - assert (NumberFormatter::format((void*) 0x12345678) == "12345678"); - } - else - { - assert (NumberFormatter::format((void*) 0x12345678) == "0000000012345678"); - } - - assert (NumberFormatter::format(12.25) == "12.25"); - assert (NumberFormatter::format(12.25, 4) == "12.2500"); - assert (NumberFormatter::format(12.25, 8, 4) == " 12.2500"); -} - - -void NumberFormatterTest::testFormat0() -{ - assert (NumberFormatter::format0(123, 5) == "00123"); - assert (NumberFormatter::format0(-123, 5) == "-0123"); - assert (NumberFormatter::format0((long) 123, 5) == "00123"); - assert (NumberFormatter::format0((long) -123, 5) == "-0123"); - assert (NumberFormatter::format0((unsigned long) 123, 5) == "00123"); - -#if defined(POCO_HAVE_INT64) - assert (NumberFormatter::format0((Int64) 123, 5) == "00123"); - assert (NumberFormatter::format0((Int64) -123, 5) == "-0123"); - assert (NumberFormatter::format0((UInt64) 123, 5) == "00123"); -#endif -} - - -void NumberFormatterTest::testFormatHex() -{ - assert (NumberFormatter::formatHex(0x12) == "12"); - assert (NumberFormatter::formatHex(0xab) == "AB"); - assert (NumberFormatter::formatHex(0x12, 4) == "0012"); - assert (NumberFormatter::formatHex(0xab, 4) == "00AB"); - - assert (NumberFormatter::formatHex((unsigned) 0x12) == "12"); - assert (NumberFormatter::formatHex((unsigned) 0xab) == "AB"); - assert (NumberFormatter::formatHex((unsigned) 0x12, 4) == "0012"); - assert (NumberFormatter::formatHex((unsigned) 0xab, 4) == "00AB"); - - assert (NumberFormatter::formatHex((long) 0x12) == "12"); - assert (NumberFormatter::formatHex((long) 0xab) == "AB"); - assert (NumberFormatter::formatHex((long) 0x12, 4) == "0012"); - assert (NumberFormatter::formatHex((long) 0xab, 4) == "00AB"); - - assert (NumberFormatter::formatHex((unsigned long) 0x12) == "12"); - assert (NumberFormatter::formatHex((unsigned long) 0xab) == "AB"); - assert (NumberFormatter::formatHex((unsigned long) 0x12, 4) == "0012"); - assert (NumberFormatter::formatHex((unsigned long) 0xab, 4) == "00AB"); - -#if defined(POCO_HAVE_INT64) - assert (NumberFormatter::formatHex((Int64) 0x12) == "12"); - assert (NumberFormatter::formatHex((Int64) 0xab) == "AB"); - assert (NumberFormatter::formatHex((Int64) 0x12, 4) == "0012"); - assert (NumberFormatter::formatHex((Int64) 0xab, 4) == "00AB"); - - assert (NumberFormatter::formatHex((UInt64) 0x12) == "12"); - assert (NumberFormatter::formatHex((UInt64) 0xab) == "AB"); - assert (NumberFormatter::formatHex((UInt64) 0x12, 4) == "0012"); - assert (NumberFormatter::formatHex((UInt64) 0xab, 4) == "00AB"); -#endif -} - - -void NumberFormatterTest::setUp() -{ -} - - -void NumberFormatterTest::tearDown() -{ -} - - -CppUnit::Test* NumberFormatterTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("NumberFormatterTest"); - - CppUnit_addTest(pSuite, NumberFormatterTest, testFormat); - CppUnit_addTest(pSuite, NumberFormatterTest, testFormat0); - CppUnit_addTest(pSuite, NumberFormatterTest, testFormatHex); - - return pSuite; -} +// +// NumberFormatterTest.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/NumberFormatterTest.cpp#1 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "NumberFormatterTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/NumberFormatter.h" + + +using Poco::NumberFormatter; +using Poco::Int64; +using Poco::UInt64; + + +NumberFormatterTest::NumberFormatterTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +NumberFormatterTest::~NumberFormatterTest() +{ +} + + +void NumberFormatterTest::testFormat() +{ + assert (NumberFormatter::format(123) == "123"); + assert (NumberFormatter::format(-123) == "-123"); + assert (NumberFormatter::format(-123, 5) == " -123"); + + assert (NumberFormatter::format((unsigned) 123) == "123"); + assert (NumberFormatter::format((unsigned) 123, 5) == " 123"); + assert (NumberFormatter::format0((unsigned) 123, 5) == "00123"); + + assert (NumberFormatter::format((long) 123) == "123"); + assert (NumberFormatter::format((long) -123) == "-123"); + assert (NumberFormatter::format((long) -123, 5) == " -123"); + + assert (NumberFormatter::format((unsigned long) 123) == "123"); + assert (NumberFormatter::format((unsigned long) 123, 5) == " 123"); + +#if defined(POCO_HAVE_INT64) + assert (NumberFormatter::format((Int64) 123) == "123"); + assert (NumberFormatter::format((Int64) -123) == "-123"); + assert (NumberFormatter::format((Int64) -123, 5) == " -123"); + + assert (NumberFormatter::format((UInt64) 123) == "123"); + assert (NumberFormatter::format((UInt64) 123, 5) == " 123"); +#endif + + if (sizeof(void*) == 4) + { + assert (NumberFormatter::format((void*) 0x12345678) == "12345678"); + } + else + { + assert (NumberFormatter::format((void*) 0x12345678) == "0000000012345678"); + } + + assert (NumberFormatter::format(12.25) == "12.25"); + assert (NumberFormatter::format(12.25, 4) == "12.2500"); + assert (NumberFormatter::format(12.25, 8, 4) == " 12.2500"); +} + + +void NumberFormatterTest::testFormat0() +{ + assert (NumberFormatter::format0(123, 5) == "00123"); + assert (NumberFormatter::format0(-123, 5) == "-0123"); + assert (NumberFormatter::format0((long) 123, 5) == "00123"); + assert (NumberFormatter::format0((long) -123, 5) == "-0123"); + assert (NumberFormatter::format0((unsigned long) 123, 5) == "00123"); + +#if defined(POCO_HAVE_INT64) + assert (NumberFormatter::format0((Int64) 123, 5) == "00123"); + assert (NumberFormatter::format0((Int64) -123, 5) == "-0123"); + assert (NumberFormatter::format0((UInt64) 123, 5) == "00123"); +#endif +} + + +void NumberFormatterTest::testFormatHex() +{ + assert (NumberFormatter::formatHex(0x12) == "12"); + assert (NumberFormatter::formatHex(0xab) == "AB"); + assert (NumberFormatter::formatHex(0x12, 4) == "0012"); + assert (NumberFormatter::formatHex(0xab, 4) == "00AB"); + + assert (NumberFormatter::formatHex((unsigned) 0x12) == "12"); + assert (NumberFormatter::formatHex((unsigned) 0xab) == "AB"); + assert (NumberFormatter::formatHex((unsigned) 0x12, 4) == "0012"); + assert (NumberFormatter::formatHex((unsigned) 0xab, 4) == "00AB"); + + assert (NumberFormatter::formatHex((long) 0x12) == "12"); + assert (NumberFormatter::formatHex((long) 0xab) == "AB"); + assert (NumberFormatter::formatHex((long) 0x12, 4) == "0012"); + assert (NumberFormatter::formatHex((long) 0xab, 4) == "00AB"); + + assert (NumberFormatter::formatHex((unsigned long) 0x12) == "12"); + assert (NumberFormatter::formatHex((unsigned long) 0xab) == "AB"); + assert (NumberFormatter::formatHex((unsigned long) 0x12, 4) == "0012"); + assert (NumberFormatter::formatHex((unsigned long) 0xab, 4) == "00AB"); + +#if defined(POCO_HAVE_INT64) + assert (NumberFormatter::formatHex((Int64) 0x12) == "12"); + assert (NumberFormatter::formatHex((Int64) 0xab) == "AB"); + assert (NumberFormatter::formatHex((Int64) 0x12, 4) == "0012"); + assert (NumberFormatter::formatHex((Int64) 0xab, 4) == "00AB"); + + assert (NumberFormatter::formatHex((UInt64) 0x12) == "12"); + assert (NumberFormatter::formatHex((UInt64) 0xab) == "AB"); + assert (NumberFormatter::formatHex((UInt64) 0x12, 4) == "0012"); + assert (NumberFormatter::formatHex((UInt64) 0xab, 4) == "00AB"); +#endif +} + + +void NumberFormatterTest::setUp() +{ +} + + +void NumberFormatterTest::tearDown() +{ +} + + +CppUnit::Test* NumberFormatterTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("NumberFormatterTest"); + + CppUnit_addTest(pSuite, NumberFormatterTest, testFormat); + CppUnit_addTest(pSuite, NumberFormatterTest, testFormat0); + CppUnit_addTest(pSuite, NumberFormatterTest, testFormatHex); + + return pSuite; +} diff --git a/Foundation/testsuite/src/NumberFormatterTest.h b/Foundation/testsuite/src/NumberFormatterTest.h index 1249bf068..a18f2f94a 100644 --- a/Foundation/testsuite/src/NumberFormatterTest.h +++ b/Foundation/testsuite/src/NumberFormatterTest.h @@ -1,62 +1,62 @@ -// -// NumberFormatterTest.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/NumberFormatterTest.h#1 $ -// -// Definition of the NumberFormatterTest class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 NumberFormatterTest_INCLUDED -#define NumberFormatterTest_INCLUDED - - -#include "Poco/Foundation.h" -#include "CppUnit/TestCase.h" - - -class NumberFormatterTest: public CppUnit::TestCase -{ -public: - NumberFormatterTest(const std::string& name); - ~NumberFormatterTest(); - - void testFormat(); - void testFormat0(); - void testFormatHex(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // NumberFormatterTest_INCLUDED +// +// NumberFormatterTest.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/NumberFormatterTest.h#1 $ +// +// Definition of the NumberFormatterTest class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 NumberFormatterTest_INCLUDED +#define NumberFormatterTest_INCLUDED + + +#include "Poco/Foundation.h" +#include "CppUnit/TestCase.h" + + +class NumberFormatterTest: public CppUnit::TestCase +{ +public: + NumberFormatterTest(const std::string& name); + ~NumberFormatterTest(); + + void testFormat(); + void testFormat0(); + void testFormatHex(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // NumberFormatterTest_INCLUDED diff --git a/Foundation/testsuite/src/NumberParserTest.cpp b/Foundation/testsuite/src/NumberParserTest.cpp index 0febabb6c..89eeaed42 100644 --- a/Foundation/testsuite/src/NumberParserTest.cpp +++ b/Foundation/testsuite/src/NumberParserTest.cpp @@ -1,169 +1,169 @@ -// -// NumberParserTest.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/NumberParserTest.cpp#1 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "NumberParserTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/NumberParser.h" -#include "Poco/Exception.h" - - -using Poco::NumberParser; -using Poco::SyntaxException; - - -NumberParserTest::NumberParserTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -NumberParserTest::~NumberParserTest() -{ -} - - -void NumberParserTest::testParse() -{ - assert (NumberParser::parse("123") == 123); - assert (NumberParser::parse("-123") == -123); - assert (NumberParser::parseUnsigned("123") == 123); - assert (NumberParser::parseHex("12AB") == 0x12ab); - -#if defined(POCO_HAVE_INT64) - assert (NumberParser::parse64("123") == 123); - assert (NumberParser::parse64("-123") == -123); - assert (NumberParser::parseUnsigned64("123") == 123); - assert (NumberParser::parseHex64("12AB") == 0x12ab); -#endif - - assertEqualDelta (12.34, NumberParser::parseFloat("12.34"), 0.01); -} - -void NumberParserTest::testParseError() -{ - try - { - NumberParser::parse(""); - failmsg("must throw SyntaxException"); - } - catch (SyntaxException&) - { - } - - try - { - NumberParser::parse("asd"); - failmsg("must throw SyntaxException"); - } - catch (SyntaxException&) - { - } - - try - { - NumberParser::parseUnsigned("a123"); - failmsg("must throw SyntaxException"); - } - catch (SyntaxException&) - { - } - - try - { - NumberParser::parseHex("z23"); - failmsg("must throw SyntaxException"); - } - catch (SyntaxException&) - { - } - -#if defined(POCO_HAVE_INT64) - - try - { - NumberParser::parse64("asd"); - failmsg("must throw SyntaxException"); - } - catch (SyntaxException&) - { - } - - try - { - NumberParser::parseUnsigned64(""); - failmsg("must throw SyntaxException"); - } - catch (SyntaxException&) - { - } - - try - { - NumberParser::parseHex64("zaz"); - failmsg("must throw SyntaxException"); - } - catch (SyntaxException&) - { - } - -#endif - - try - { - NumberParser::parseFloat("a12.3"); - failmsg("must throw SyntaxException"); - } - catch (SyntaxException&) - { - } -} - - -void NumberParserTest::setUp() -{ -} - - -void NumberParserTest::tearDown() -{ -} - - -CppUnit::Test* NumberParserTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("NumberParserTest"); - - CppUnit_addTest(pSuite, NumberParserTest, testParse); - CppUnit_addTest(pSuite, NumberParserTest, testParseError); - - return pSuite; -} +// +// NumberParserTest.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/NumberParserTest.cpp#1 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "NumberParserTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/NumberParser.h" +#include "Poco/Exception.h" + + +using Poco::NumberParser; +using Poco::SyntaxException; + + +NumberParserTest::NumberParserTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +NumberParserTest::~NumberParserTest() +{ +} + + +void NumberParserTest::testParse() +{ + assert (NumberParser::parse("123") == 123); + assert (NumberParser::parse("-123") == -123); + assert (NumberParser::parseUnsigned("123") == 123); + assert (NumberParser::parseHex("12AB") == 0x12ab); + +#if defined(POCO_HAVE_INT64) + assert (NumberParser::parse64("123") == 123); + assert (NumberParser::parse64("-123") == -123); + assert (NumberParser::parseUnsigned64("123") == 123); + assert (NumberParser::parseHex64("12AB") == 0x12ab); +#endif + + assertEqualDelta (12.34, NumberParser::parseFloat("12.34"), 0.01); +} + +void NumberParserTest::testParseError() +{ + try + { + NumberParser::parse(""); + failmsg("must throw SyntaxException"); + } + catch (SyntaxException&) + { + } + + try + { + NumberParser::parse("asd"); + failmsg("must throw SyntaxException"); + } + catch (SyntaxException&) + { + } + + try + { + NumberParser::parseUnsigned("a123"); + failmsg("must throw SyntaxException"); + } + catch (SyntaxException&) + { + } + + try + { + NumberParser::parseHex("z23"); + failmsg("must throw SyntaxException"); + } + catch (SyntaxException&) + { + } + +#if defined(POCO_HAVE_INT64) + + try + { + NumberParser::parse64("asd"); + failmsg("must throw SyntaxException"); + } + catch (SyntaxException&) + { + } + + try + { + NumberParser::parseUnsigned64(""); + failmsg("must throw SyntaxException"); + } + catch (SyntaxException&) + { + } + + try + { + NumberParser::parseHex64("zaz"); + failmsg("must throw SyntaxException"); + } + catch (SyntaxException&) + { + } + +#endif + + try + { + NumberParser::parseFloat("a12.3"); + failmsg("must throw SyntaxException"); + } + catch (SyntaxException&) + { + } +} + + +void NumberParserTest::setUp() +{ +} + + +void NumberParserTest::tearDown() +{ +} + + +CppUnit::Test* NumberParserTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("NumberParserTest"); + + CppUnit_addTest(pSuite, NumberParserTest, testParse); + CppUnit_addTest(pSuite, NumberParserTest, testParseError); + + return pSuite; +} diff --git a/Foundation/testsuite/src/NumberParserTest.h b/Foundation/testsuite/src/NumberParserTest.h index 6f9ea348a..5e92a705d 100644 --- a/Foundation/testsuite/src/NumberParserTest.h +++ b/Foundation/testsuite/src/NumberParserTest.h @@ -1,61 +1,61 @@ -// -// NumberParserTest.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/NumberParserTest.h#1 $ -// -// Definition of the NumberParserTest class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 NumberParserTest_INCLUDED -#define NumberParserTest_INCLUDED - - -#include "Poco/Foundation.h" -#include "CppUnit/TestCase.h" - - -class NumberParserTest: public CppUnit::TestCase -{ -public: - NumberParserTest(const std::string& name); - ~NumberParserTest(); - - void testParse(); - void testParseError(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // NumberParserTest_INCLUDED +// +// NumberParserTest.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/NumberParserTest.h#1 $ +// +// Definition of the NumberParserTest class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 NumberParserTest_INCLUDED +#define NumberParserTest_INCLUDED + + +#include "Poco/Foundation.h" +#include "CppUnit/TestCase.h" + + +class NumberParserTest: public CppUnit::TestCase +{ +public: + NumberParserTest(const std::string& name); + ~NumberParserTest(); + + void testParse(); + void testParseError(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // NumberParserTest_INCLUDED diff --git a/Foundation/testsuite/src/PathTest.cpp b/Foundation/testsuite/src/PathTest.cpp index c611496bc..904690d05 100644 --- a/Foundation/testsuite/src/PathTest.cpp +++ b/Foundation/testsuite/src/PathTest.cpp @@ -1,1652 +1,1652 @@ -// -// PathTest.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/PathTest.cpp#1 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "PathTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/Path.h" -#include "Poco/Exception.h" -#include "Poco/Random.h" -#include "Poco/Environment.h" -#include - - -using Poco::Path; -using Poco::PathSyntaxException; -using Poco::Random; -using Poco::Environment; - - -PathTest::PathTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -PathTest::~PathTest() -{ -} - - -void PathTest::testParseUnix1() -{ - Path p; - p.parse("", Path::PATH_UNIX); - assert (p.isRelative()); - assert (!p.isAbsolute()); - assert (p.depth() == 0); - assert (p.isDirectory()); - assert (!p.isFile()); - assert (p.toString(Path::PATH_UNIX) == ""); - - p.parse("/", Path::PATH_UNIX); - assert (!p.isRelative()); - assert (p.isAbsolute()); - assert (p.depth() == 0); - assert (p.isDirectory()); - assert (!p.isFile()); - assert (p.toString(Path::PATH_UNIX) == "/"); - - p.parse("/usr", Path::PATH_UNIX); - assert (!p.isRelative()); - assert (p.isAbsolute()); - assert (p.depth() == 0); - assert (!p.isDirectory()); - assert (p.isFile()); - assert (p.toString(Path::PATH_UNIX) == "/usr"); - - p.parse("/usr/", Path::PATH_UNIX); - assert (!p.isRelative()); - assert (p.isAbsolute()); - assert (p.depth() == 1); - assert (p[0] == "usr"); - assert (p.isDirectory()); - assert (!p.isFile()); - assert (p.toString(Path::PATH_UNIX) == "/usr/"); - - p.parse("usr/", Path::PATH_UNIX); - assert (p.isRelative()); - assert (!p.isAbsolute()); - assert (p.depth() == 1); - assert (p[0] == "usr"); - assert (p.isDirectory()); - assert (!p.isFile()); - assert (p.toString(Path::PATH_UNIX) == "usr/"); - - p.parse("usr", Path::PATH_UNIX); - assert (p.isRelative()); - assert (!p.isAbsolute()); - assert (p.depth() == 0); - assert (p[0] == "usr"); - assert (!p.isDirectory()); - assert (p.isFile()); - assert (p.toString(Path::PATH_UNIX) == "usr"); - - p.parse("/usr/local", Path::PATH_UNIX); - assert (!p.isRelative()); - assert (p.isAbsolute()); - assert (p.depth() == 1); - assert (p[0] == "usr"); - assert (p[1] == "local"); - assert (!p.isDirectory()); - assert (p.isFile()); - assert (p.toString(Path::PATH_UNIX) == "/usr/local"); -} - - -void PathTest::testParseUnix2() -{ - Path p; - p.parse("/usr/local/", Path::PATH_UNIX); - assert (!p.isRelative()); - assert (p.isAbsolute()); - assert (p.depth() == 2); - assert (p[0] == "usr"); - assert (p[1] == "local"); - assert (p.isDirectory()); - assert (!p.isFile()); - assert (p.toString(Path::PATH_UNIX) == "/usr/local/"); - - p.parse("usr/local/", Path::PATH_UNIX); - assert (p.isRelative()); - assert (!p.isAbsolute()); - assert (p.depth() == 2); - assert (p[0] == "usr"); - assert (p[1] == "local"); - assert (p.isDirectory()); - assert (!p.isFile()); - assert (p.toString(Path::PATH_UNIX) == "usr/local/"); - - p.parse("usr/local", Path::PATH_UNIX); - assert (p.isRelative()); - assert (!p.isAbsolute()); - assert (p.depth() == 1); - assert (p[0] == "usr"); - assert (p[1] == "local"); - assert (!p.isDirectory()); - assert (p.isFile()); - assert (p.toString(Path::PATH_UNIX) == "usr/local"); - - p.parse("/usr/local/bin", Path::PATH_UNIX); - assert (!p.isRelative()); - assert (p.isAbsolute()); - assert (p.depth() == 2); - assert (p[0] == "usr"); - assert (p[1] == "local"); - assert (p[2] == "bin"); - assert (!p.isDirectory()); - assert (p.isFile()); - assert (p.toString(Path::PATH_UNIX) == "/usr/local/bin"); - - p.parse("/usr/local/bin/", Path::PATH_UNIX); - assert (!p.isRelative()); - assert (p.isAbsolute()); - assert (p.depth() == 3); - assert (p[0] == "usr"); - assert (p[1] == "local"); - assert (p[2] == "bin"); - assert (p.isDirectory()); - assert (!p.isFile()); - assert (p.toString(Path::PATH_UNIX) == "/usr/local/bin/"); -} - - -void PathTest::testParseUnix3() -{ - Path p; - p.parse("//usr/local/bin/", Path::PATH_UNIX); - assert (!p.isRelative()); - assert (p.isAbsolute()); - assert (p.depth() == 3); - assert (p[0] == "usr"); - assert (p[1] == "local"); - assert (p[2] == "bin"); - assert (p.isDirectory()); - assert (!p.isFile()); - assert (p.toString(Path::PATH_UNIX) == "/usr/local/bin/"); - - p.parse("/usr//local/bin/", Path::PATH_UNIX); - assert (!p.isRelative()); - assert (p.isAbsolute()); - assert (p.depth() == 3); - assert (p[0] == "usr"); - assert (p[1] == "local"); - assert (p[2] == "bin"); - assert (p.isDirectory()); - assert (!p.isFile()); - assert (p.toString(Path::PATH_UNIX) == "/usr/local/bin/"); - - p.parse("/usr/local//bin/", Path::PATH_UNIX); - assert (!p.isRelative()); - assert (p.isAbsolute()); - assert (p.depth() == 3); - assert (p[0] == "usr"); - assert (p[1] == "local"); - assert (p[2] == "bin"); - assert (p.isDirectory()); - assert (!p.isFile()); - assert (p.toString(Path::PATH_UNIX) == "/usr/local/bin/"); - - p.parse("/usr/local/bin//", Path::PATH_UNIX); - assert (!p.isRelative()); - assert (p.isAbsolute()); - assert (p.depth() == 3); - assert (p[0] == "usr"); - assert (p[1] == "local"); - assert (p[2] == "bin"); - assert (p.isDirectory()); - assert (!p.isFile()); - assert (p.toString(Path::PATH_UNIX) == "/usr/local/bin/"); - - p.parse("/usr/local/./bin/", Path::PATH_UNIX); - assert (!p.isRelative()); - assert (p.isAbsolute()); - assert (p.depth() == 3); - assert (p[0] == "usr"); - assert (p[1] == "local"); - assert (p[2] == "bin"); - assert (p.isDirectory()); - assert (!p.isFile()); - assert (p.toString(Path::PATH_UNIX) == "/usr/local/bin/"); - - p.parse("./usr/local/bin/", Path::PATH_UNIX); - assert (p.isRelative()); - assert (!p.isAbsolute()); - assert (p.depth() == 3); - assert (p[0] == "usr"); - assert (p[1] == "local"); - assert (p[2] == "bin"); - assert (p.isDirectory()); - assert (!p.isFile()); - assert (p.toString(Path::PATH_UNIX) == "usr/local/bin/"); - - p.parse("./usr/local/bin/./", Path::PATH_UNIX); - assert (p.isRelative()); - assert (!p.isAbsolute()); - assert (p.depth() == 3); - assert (p[0] == "usr"); - assert (p[1] == "local"); - assert (p[2] == "bin"); - assert (p.isDirectory()); - assert (!p.isFile()); - assert (p.toString(Path::PATH_UNIX) == "usr/local/bin/"); - - p.parse("./usr/local/bin/.", Path::PATH_UNIX); - assert (p.isRelative()); - assert (!p.isAbsolute()); - assert (p.depth() == 3); - assert (p[0] == "usr"); - assert (p[1] == "local"); - assert (p[2] == "bin"); - assert (!p.isDirectory()); - assert (p.isFile()); - assert (p.toString(Path::PATH_UNIX) == "usr/local/bin/."); -} - - -void PathTest::testParseUnix4() -{ - Path p; - p.parse("/usr/local/lib/../bin/", Path::PATH_UNIX); - assert (!p.isRelative()); - assert (p.isAbsolute()); - assert (p.depth() == 3); - assert (p[0] == "usr"); - assert (p[1] == "local"); - assert (p[2] == "bin"); - assert (p.isDirectory()); - assert (!p.isFile()); - assert (p.toString(Path::PATH_UNIX) == "/usr/local/bin/"); - - p.parse("/usr/local/lib/../bin/", Path::PATH_UNIX); - assert (!p.isRelative()); - assert (p.isAbsolute()); - assert (p.depth() == 3); - assert (p[0] == "usr"); - assert (p[1] == "local"); - assert (p[2] == "bin"); - assert (p.isDirectory()); - assert (!p.isFile()); - assert (p.toString(Path::PATH_UNIX) == "/usr/local/bin/"); - - p.parse("/usr/local/lib/../../", Path::PATH_UNIX); - assert (!p.isRelative()); - assert (p.isAbsolute()); - assert (p.depth() == 1); - assert (p[0] == "usr"); - assert (p.isDirectory()); - assert (!p.isFile()); - assert (p.toString(Path::PATH_UNIX) == "/usr/"); - - p.parse("/usr/local/lib/..", Path::PATH_UNIX); - assert (!p.isRelative()); - assert (p.isAbsolute()); - assert (p.depth() == 3); - assert (p[0] == "usr"); - assert (p[1] == "local"); - assert (p[2] == "lib"); - assert (!p.isDirectory()); - assert (p.isFile()); - assert (p.toString(Path::PATH_UNIX) == "/usr/local/lib/.."); - - p.parse("../usr/local/lib/", Path::PATH_UNIX); - assert (p.isRelative()); - assert (!p.isAbsolute()); - assert (p.depth() == 4); - assert (p[0] == ".."); - assert (p[1] == "usr"); - assert (p[2] == "local"); - assert (p[3] == "lib"); - assert (p.isDirectory()); - assert (!p.isFile()); - assert (p.toString(Path::PATH_UNIX) == "../usr/local/lib/"); - - p.parse("/usr/../lib/", Path::PATH_UNIX); - assert (!p.isRelative()); - assert (p.isAbsolute()); - assert (p.depth() == 1); - assert (p[0] == "lib"); - assert (p.isDirectory()); - assert (!p.isFile()); - assert (p.toString(Path::PATH_UNIX) == "/lib/"); - - p.parse("/usr/../../lib/", Path::PATH_UNIX); - assert (!p.isRelative()); - assert (p.isAbsolute()); - assert (p.depth() == 1); - assert (p[0] == "lib"); - assert (p.isDirectory()); - assert (!p.isFile()); - assert (p.toString(Path::PATH_UNIX) == "/lib/"); - - p.parse("local/../../lib/", Path::PATH_UNIX); - assert (p.isRelative()); - assert (!p.isAbsolute()); - assert (p.depth() == 2); - assert (p[0] == ".."); - assert (p[1] == "lib"); - assert (p.isDirectory()); - assert (!p.isFile()); - assert (p.toString(Path::PATH_UNIX) == "../lib/"); - - p.parse("a/b/c/d", Path::PATH_UNIX); - assert (p.isRelative()); - assert (!p.isAbsolute()); - assert (p.depth() == 3); - assert (p[0] == "a"); - assert (p[1] == "b"); - assert (p[2] == "c"); - assert (!p.isDirectory()); - assert (p.isFile()); - assert (p.toString(Path::PATH_UNIX) == "a/b/c/d"); -} - - -void PathTest::testParseUnix5() -{ - Path p; - p.parse("/c:/windows/system32/", Path::PATH_UNIX); - assert (!p.isRelative()); - assert (p.isAbsolute()); - assert (p.getDevice() == "c"); - assert (p.depth() == 2); - assert (p[0] == "windows"); - assert (p[1] == "system32"); - assert (p.isDirectory()); - assert (!p.isFile()); - assert (p.toString(Path::PATH_UNIX) == "/c:/windows/system32/"); -} - - -void PathTest::testParseWindows1() -{ - Path p; - p.parse("", Path::PATH_WINDOWS); - assert (p.isRelative()); - assert (!p.isAbsolute()); - assert (p.depth() == 0); - assert (p.isDirectory()); - assert (!p.isFile()); - assert (p.toString(Path::PATH_WINDOWS) == ""); - - p.parse("/", Path::PATH_WINDOWS); - assert (!p.isRelative()); - assert (p.isAbsolute()); - assert (p.depth() == 0); - assert (p.isDirectory()); - assert (!p.isFile()); - assert (p.toString(Path::PATH_WINDOWS) == "\\"); - - p.parse("\\", Path::PATH_WINDOWS); - assert (!p.isRelative()); - assert (p.isAbsolute()); - assert (p.depth() == 0); - assert (p.isDirectory()); - assert (!p.isFile()); - assert (p.toString(Path::PATH_WINDOWS) == "\\"); - - p.parse("/usr", Path::PATH_WINDOWS); - assert (!p.isRelative()); - assert (p.isAbsolute()); - assert (p.depth() == 0); - assert (!p.isDirectory()); - assert (p.isFile()); - assert (p.toString(Path::PATH_WINDOWS) == "\\usr"); - - p.parse("\\usr", Path::PATH_WINDOWS); - assert (!p.isRelative()); - assert (p.isAbsolute()); - assert (p.depth() == 0); - assert (!p.isDirectory()); - assert (p.isFile()); - assert (p.toString(Path::PATH_WINDOWS) == "\\usr"); - - p.parse("/usr/", Path::PATH_WINDOWS); - assert (!p.isRelative()); - assert (p.isAbsolute()); - assert (p.depth() == 1); - assert (p[0] == "usr"); - assert (p.isDirectory()); - assert (!p.isFile()); - assert (p.toString(Path::PATH_WINDOWS) == "\\usr\\"); - - p.parse("\\usr\\", Path::PATH_WINDOWS); - assert (!p.isRelative()); - assert (p.isAbsolute()); - assert (p.depth() == 1); - assert (p[0] == "usr"); - assert (p.isDirectory()); - assert (!p.isFile()); - assert (p.toString(Path::PATH_WINDOWS) == "\\usr\\"); -} - - -void PathTest::testParseWindows2() -{ - Path p; - p.parse("usr/", Path::PATH_WINDOWS); - assert (p.isRelative()); - assert (!p.isAbsolute()); - assert (p.depth() == 1); - assert (p[0] == "usr"); - assert (p.isDirectory()); - assert (!p.isFile()); - assert (p.toString(Path::PATH_WINDOWS) == "usr\\"); - - p.parse("usr", Path::PATH_WINDOWS); - assert (p.isRelative()); - assert (!p.isAbsolute()); - assert (p.depth() == 0); - assert (p[0] == "usr"); - assert (!p.isDirectory()); - assert (p.isFile()); - assert (p.toString(Path::PATH_WINDOWS) == "usr"); - - p.parse("usr\\", Path::PATH_WINDOWS); - assert (p.isRelative()); - assert (!p.isAbsolute()); - assert (p.depth() == 1); - assert (p[0] == "usr"); - assert (p.isDirectory()); - assert (!p.isFile()); - assert (p.toString(Path::PATH_WINDOWS) == "usr\\"); - - p.parse("/usr/local", Path::PATH_WINDOWS); - assert (!p.isRelative()); - assert (p.isAbsolute()); - assert (p.depth() == 1); - assert (p[0] == "usr"); - assert (p[1] == "local"); - assert (!p.isDirectory()); - assert (p.isFile()); - assert (p.toString(Path::PATH_WINDOWS) == "\\usr\\local"); - - p.parse("\\usr\\local", Path::PATH_WINDOWS); - assert (!p.isRelative()); - assert (p.isAbsolute()); - assert (p.depth() == 1); - assert (p[0] == "usr"); - assert (p[1] == "local"); - assert (!p.isDirectory()); - assert (p.isFile()); - assert (p.toString(Path::PATH_WINDOWS) == "\\usr\\local"); - - p.parse("/usr/local/", Path::PATH_WINDOWS); - assert (!p.isRelative()); - assert (p.isAbsolute()); - assert (p.depth() == 2); - assert (p[0] == "usr"); - assert (p[1] == "local"); - assert (p.isDirectory()); - assert (!p.isFile()); - assert (p.toString(Path::PATH_WINDOWS) == "\\usr\\local\\"); - - p.parse("usr/local/", Path::PATH_WINDOWS); - assert (p.isRelative()); - assert (!p.isAbsolute()); - assert (p.depth() == 2); - assert (p[0] == "usr"); - assert (p[1] == "local"); - assert (p.isDirectory()); - assert (!p.isFile()); - assert (p.toString(Path::PATH_WINDOWS) == "usr\\local\\"); - - p.parse("usr/local", Path::PATH_WINDOWS); - assert (p.isRelative()); - assert (!p.isAbsolute()); - assert (p.depth() == 1); - assert (p[0] == "usr"); - assert (p[1] == "local"); - assert (!p.isDirectory()); - assert (p.isFile()); - assert (p.toString(Path::PATH_WINDOWS) == "usr\\local"); - - p.parse("/usr/local/bin", Path::PATH_WINDOWS); - assert (!p.isRelative()); - assert (p.isAbsolute()); - assert (p.depth() == 2); - assert (p[0] == "usr"); - assert (p[1] == "local"); - assert (p[2] == "bin"); - assert (!p.isDirectory()); - assert (p.isFile()); - assert (p.toString(Path::PATH_WINDOWS) == "\\usr\\local\\bin"); - - p.parse("/usr/local/bin/", Path::PATH_WINDOWS); - assert (!p.isRelative()); - assert (p.isAbsolute()); - assert (p.depth() == 3); - assert (p[0] == "usr"); - assert (p[1] == "local"); - assert (p[2] == "bin"); - assert (p.isDirectory()); - assert (!p.isFile()); - assert (p.toString(Path::PATH_WINDOWS) == "\\usr\\local\\bin\\"); - - p.parse("/usr//local/bin/", Path::PATH_WINDOWS); - assert (!p.isRelative()); - assert (p.isAbsolute()); - assert (p.depth() == 3); - assert (p[0] == "usr"); - assert (p[1] == "local"); - assert (p[2] == "bin"); - assert (p.isDirectory()); - assert (!p.isFile()); - assert (p.toString(Path::PATH_WINDOWS) == "\\usr\\local\\bin\\"); - - p.parse("/usr/local//bin/", Path::PATH_WINDOWS); - assert (!p.isRelative()); - assert (p.isAbsolute()); - assert (p.depth() == 3); - assert (p[0] == "usr"); - assert (p[1] == "local"); - assert (p[2] == "bin"); - assert (p.isDirectory()); - assert (!p.isFile()); - assert (p.toString(Path::PATH_WINDOWS) == "\\usr\\local\\bin\\"); - - p.parse("/usr/local/bin//", Path::PATH_WINDOWS); - assert (!p.isRelative()); - assert (p.isAbsolute()); - assert (p.depth() == 3); - assert (p[0] == "usr"); - assert (p[1] == "local"); - assert (p[2] == "bin"); - assert (p.isDirectory()); - assert (!p.isFile()); - assert (p.toString(Path::PATH_WINDOWS) == "\\usr\\local\\bin\\"); -} - - -void PathTest::testParseWindows3() -{ - Path p; - p.parse("/usr/local/./bin/", Path::PATH_WINDOWS); - assert (!p.isRelative()); - assert (p.isAbsolute()); - assert (p.depth() == 3); - assert (p[0] == "usr"); - assert (p[1] == "local"); - assert (p[2] == "bin"); - assert (p.isDirectory()); - assert (!p.isFile()); - assert (p.toString(Path::PATH_WINDOWS) == "\\usr\\local\\bin\\"); - - p.parse("./usr/local/bin/", Path::PATH_WINDOWS); - assert (p.isRelative()); - assert (!p.isAbsolute()); - assert (p.depth() == 3); - assert (p[0] == "usr"); - assert (p[1] == "local"); - assert (p[2] == "bin"); - assert (p.isDirectory()); - assert (!p.isFile()); - assert (p.toString(Path::PATH_WINDOWS) == "usr\\local\\bin\\"); - - p.parse("./usr/local/bin/./", Path::PATH_WINDOWS); - assert (p.isRelative()); - assert (!p.isAbsolute()); - assert (p.depth() == 3); - assert (p[0] == "usr"); - assert (p[1] == "local"); - assert (p[2] == "bin"); - assert (p.isDirectory()); - assert (!p.isFile()); - assert (p.toString(Path::PATH_WINDOWS) == "usr\\local\\bin\\"); - - p.parse("./usr/local/bin/.", Path::PATH_WINDOWS); - assert (p.isRelative()); - assert (!p.isAbsolute()); - assert (p.depth() == 3); - assert (p[0] == "usr"); - assert (p[1] == "local"); - assert (p[2] == "bin"); - assert (!p.isDirectory()); - assert (p.isFile()); - assert (p.toString(Path::PATH_WINDOWS) == "usr\\local\\bin\\."); - - p.parse("/usr/local/lib/../bin/", Path::PATH_WINDOWS); - assert (!p.isRelative()); - assert (p.isAbsolute()); - assert (p.depth() == 3); - assert (p[0] == "usr"); - assert (p[1] == "local"); - assert (p[2] == "bin"); - assert (p.isDirectory()); - assert (!p.isFile()); - assert (p.toString(Path::PATH_WINDOWS) == "\\usr\\local\\bin\\"); - - p.parse("/usr/local/lib/../bin/", Path::PATH_WINDOWS); - assert (!p.isRelative()); - assert (p.isAbsolute()); - assert (p.depth() == 3); - assert (p[0] == "usr"); - assert (p[1] == "local"); - assert (p[2] == "bin"); - assert (p.isDirectory()); - assert (!p.isFile()); - assert (p.toString(Path::PATH_WINDOWS) == "\\usr\\local\\bin\\"); - - p.parse("\\usr\\local\\lib\\..\\bin\\", Path::PATH_WINDOWS); - assert (!p.isRelative()); - assert (p.isAbsolute()); - assert (p.depth() == 3); - assert (p[0] == "usr"); - assert (p[1] == "local"); - assert (p[2] == "bin"); - assert (p.isDirectory()); - assert (!p.isFile()); - assert (p.toString(Path::PATH_WINDOWS) == "\\usr\\local\\bin\\"); - - p.parse("/usr/local/lib/../../", Path::PATH_WINDOWS); - assert (!p.isRelative()); - assert (p.isAbsolute()); - assert (p.depth() == 1); - assert (p[0] == "usr"); - assert (p.isDirectory()); - assert (!p.isFile()); - assert (p.toString(Path::PATH_WINDOWS) == "\\usr\\"); - - p.parse("/usr/local/lib/..", Path::PATH_WINDOWS); - assert (!p.isRelative()); - assert (p.isAbsolute()); - assert (p.depth() == 3); - assert (p[0] == "usr"); - assert (p[1] == "local"); - assert (p[2] == "lib"); - assert (!p.isDirectory()); - assert (p.isFile()); - assert (p.toString(Path::PATH_WINDOWS) == "\\usr\\local\\lib\\.."); - - p.parse("../usr/local/lib/", Path::PATH_WINDOWS); - assert (p.isRelative()); - assert (!p.isAbsolute()); - assert (p.depth() == 4); - assert (p[0] == ".."); - assert (p[1] == "usr"); - assert (p[2] == "local"); - assert (p[3] == "lib"); - assert (p.isDirectory()); - assert (!p.isFile()); - assert (p.toString(Path::PATH_WINDOWS) == "..\\usr\\local\\lib\\"); - - p.parse("/usr/../lib/", Path::PATH_WINDOWS); - assert (!p.isRelative()); - assert (p.isAbsolute()); - assert (p.depth() == 1); - assert (p[0] == "lib"); - assert (p.isDirectory()); - assert (!p.isFile()); - assert (p.toString(Path::PATH_WINDOWS) == "\\lib\\"); - - p.parse("/usr/../../lib/", Path::PATH_WINDOWS); - assert (!p.isRelative()); - assert (p.isAbsolute()); - assert (p.depth() == 1); - assert (p[0] == "lib"); - assert (p.isDirectory()); - assert (!p.isFile()); - assert (p.toString(Path::PATH_WINDOWS) == "\\lib\\"); - - p.parse("local/../../lib/", Path::PATH_WINDOWS); - assert (p.isRelative()); - assert (!p.isAbsolute()); - assert (p.depth() == 2); - assert (p[0] == ".."); - assert (p[1] == "lib"); - assert (p.isDirectory()); - assert (!p.isFile()); - assert (p.toString(Path::PATH_WINDOWS) == "..\\lib\\"); -} - - -void PathTest::testParseWindows4() -{ - Path p; - p.parse("\\\\server\\files", Path::PATH_WINDOWS); - assert (!p.isRelative()); - assert (p.isAbsolute()); - assert (p.depth() == 1); - assert (p[0] == "files"); - assert (p.getNode() == "server"); - assert (p.isDirectory()); - assert (!p.isFile()); - assert (p.toString(Path::PATH_WINDOWS) == "\\\\server\\files\\"); - - p.parse("\\\\server\\files\\", Path::PATH_WINDOWS); - assert (!p.isRelative()); - assert (p.isAbsolute()); - assert (p.depth() == 1); - assert (p[0] == "files"); - assert (p.getNode() == "server"); - assert (p.isDirectory()); - assert (!p.isFile()); - assert (p.toString(Path::PATH_WINDOWS) == "\\\\server\\files\\"); - - p.parse("\\\\server\\files\\file", Path::PATH_WINDOWS); - assert (!p.isRelative()); - assert (p.isAbsolute()); - assert (p.depth() == 1); - assert (p[0] == "files"); - assert (p.getNode() == "server"); - assert (!p.isDirectory()); - assert (p.isFile()); - assert (p.toString(Path::PATH_WINDOWS) == "\\\\server\\files\\file"); - - p.parse("\\\\server\\files\\dir\\file", Path::PATH_WINDOWS); - assert (!p.isRelative()); - assert (p.isAbsolute()); - assert (p.depth() == 2); - assert (p[0] == "files"); - assert (p[1] == "dir"); - assert (p.getNode() == "server"); - assert (!p.isDirectory()); - assert (p.isFile()); - assert (p.toString(Path::PATH_WINDOWS) == "\\\\server\\files\\dir\\file"); - - p.parse("\\\\server\\files\\dir\\file", Path::PATH_WINDOWS); - assert (!p.isRelative()); - assert (p.isAbsolute()); - assert (p.depth() == 2); - assert (p[0] == "files"); - assert (p[1] == "dir"); - assert (p.getNode() == "server"); - assert (!p.isDirectory()); - assert (p.isFile()); - assert (p.toString(Path::PATH_WINDOWS) == "\\\\server\\files\\dir\\file"); - - p.parse("\\\\server", Path::PATH_WINDOWS); - assert (!p.isRelative()); - assert (p.isAbsolute()); - assert (p.depth() == 0); - assert (p.getNode() == "server"); - assert (p.isDirectory()); - assert (!p.isFile()); - assert (p.toString(Path::PATH_WINDOWS) == "\\\\server\\"); - - p.parse("c:\\", Path::PATH_WINDOWS); - assert (!p.isRelative()); - assert (p.isAbsolute()); - assert (p.depth() == 0); - assert (p.getDevice() == "c"); - assert (p.isDirectory()); - assert (!p.isFile()); - assert (p.toString(Path::PATH_WINDOWS) == "c:\\"); - - p.parse("c:\\WinNT", Path::PATH_WINDOWS); - assert (!p.isRelative()); - assert (p.isAbsolute()); - assert (p.depth() == 0); - assert (p.getDevice() == "c"); - assert (!p.isDirectory()); - assert (p.isFile()); - assert (p.toString(Path::PATH_WINDOWS) == "c:\\WinNT"); - - p.parse("c:\\WinNT\\", Path::PATH_WINDOWS); - assert (!p.isRelative()); - assert (p.isAbsolute()); - assert (p.depth() == 1); - assert (p[0] == "WinNT"); - assert (p.getDevice() == "c"); - assert (p.isDirectory()); - assert (!p.isFile()); - assert (p.toString(Path::PATH_WINDOWS) == "c:\\WinNT\\"); - - try - { - p.parse("ü:\\", Path::PATH_WINDOWS); - fail("bad path - must throw exception"); - } - catch (PathSyntaxException&) - { - } - - try - { - p.parse("c:file.txt", Path::PATH_WINDOWS); - fail("bad path - must throw exception"); - } - catch (PathSyntaxException&) - { - } - - p.parse("a\\b\\c\\d", Path::PATH_WINDOWS); - assert (p.isRelative()); - assert (!p.isAbsolute()); - assert (p.depth() == 3); - assert (p[0] == "a"); - assert (p[1] == "b"); - assert (p[2] == "c"); - assert (!p.isDirectory()); - assert (p.isFile()); - assert (p.toString(Path::PATH_WINDOWS) == "a\\b\\c\\d"); -} - - -void PathTest::testParseVMS1() -{ - Path p; - p.parse("", Path::PATH_VMS); - assert (p.isRelative()); - assert (!p.isAbsolute()); - assert (p.depth() == 0); - assert (p.isDirectory()); - assert (!p.isFile()); - assert (p.toString(Path::PATH_VMS) == ""); - - p.parse("[]", Path::PATH_VMS); - assert (p.isRelative()); - assert (!p.isAbsolute()); - assert (p.depth() == 0); - assert (p.isDirectory()); - assert (!p.isFile()); - assert (p.toString(Path::PATH_VMS) == ""); - - p.parse("[foo]", Path::PATH_VMS); - assert (!p.isRelative()); - assert (p.isAbsolute()); - assert (p.depth() == 1); - assert (p[0] == "foo"); - assert (p.isDirectory()); - assert (!p.isFile()); - assert (p.toString(Path::PATH_VMS) == "[foo]"); - - p.parse("[.foo]", Path::PATH_VMS); - assert (p.isRelative()); - assert (!p.isAbsolute()); - assert (p.depth() == 1); - assert (p[0] == "foo"); - assert (p.isDirectory()); - assert (!p.isFile()); - assert (p.toString(Path::PATH_VMS) == "[.foo]"); - - p.parse("[foo.bar]", Path::PATH_VMS); - assert (!p.isRelative()); - assert (p.isAbsolute()); - assert (p.depth() == 2); - assert (p[0] == "foo"); - assert (p[1] == "bar"); - assert (p.isDirectory()); - assert (!p.isFile()); - assert (p.toString(Path::PATH_VMS) == "[foo.bar]"); - - p.parse("[.foo.bar]", Path::PATH_VMS); - assert (p.isRelative()); - assert (!p.isAbsolute()); - assert (p.depth() == 2); - assert (p[0] == "foo"); - assert (p[1] == "bar"); - assert (p.isDirectory()); - assert (!p.isFile()); - assert (p.toString(Path::PATH_VMS) == "[.foo.bar]"); - - p.parse("[foo.bar.foobar]", Path::PATH_VMS); - assert (!p.isRelative()); - assert (p.isAbsolute()); - assert (p.depth() == 3); - assert (p[0] == "foo"); - assert (p[1] == "bar"); - assert (p[2] == "foobar"); - assert (p.isDirectory()); - assert (!p.isFile()); - assert (p.toString(Path::PATH_VMS) == "[foo.bar.foobar]"); - - p.parse("[.foo.bar.foobar]", Path::PATH_VMS); - assert (p.isRelative()); - assert (!p.isAbsolute()); - assert (p.depth() == 3); - assert (p[0] == "foo"); - assert (p[1] == "bar"); - assert (p[2] == "foobar"); - assert (p.isDirectory()); - assert (!p.isFile()); - assert (p.toString(Path::PATH_VMS) == "[.foo.bar.foobar]"); -} - - -void PathTest::testParseVMS2() -{ - Path p; - p.parse("[foo][bar]", Path::PATH_VMS); - assert (!p.isRelative()); - assert (p.isAbsolute()); - assert (p.depth() == 2); - assert (p[0] == "foo"); - assert (p[1] == "bar"); - assert (p.isDirectory()); - assert (!p.isFile()); - assert (p.toString(Path::PATH_VMS) == "[foo.bar]"); - - p.parse("[foo.][bar]", Path::PATH_VMS); - assert (!p.isRelative()); - assert (p.isAbsolute()); - assert (p.depth() == 2); - assert (p[0] == "foo"); - assert (p[1] == "bar"); - assert (p.isDirectory()); - assert (!p.isFile()); - assert (p.toString(Path::PATH_VMS) == "[foo.bar]"); - - p.parse("[foo.bar][foo]", Path::PATH_VMS); - assert (!p.isRelative()); - assert (p.isAbsolute()); - assert (p.depth() == 3); - assert (p[0] == "foo"); - assert (p[1] == "bar"); - assert (p[2] == "foo"); - assert (p.isDirectory()); - assert (!p.isFile()); - assert (p.toString(Path::PATH_VMS) == "[foo.bar.foo]"); - - try - { - p.parse("[foo.bar][.foo]", Path::PATH_VMS); - failmsg("bad path - must throw exception"); - } - catch (PathSyntaxException&) - { - } - - try - { - p.parse("[.foo.bar][foo]", Path::PATH_VMS); - failmsg("bad path - must throw exception"); - } - catch (PathSyntaxException&) - { - } - - p.parse("[-]", Path::PATH_VMS); - assert (p.isRelative()); - assert (!p.isAbsolute()); - assert (p.depth() == 1); - assert (p[0] == ".."); - assert (p.isDirectory()); - assert (!p.isFile()); - assert (p.toString(Path::PATH_VMS) == "[-]"); - - p.parse("[--]", Path::PATH_VMS); - assert (p.isRelative()); - assert (!p.isAbsolute()); - assert (p.depth() == 2); - assert (p[0] == ".."); - assert (p[1] == ".."); - assert (p.isDirectory()); - assert (!p.isFile()); - assert (p.toString(Path::PATH_VMS) == "[--]"); - - p.parse("[---]", Path::PATH_VMS); - assert (p.isRelative()); - assert (!p.isAbsolute()); - assert (p.depth() == 3); - assert (p[0] == ".."); - assert (p[1] == ".."); - assert (p[2] == ".."); - assert (p.isDirectory()); - assert (!p.isFile()); - assert (p.toString(Path::PATH_VMS) == "[---]"); - - p.parse("[-.-]", Path::PATH_VMS); - assert (p.isRelative()); - assert (!p.isAbsolute()); - assert (p.depth() == 2); - assert (p[0] == ".."); - assert (p[1] == ".."); - assert (p.isDirectory()); - assert (!p.isFile()); - assert (p.toString(Path::PATH_VMS) == "[--]"); - - p.parse("[.-.-]", Path::PATH_VMS); - assert (p.isRelative()); - assert (!p.isAbsolute()); - assert (p.depth() == 2); - assert (p[0] == ".."); - assert (p[1] == ".."); - assert (p.isDirectory()); - assert (!p.isFile()); - assert (p.toString(Path::PATH_VMS) == "[--]"); - - p.parse("[-.-.-]", Path::PATH_VMS); - assert (p.isRelative()); - assert (!p.isAbsolute()); - assert (p.depth() == 3); - assert (p[0] == ".."); - assert (p[1] == ".."); - assert (p[2] == ".."); - assert (p.isDirectory()); - assert (!p.isFile()); - assert (p.toString(Path::PATH_VMS) == "[---]"); - - p.parse("[.-.-.-]", Path::PATH_VMS); - assert (p.isRelative()); - assert (!p.isAbsolute()); - assert (p.depth() == 3); - assert (p[0] == ".."); - assert (p[1] == ".."); - assert (p[2] == ".."); - assert (p.isDirectory()); - assert (!p.isFile()); - assert (p.toString(Path::PATH_VMS) == "[---]"); - - p.parse("[.--.-]", Path::PATH_VMS); - assert (p.isRelative()); - assert (!p.isAbsolute()); - assert (p.depth() == 3); - assert (p[0] == ".."); - assert (p[1] == ".."); - assert (p[2] == ".."); - assert (p.isDirectory()); - assert (!p.isFile()); - assert (p.toString(Path::PATH_VMS) == "[---]"); - - p.parse("[--.-]", Path::PATH_VMS); - assert (p.isRelative()); - assert (!p.isAbsolute()); - assert (p.depth() == 3); - assert (p[0] == ".."); - assert (p[1] == ".."); - assert (p[2] == ".."); - assert (p.isDirectory()); - assert (!p.isFile()); - assert (p.toString(Path::PATH_VMS) == "[---]"); -} - - -void PathTest::testParseVMS3() -{ - Path p; - p.parse("[foo][-]", Path::PATH_VMS); - assert (!p.isRelative()); - assert (p.isAbsolute()); - assert (p.depth() == 1); - assert (p[0] == "foo"); - assert (p.isDirectory()); - assert (!p.isFile()); - assert (p.toString(Path::PATH_VMS) == "[foo]"); - - p.parse("[foo][--]", Path::PATH_VMS); - assert (!p.isRelative()); - assert (p.isAbsolute()); - assert (p.depth() == 1); - assert (p[0] == "foo"); - assert (p.isDirectory()); - assert (!p.isFile()); - assert (p.toString(Path::PATH_VMS) == "[foo]"); - - p.parse("[foo][-.-]", Path::PATH_VMS); - assert (!p.isRelative()); - assert (p.isAbsolute()); - assert (p.depth() == 1); - assert (p[0] == "foo"); - assert (p.isDirectory()); - assert (!p.isFile()); - assert (p.toString(Path::PATH_VMS) == "[foo]"); - - p.parse("[foo][bar.-]", Path::PATH_VMS); - assert (!p.isRelative()); - assert (p.isAbsolute()); - assert (p.depth() == 1); - assert (p[0] == "foo"); - assert (p.isDirectory()); - assert (!p.isFile()); - assert (p.toString(Path::PATH_VMS) == "[foo]"); - - p.parse("[foo][bar.foo.-]", Path::PATH_VMS); - assert (!p.isRelative()); - assert (p.isAbsolute()); - assert (p.depth() == 2); - assert (p[0] == "foo"); - assert (p[1] == "bar"); - assert (p.isDirectory()); - assert (!p.isFile()); - assert (p.toString(Path::PATH_VMS) == "[foo.bar]"); - - p.parse("[foo][bar.foo.--]", Path::PATH_VMS); - assert (!p.isRelative()); - assert (p.isAbsolute()); - assert (p.depth() == 1); - assert (p[0] == "foo"); - assert (p.isDirectory()); - assert (!p.isFile()); - assert (p.toString(Path::PATH_VMS) == "[foo]"); - - p.parse("[foo][bar.foo.---]", Path::PATH_VMS); - assert (!p.isRelative()); - assert (p.isAbsolute()); - assert (p.depth() == 1); - assert (p[0] == "foo"); - assert (p.isDirectory()); - assert (!p.isFile()); - assert (p.toString(Path::PATH_VMS) == "[foo]"); - - p.parse("[foo][bar.foo.-.-.-]", Path::PATH_VMS); - assert (!p.isRelative()); - assert (p.isAbsolute()); - assert (p.depth() == 1); - assert (p[0] == "foo"); - assert (p.isDirectory()); - assert (!p.isFile()); - assert (p.toString(Path::PATH_VMS) == "[foo]"); -} - - -void PathTest::testParseVMS4() -{ - Path p; - p.parse("device:[foo]", Path::PATH_VMS); - assert (!p.isRelative()); - assert (p.isAbsolute()); - assert (p.depth() == 1); - assert (p[0] == "foo"); - assert (p.getDevice() == "device"); - assert (p.isDirectory()); - assert (!p.isFile()); - assert (p.toString(Path::PATH_VMS) == "device:[foo]"); - - p.parse("device:[.foo]", Path::PATH_VMS); - assert (p.isRelative()); - assert (!p.isAbsolute()); - assert (p.depth() == 1); - assert (p[0] == "foo"); - assert (p.getDevice() == "device"); - assert (p.isDirectory()); - assert (!p.isFile()); - assert (p.toString(Path::PATH_VMS) == "device:[.foo]"); - - p.parse("node::device:[foo]", Path::PATH_VMS); - assert (!p.isRelative()); - assert (p.isAbsolute()); - assert (p.depth() == 1); - assert (p[0] == "foo"); - assert (p.getNode() == "node"); - assert (p.getDevice() == "device"); - assert (p.isDirectory()); - assert (!p.isFile()); - assert (p.toString(Path::PATH_VMS) == "node::device:[foo]"); - - p.parse("node::device:[foo.bar]", Path::PATH_VMS); - assert (!p.isRelative()); - assert (p.isAbsolute()); - assert (p.depth() == 2); - assert (p[0] == "foo"); - assert (p[1] == "bar"); - assert (p.getNode() == "node"); - assert (p.getDevice() == "device"); - assert (p.isDirectory()); - assert (!p.isFile()); - assert (p.toString(Path::PATH_VMS) == "node::device:[foo.bar]"); - - p.parse("node::device:[foo.bar.][goo]", Path::PATH_VMS); - assert (!p.isRelative()); - assert (p.isAbsolute()); - assert (p.depth() == 3); - assert (p[0] == "foo"); - assert (p[1] == "bar"); - assert (p[2] == "goo"); - assert (p.getNode() == "node"); - assert (p.getDevice() == "device"); - assert (p.isDirectory()); - assert (!p.isFile()); - assert (p.toString(Path::PATH_VMS) == "node::device:[foo.bar.goo]"); - - p.parse("[]foo.txt", Path::PATH_VMS); - assert (p.isRelative()); - assert (!p.isAbsolute()); - assert (p.depth() == 0); - assert (!p.isDirectory()); - assert (p.isFile()); - assert (p.toString(Path::PATH_VMS) == "foo.txt"); - - p.parse("[foo]bar.txt", Path::PATH_VMS); - assert (!p.isRelative()); - assert (p.isAbsolute()); - assert (p.depth() == 1); - assert (p[0] == "foo"); - assert (!p.isDirectory()); - assert (p.isFile()); - assert (p.toString(Path::PATH_VMS) == "[foo]bar.txt"); - - p.parse("[foo]bar.txt;", Path::PATH_VMS); - assert (!p.isRelative()); - assert (p.isAbsolute()); - assert (p.depth() == 1); - assert (p[0] == "foo"); - assert (!p.isDirectory()); - assert (p.isFile()); - assert (p.toString(Path::PATH_VMS) == "[foo]bar.txt"); - - p.parse("[foo]bar.txt;5", Path::PATH_VMS); - assert (!p.isRelative()); - assert (p.isAbsolute()); - assert (p.depth() == 1); - assert (p[0] == "foo"); - assert (!p.isDirectory()); - assert (p.isFile()); - assert (p.toString(Path::PATH_VMS) == "[foo]bar.txt;5"); - assert (p.version() == "5"); - - p.parse("foo:bar.txt", Path::PATH_VMS); - assert (!p.isRelative()); - assert (p.isAbsolute()); - assert (p.depth() == 0); - assert (p.getDevice() == "foo"); - assert (!p.isDirectory()); - assert (p.isFile()); - assert (p.toString(Path::PATH_VMS) == "foo:bar.txt"); - - p.parse("foo:bar.txt;5", Path::PATH_VMS); - assert (!p.isRelative()); - assert (p.isAbsolute()); - assert (p.depth() == 0); - assert (p.getDevice() == "foo"); - assert (!p.isDirectory()); - assert (p.isFile()); - assert (p.toString(Path::PATH_VMS) == "foo:bar.txt;5"); - assert (p.version() == "5"); - - p.parse("foo:", Path::PATH_VMS); - assert (!p.isRelative()); - assert (p.isAbsolute()); - assert (p.depth() == 0); - assert (p.getDevice() == "foo"); - assert (p.isDirectory()); - assert (!p.isFile()); - assert (p.toString(Path::PATH_VMS) == "foo:"); - - p.parse("bar.txt", Path::PATH_VMS); - assert (p.isRelative()); - assert (!p.isAbsolute()); - assert (p.depth() == 0); - assert (!p.isDirectory()); - assert (p.isFile()); - assert (p.toString(Path::PATH_VMS) == "bar.txt"); - - p.parse("bar.txt;5", Path::PATH_VMS); - assert (p.isRelative()); - assert (!p.isAbsolute()); - assert (p.depth() == 0); - assert (!p.isDirectory()); - assert (p.isFile()); - assert (p.toString(Path::PATH_VMS) == "bar.txt;5"); - assert (p.version() == "5"); -} - - -void PathTest::testParseGuess() -{ - Path p; - - p.parse("foo:bar.txt;5", Path::PATH_GUESS); - assert (!p.isRelative()); - assert (p.isAbsolute()); - assert (p.depth() == 0); - assert (p.getDevice() == "foo"); - assert (!p.isDirectory()); - assert (p.isFile()); - assert (p.toString(Path::PATH_VMS) == "foo:bar.txt;5"); - assert (p.version() == "5"); - - p.parse("/usr/local/bin", Path::PATH_GUESS); - assert (!p.isRelative()); - assert (p.isAbsolute()); - assert (p.depth() == 2); - assert (p[0] == "usr"); - assert (p[1] == "local"); - assert (p[2] == "bin"); - assert (!p.isDirectory()); - assert (p.isFile()); - assert (p.toString(Path::PATH_UNIX) == "/usr/local/bin"); - - p.parse("\\\\server\\files", Path::PATH_GUESS); - assert (!p.isRelative()); - assert (p.isAbsolute()); - assert (p.depth() == 1); - assert (p[0] == "files"); - assert (p.getNode() == "server"); - assert (p.isDirectory()); - assert (!p.isFile()); - assert (p.toString(Path::PATH_WINDOWS) == "\\\\server\\files\\"); - - p.parse("c:\\WinNT", Path::PATH_GUESS); - assert (!p.isRelative()); - assert (p.isAbsolute()); - assert (p.depth() == 0); - assert (p.getDevice() == "c"); - assert (!p.isDirectory()); - assert (p.isFile()); - assert (p.toString(Path::PATH_WINDOWS) == "c:\\WinNT"); - - p.parse("foo:bar.txt;5", Path::PATH_GUESS); - assert (!p.isRelative()); - assert (p.isAbsolute()); - assert (p.depth() == 0); - assert (p.getDevice() == "foo"); - assert (!p.isDirectory()); - assert (p.isFile()); - assert (p.toString(Path::PATH_VMS) == "foo:bar.txt;5"); - assert (p.version() == "5"); - - p.parse("[foo]bar.txt", Path::PATH_GUESS); - assert (!p.isRelative()); - assert (p.isAbsolute()); - assert (p.depth() == 1); - assert (p[0] == "foo"); - assert (!p.isDirectory()); - assert (p.isFile()); - assert (p.toString(Path::PATH_VMS) == "[foo]bar.txt"); -} - - -void PathTest::testTryParse() -{ - Path p; -#if defined(POCO_OS_FAMILY_UNIX) - assert (p.tryParse("/etc/passwd")); - assert (p.toString() == "/etc/passwd"); -#elif defined(POCO_OS_FAMILY_WINDOWS) - assert (p.tryParse("c:\\windows\\system32")); - assert (p.toString() == "c:\\windows\\system32"); - assert (!p.tryParse("c:foo.bar")); - assert (p.toString() == "c:\\windows\\system32"); -#endif - - assert (p.tryParse("c:\\windows\\system", Path::PATH_WINDOWS)); - assert (p.toString(Path::PATH_WINDOWS) == "c:\\windows\\system"); - assert (!p.tryParse("c:foo.bar", Path::PATH_WINDOWS)); - assert (p.toString(Path::PATH_WINDOWS) == "c:\\windows\\system"); -} - - -void PathTest::testStatics() -{ - std::string s = Path::current(); - assert (!s.empty()); - Path p(s); - assert (p.isDirectory() && p.isAbsolute()); - - s = Path::home(); - assert (!s.empty()); - p = s; - assert (p.isDirectory() && p.isAbsolute()); - - s = Path::temp(); - assert (!s.empty()); - p = s; - assert (p.isDirectory() && p.isAbsolute()); - - s = Path::null(); - assert (!s.empty()); - p = s; -} - - -void PathTest::testBaseNameExt() -{ - Path p("foo.bar"); - assert (p.getFileName() == "foo.bar"); - assert (p.getBaseName() == "foo"); - assert (p.getExtension() == "bar"); - - p.setBaseName("readme"); - assert (p.getFileName() == "readme.bar"); - assert (p.getBaseName() == "readme"); - assert (p.getExtension() == "bar"); - - p.setExtension("txt"); - assert (p.getFileName() == "readme.txt"); - assert (p.getBaseName() == "readme"); - assert (p.getExtension() == "txt"); - - p.setExtension("html"); - assert (p.getFileName() == "readme.html"); - assert (p.getBaseName() == "readme"); - assert (p.getExtension() == "html"); - - p.setBaseName("index"); - assert (p.getFileName() == "index.html"); - assert (p.getBaseName() == "index"); - assert (p.getExtension() == "html"); -} - - -void PathTest::testAbsolute() -{ - Path base("C:\\Program Files\\", Path::PATH_WINDOWS); - Path rel("Poco"); - Path abs = rel.absolute(base); - assert (abs.toString(Path::PATH_WINDOWS) == "C:\\Program Files\\Poco"); - - base.parse("/usr/local", Path::PATH_UNIX); - rel.parse("Poco/include", Path::PATH_UNIX); - abs = rel.absolute(base); - assert (abs.toString(Path::PATH_UNIX) == "/usr/local/Poco/include"); - - base.parse("/usr/local/bin", Path::PATH_UNIX); - rel.parse("../Poco/include", Path::PATH_UNIX); - abs = rel.absolute(base); - assert (abs.toString(Path::PATH_UNIX) == "/usr/local/Poco/include"); -} - - -void PathTest::testRobustness() -{ - Random r; - for (int i = 0; i < 256; ++i) - { - int len = r.next(1024); - std::string s; - for (int i = 0; i < len; ++i) s += r.nextChar(); - try - { - Path p(s, Path::PATH_WINDOWS); - } - catch (PathSyntaxException&) - { - } - try - { - Path p(s, Path::PATH_UNIX); - } - catch (PathSyntaxException&) - { - } - try - { - Path p(s, Path::PATH_VMS); - } - catch (PathSyntaxException&) - { - } - try - { - Path p(s, Path::PATH_GUESS); - } - catch (PathSyntaxException&) - { - } - } -} - - -void PathTest::testParent() -{ - Path p("/usr/local/include", Path::PATH_UNIX); - p.makeParent(); - assert (p.toString(Path::PATH_UNIX) == "/usr/local/"); - p.makeParent(); - assert (p.toString(Path::PATH_UNIX) == "/usr/"); - p.makeParent(); - assert (p.toString(Path::PATH_UNIX) == "/"); - p.makeParent(); - assert (p.toString(Path::PATH_UNIX) == "/"); -} - - -void PathTest::testForDirectory() -{ - Path p = Path::forDirectory("/usr/local/include", Path::PATH_UNIX); - assert (p.toString(Path::PATH_UNIX) == "/usr/local/include/"); - - p = Path::forDirectory("/usr/local/include/", Path::PATH_UNIX); - assert (p.toString(Path::PATH_UNIX) == "/usr/local/include/"); -} - - -void PathTest::testExpand() -{ -#if defined(POCO_OS_FAMILY_UNIX) - std::string s = Path::expand("~/.bashrc"); - assert (s == Path::expand("$HOME/.bashrc")); - assert (s == Environment::get("HOME") + "/.bashrc" || - s == Environment::get("HOME") + "//.bashrc"); - Path p(s); - s = Path::expand("$HOME/.bashrc"); - assert (s == Path::expand("~/.bashrc")); - s = Path::expand("${HOME}/.bashrc"); - assert (s == Path::expand("~/.bashrc")); -#elif defined(POCO_OS_FAMILY_WINDOWS) - std::string s = Path::expand("%TMP%\\foo"); - assert (s == Environment::get("TMP") + "\\foo"); - Path p(s); -#else - std::string s = Path::expand("SYS$LOGIN:[projects]"); - assert (s.find(":[projects]") != std::string::npos); - Path p(s); -#endif -} - - -void PathTest::testListRoots() -{ - std::vector devs; - Path::listRoots(devs); - assert (devs.size() > 0); - for (std::vector::iterator it = devs.begin(); it != devs.end(); ++it) - { - std::cout << *it << std::endl; - } -} - - -void PathTest::testFind() -{ - Path p; -#if defined(POCO_OS_FAMILY_UNIX) - bool found = Path::find(Environment::get("PATH"), "ls", p); - bool notfound = Path::find(Environment::get("PATH"), "xxxyyy123", p); -#elif defined(POCO_OS_FAMILY_WINDOWS) - bool found = Path::find(Environment::get("PATH"), "cmd.exe", p); - bool notfound = Path::find(Environment::get("PATH"), "xxxyyy123.zzz", p); -#else - bool found = true; - bool notfound = false; -#endif - assert (found); - assert (!notfound); - - std::string fn = p.toString(); - assert (fn.size() > 0); -} - - -void PathTest::testSwap() -{ - Path p1("c:\\temp\\foo.bar"); - Path p2("\\\\server\\files\\foo.bar"); - p1.swap(p2); - assert (p1.toString() == "\\\\server\\files\\foo.bar"); - assert (p2.toString() == "c:\\temp\\foo.bar"); -} - - -void PathTest::testResolve() -{ - Path p("c:\\foo\\", Path::PATH_WINDOWS); - p.resolve("test.dat"); - assert (p.toString(Path::PATH_WINDOWS) == "c:\\foo\\test.dat"); - - p.assign("c:\\foo\\", Path::PATH_WINDOWS); - p.resolve(Path("d:\\bar.txt", Path::PATH_WINDOWS)); - assert (p.toString(Path::PATH_WINDOWS) == "d:\\bar.txt"); - - p.assign("c:\\foo\\bar.txt", Path::PATH_WINDOWS); - p.resolve("foo.txt"); - assert (p.toString(Path::PATH_WINDOWS) == "c:\\foo\\foo.txt"); - - p.assign("c:\\foo\\bar\\", Path::PATH_WINDOWS); - p.resolve(Path("..\\baz\\test.dat", Path::PATH_WINDOWS)); - assert (p.toString(Path::PATH_WINDOWS) == "c:\\foo\\baz\\test.dat"); -} - - -void PathTest::setUp() -{ -} - - -void PathTest::tearDown() -{ -} - - -CppUnit::Test* PathTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("PathTest"); - - CppUnit_addTest(pSuite, PathTest, testParseUnix1); - CppUnit_addTest(pSuite, PathTest, testParseUnix2); - CppUnit_addTest(pSuite, PathTest, testParseUnix3); - CppUnit_addTest(pSuite, PathTest, testParseUnix4); - CppUnit_addTest(pSuite, PathTest, testParseUnix5); - CppUnit_addTest(pSuite, PathTest, testParseWindows1); - CppUnit_addTest(pSuite, PathTest, testParseWindows2); - CppUnit_addTest(pSuite, PathTest, testParseWindows3); - CppUnit_addTest(pSuite, PathTest, testParseWindows4); - CppUnit_addTest(pSuite, PathTest, testParseVMS1); - CppUnit_addTest(pSuite, PathTest, testParseVMS2); - CppUnit_addTest(pSuite, PathTest, testParseVMS3); - CppUnit_addTest(pSuite, PathTest, testParseVMS4); - CppUnit_addTest(pSuite, PathTest, testParseGuess); - CppUnit_addTest(pSuite, PathTest, testTryParse); - CppUnit_addTest(pSuite, PathTest, testStatics); - CppUnit_addTest(pSuite, PathTest, testBaseNameExt); - CppUnit_addTest(pSuite, PathTest, testAbsolute); - CppUnit_addTest(pSuite, PathTest, testRobustness); - CppUnit_addTest(pSuite, PathTest, testParent); - CppUnit_addTest(pSuite, PathTest, testForDirectory); - CppUnit_addTest(pSuite, PathTest, testExpand); - CppUnit_addTest(pSuite, PathTest, testListRoots); - CppUnit_addTest(pSuite, PathTest, testFind); - CppUnit_addTest(pSuite, PathTest, testSwap); - CppUnit_addTest(pSuite, PathTest, testResolve); - - return pSuite; -} +// +// PathTest.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/PathTest.cpp#1 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "PathTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/Path.h" +#include "Poco/Exception.h" +#include "Poco/Random.h" +#include "Poco/Environment.h" +#include + + +using Poco::Path; +using Poco::PathSyntaxException; +using Poco::Random; +using Poco::Environment; + + +PathTest::PathTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +PathTest::~PathTest() +{ +} + + +void PathTest::testParseUnix1() +{ + Path p; + p.parse("", Path::PATH_UNIX); + assert (p.isRelative()); + assert (!p.isAbsolute()); + assert (p.depth() == 0); + assert (p.isDirectory()); + assert (!p.isFile()); + assert (p.toString(Path::PATH_UNIX) == ""); + + p.parse("/", Path::PATH_UNIX); + assert (!p.isRelative()); + assert (p.isAbsolute()); + assert (p.depth() == 0); + assert (p.isDirectory()); + assert (!p.isFile()); + assert (p.toString(Path::PATH_UNIX) == "/"); + + p.parse("/usr", Path::PATH_UNIX); + assert (!p.isRelative()); + assert (p.isAbsolute()); + assert (p.depth() == 0); + assert (!p.isDirectory()); + assert (p.isFile()); + assert (p.toString(Path::PATH_UNIX) == "/usr"); + + p.parse("/usr/", Path::PATH_UNIX); + assert (!p.isRelative()); + assert (p.isAbsolute()); + assert (p.depth() == 1); + assert (p[0] == "usr"); + assert (p.isDirectory()); + assert (!p.isFile()); + assert (p.toString(Path::PATH_UNIX) == "/usr/"); + + p.parse("usr/", Path::PATH_UNIX); + assert (p.isRelative()); + assert (!p.isAbsolute()); + assert (p.depth() == 1); + assert (p[0] == "usr"); + assert (p.isDirectory()); + assert (!p.isFile()); + assert (p.toString(Path::PATH_UNIX) == "usr/"); + + p.parse("usr", Path::PATH_UNIX); + assert (p.isRelative()); + assert (!p.isAbsolute()); + assert (p.depth() == 0); + assert (p[0] == "usr"); + assert (!p.isDirectory()); + assert (p.isFile()); + assert (p.toString(Path::PATH_UNIX) == "usr"); + + p.parse("/usr/local", Path::PATH_UNIX); + assert (!p.isRelative()); + assert (p.isAbsolute()); + assert (p.depth() == 1); + assert (p[0] == "usr"); + assert (p[1] == "local"); + assert (!p.isDirectory()); + assert (p.isFile()); + assert (p.toString(Path::PATH_UNIX) == "/usr/local"); +} + + +void PathTest::testParseUnix2() +{ + Path p; + p.parse("/usr/local/", Path::PATH_UNIX); + assert (!p.isRelative()); + assert (p.isAbsolute()); + assert (p.depth() == 2); + assert (p[0] == "usr"); + assert (p[1] == "local"); + assert (p.isDirectory()); + assert (!p.isFile()); + assert (p.toString(Path::PATH_UNIX) == "/usr/local/"); + + p.parse("usr/local/", Path::PATH_UNIX); + assert (p.isRelative()); + assert (!p.isAbsolute()); + assert (p.depth() == 2); + assert (p[0] == "usr"); + assert (p[1] == "local"); + assert (p.isDirectory()); + assert (!p.isFile()); + assert (p.toString(Path::PATH_UNIX) == "usr/local/"); + + p.parse("usr/local", Path::PATH_UNIX); + assert (p.isRelative()); + assert (!p.isAbsolute()); + assert (p.depth() == 1); + assert (p[0] == "usr"); + assert (p[1] == "local"); + assert (!p.isDirectory()); + assert (p.isFile()); + assert (p.toString(Path::PATH_UNIX) == "usr/local"); + + p.parse("/usr/local/bin", Path::PATH_UNIX); + assert (!p.isRelative()); + assert (p.isAbsolute()); + assert (p.depth() == 2); + assert (p[0] == "usr"); + assert (p[1] == "local"); + assert (p[2] == "bin"); + assert (!p.isDirectory()); + assert (p.isFile()); + assert (p.toString(Path::PATH_UNIX) == "/usr/local/bin"); + + p.parse("/usr/local/bin/", Path::PATH_UNIX); + assert (!p.isRelative()); + assert (p.isAbsolute()); + assert (p.depth() == 3); + assert (p[0] == "usr"); + assert (p[1] == "local"); + assert (p[2] == "bin"); + assert (p.isDirectory()); + assert (!p.isFile()); + assert (p.toString(Path::PATH_UNIX) == "/usr/local/bin/"); +} + + +void PathTest::testParseUnix3() +{ + Path p; + p.parse("//usr/local/bin/", Path::PATH_UNIX); + assert (!p.isRelative()); + assert (p.isAbsolute()); + assert (p.depth() == 3); + assert (p[0] == "usr"); + assert (p[1] == "local"); + assert (p[2] == "bin"); + assert (p.isDirectory()); + assert (!p.isFile()); + assert (p.toString(Path::PATH_UNIX) == "/usr/local/bin/"); + + p.parse("/usr//local/bin/", Path::PATH_UNIX); + assert (!p.isRelative()); + assert (p.isAbsolute()); + assert (p.depth() == 3); + assert (p[0] == "usr"); + assert (p[1] == "local"); + assert (p[2] == "bin"); + assert (p.isDirectory()); + assert (!p.isFile()); + assert (p.toString(Path::PATH_UNIX) == "/usr/local/bin/"); + + p.parse("/usr/local//bin/", Path::PATH_UNIX); + assert (!p.isRelative()); + assert (p.isAbsolute()); + assert (p.depth() == 3); + assert (p[0] == "usr"); + assert (p[1] == "local"); + assert (p[2] == "bin"); + assert (p.isDirectory()); + assert (!p.isFile()); + assert (p.toString(Path::PATH_UNIX) == "/usr/local/bin/"); + + p.parse("/usr/local/bin//", Path::PATH_UNIX); + assert (!p.isRelative()); + assert (p.isAbsolute()); + assert (p.depth() == 3); + assert (p[0] == "usr"); + assert (p[1] == "local"); + assert (p[2] == "bin"); + assert (p.isDirectory()); + assert (!p.isFile()); + assert (p.toString(Path::PATH_UNIX) == "/usr/local/bin/"); + + p.parse("/usr/local/./bin/", Path::PATH_UNIX); + assert (!p.isRelative()); + assert (p.isAbsolute()); + assert (p.depth() == 3); + assert (p[0] == "usr"); + assert (p[1] == "local"); + assert (p[2] == "bin"); + assert (p.isDirectory()); + assert (!p.isFile()); + assert (p.toString(Path::PATH_UNIX) == "/usr/local/bin/"); + + p.parse("./usr/local/bin/", Path::PATH_UNIX); + assert (p.isRelative()); + assert (!p.isAbsolute()); + assert (p.depth() == 3); + assert (p[0] == "usr"); + assert (p[1] == "local"); + assert (p[2] == "bin"); + assert (p.isDirectory()); + assert (!p.isFile()); + assert (p.toString(Path::PATH_UNIX) == "usr/local/bin/"); + + p.parse("./usr/local/bin/./", Path::PATH_UNIX); + assert (p.isRelative()); + assert (!p.isAbsolute()); + assert (p.depth() == 3); + assert (p[0] == "usr"); + assert (p[1] == "local"); + assert (p[2] == "bin"); + assert (p.isDirectory()); + assert (!p.isFile()); + assert (p.toString(Path::PATH_UNIX) == "usr/local/bin/"); + + p.parse("./usr/local/bin/.", Path::PATH_UNIX); + assert (p.isRelative()); + assert (!p.isAbsolute()); + assert (p.depth() == 3); + assert (p[0] == "usr"); + assert (p[1] == "local"); + assert (p[2] == "bin"); + assert (!p.isDirectory()); + assert (p.isFile()); + assert (p.toString(Path::PATH_UNIX) == "usr/local/bin/."); +} + + +void PathTest::testParseUnix4() +{ + Path p; + p.parse("/usr/local/lib/../bin/", Path::PATH_UNIX); + assert (!p.isRelative()); + assert (p.isAbsolute()); + assert (p.depth() == 3); + assert (p[0] == "usr"); + assert (p[1] == "local"); + assert (p[2] == "bin"); + assert (p.isDirectory()); + assert (!p.isFile()); + assert (p.toString(Path::PATH_UNIX) == "/usr/local/bin/"); + + p.parse("/usr/local/lib/../bin/", Path::PATH_UNIX); + assert (!p.isRelative()); + assert (p.isAbsolute()); + assert (p.depth() == 3); + assert (p[0] == "usr"); + assert (p[1] == "local"); + assert (p[2] == "bin"); + assert (p.isDirectory()); + assert (!p.isFile()); + assert (p.toString(Path::PATH_UNIX) == "/usr/local/bin/"); + + p.parse("/usr/local/lib/../../", Path::PATH_UNIX); + assert (!p.isRelative()); + assert (p.isAbsolute()); + assert (p.depth() == 1); + assert (p[0] == "usr"); + assert (p.isDirectory()); + assert (!p.isFile()); + assert (p.toString(Path::PATH_UNIX) == "/usr/"); + + p.parse("/usr/local/lib/..", Path::PATH_UNIX); + assert (!p.isRelative()); + assert (p.isAbsolute()); + assert (p.depth() == 3); + assert (p[0] == "usr"); + assert (p[1] == "local"); + assert (p[2] == "lib"); + assert (!p.isDirectory()); + assert (p.isFile()); + assert (p.toString(Path::PATH_UNIX) == "/usr/local/lib/.."); + + p.parse("../usr/local/lib/", Path::PATH_UNIX); + assert (p.isRelative()); + assert (!p.isAbsolute()); + assert (p.depth() == 4); + assert (p[0] == ".."); + assert (p[1] == "usr"); + assert (p[2] == "local"); + assert (p[3] == "lib"); + assert (p.isDirectory()); + assert (!p.isFile()); + assert (p.toString(Path::PATH_UNIX) == "../usr/local/lib/"); + + p.parse("/usr/../lib/", Path::PATH_UNIX); + assert (!p.isRelative()); + assert (p.isAbsolute()); + assert (p.depth() == 1); + assert (p[0] == "lib"); + assert (p.isDirectory()); + assert (!p.isFile()); + assert (p.toString(Path::PATH_UNIX) == "/lib/"); + + p.parse("/usr/../../lib/", Path::PATH_UNIX); + assert (!p.isRelative()); + assert (p.isAbsolute()); + assert (p.depth() == 1); + assert (p[0] == "lib"); + assert (p.isDirectory()); + assert (!p.isFile()); + assert (p.toString(Path::PATH_UNIX) == "/lib/"); + + p.parse("local/../../lib/", Path::PATH_UNIX); + assert (p.isRelative()); + assert (!p.isAbsolute()); + assert (p.depth() == 2); + assert (p[0] == ".."); + assert (p[1] == "lib"); + assert (p.isDirectory()); + assert (!p.isFile()); + assert (p.toString(Path::PATH_UNIX) == "../lib/"); + + p.parse("a/b/c/d", Path::PATH_UNIX); + assert (p.isRelative()); + assert (!p.isAbsolute()); + assert (p.depth() == 3); + assert (p[0] == "a"); + assert (p[1] == "b"); + assert (p[2] == "c"); + assert (!p.isDirectory()); + assert (p.isFile()); + assert (p.toString(Path::PATH_UNIX) == "a/b/c/d"); +} + + +void PathTest::testParseUnix5() +{ + Path p; + p.parse("/c:/windows/system32/", Path::PATH_UNIX); + assert (!p.isRelative()); + assert (p.isAbsolute()); + assert (p.getDevice() == "c"); + assert (p.depth() == 2); + assert (p[0] == "windows"); + assert (p[1] == "system32"); + assert (p.isDirectory()); + assert (!p.isFile()); + assert (p.toString(Path::PATH_UNIX) == "/c:/windows/system32/"); +} + + +void PathTest::testParseWindows1() +{ + Path p; + p.parse("", Path::PATH_WINDOWS); + assert (p.isRelative()); + assert (!p.isAbsolute()); + assert (p.depth() == 0); + assert (p.isDirectory()); + assert (!p.isFile()); + assert (p.toString(Path::PATH_WINDOWS) == ""); + + p.parse("/", Path::PATH_WINDOWS); + assert (!p.isRelative()); + assert (p.isAbsolute()); + assert (p.depth() == 0); + assert (p.isDirectory()); + assert (!p.isFile()); + assert (p.toString(Path::PATH_WINDOWS) == "\\"); + + p.parse("\\", Path::PATH_WINDOWS); + assert (!p.isRelative()); + assert (p.isAbsolute()); + assert (p.depth() == 0); + assert (p.isDirectory()); + assert (!p.isFile()); + assert (p.toString(Path::PATH_WINDOWS) == "\\"); + + p.parse("/usr", Path::PATH_WINDOWS); + assert (!p.isRelative()); + assert (p.isAbsolute()); + assert (p.depth() == 0); + assert (!p.isDirectory()); + assert (p.isFile()); + assert (p.toString(Path::PATH_WINDOWS) == "\\usr"); + + p.parse("\\usr", Path::PATH_WINDOWS); + assert (!p.isRelative()); + assert (p.isAbsolute()); + assert (p.depth() == 0); + assert (!p.isDirectory()); + assert (p.isFile()); + assert (p.toString(Path::PATH_WINDOWS) == "\\usr"); + + p.parse("/usr/", Path::PATH_WINDOWS); + assert (!p.isRelative()); + assert (p.isAbsolute()); + assert (p.depth() == 1); + assert (p[0] == "usr"); + assert (p.isDirectory()); + assert (!p.isFile()); + assert (p.toString(Path::PATH_WINDOWS) == "\\usr\\"); + + p.parse("\\usr\\", Path::PATH_WINDOWS); + assert (!p.isRelative()); + assert (p.isAbsolute()); + assert (p.depth() == 1); + assert (p[0] == "usr"); + assert (p.isDirectory()); + assert (!p.isFile()); + assert (p.toString(Path::PATH_WINDOWS) == "\\usr\\"); +} + + +void PathTest::testParseWindows2() +{ + Path p; + p.parse("usr/", Path::PATH_WINDOWS); + assert (p.isRelative()); + assert (!p.isAbsolute()); + assert (p.depth() == 1); + assert (p[0] == "usr"); + assert (p.isDirectory()); + assert (!p.isFile()); + assert (p.toString(Path::PATH_WINDOWS) == "usr\\"); + + p.parse("usr", Path::PATH_WINDOWS); + assert (p.isRelative()); + assert (!p.isAbsolute()); + assert (p.depth() == 0); + assert (p[0] == "usr"); + assert (!p.isDirectory()); + assert (p.isFile()); + assert (p.toString(Path::PATH_WINDOWS) == "usr"); + + p.parse("usr\\", Path::PATH_WINDOWS); + assert (p.isRelative()); + assert (!p.isAbsolute()); + assert (p.depth() == 1); + assert (p[0] == "usr"); + assert (p.isDirectory()); + assert (!p.isFile()); + assert (p.toString(Path::PATH_WINDOWS) == "usr\\"); + + p.parse("/usr/local", Path::PATH_WINDOWS); + assert (!p.isRelative()); + assert (p.isAbsolute()); + assert (p.depth() == 1); + assert (p[0] == "usr"); + assert (p[1] == "local"); + assert (!p.isDirectory()); + assert (p.isFile()); + assert (p.toString(Path::PATH_WINDOWS) == "\\usr\\local"); + + p.parse("\\usr\\local", Path::PATH_WINDOWS); + assert (!p.isRelative()); + assert (p.isAbsolute()); + assert (p.depth() == 1); + assert (p[0] == "usr"); + assert (p[1] == "local"); + assert (!p.isDirectory()); + assert (p.isFile()); + assert (p.toString(Path::PATH_WINDOWS) == "\\usr\\local"); + + p.parse("/usr/local/", Path::PATH_WINDOWS); + assert (!p.isRelative()); + assert (p.isAbsolute()); + assert (p.depth() == 2); + assert (p[0] == "usr"); + assert (p[1] == "local"); + assert (p.isDirectory()); + assert (!p.isFile()); + assert (p.toString(Path::PATH_WINDOWS) == "\\usr\\local\\"); + + p.parse("usr/local/", Path::PATH_WINDOWS); + assert (p.isRelative()); + assert (!p.isAbsolute()); + assert (p.depth() == 2); + assert (p[0] == "usr"); + assert (p[1] == "local"); + assert (p.isDirectory()); + assert (!p.isFile()); + assert (p.toString(Path::PATH_WINDOWS) == "usr\\local\\"); + + p.parse("usr/local", Path::PATH_WINDOWS); + assert (p.isRelative()); + assert (!p.isAbsolute()); + assert (p.depth() == 1); + assert (p[0] == "usr"); + assert (p[1] == "local"); + assert (!p.isDirectory()); + assert (p.isFile()); + assert (p.toString(Path::PATH_WINDOWS) == "usr\\local"); + + p.parse("/usr/local/bin", Path::PATH_WINDOWS); + assert (!p.isRelative()); + assert (p.isAbsolute()); + assert (p.depth() == 2); + assert (p[0] == "usr"); + assert (p[1] == "local"); + assert (p[2] == "bin"); + assert (!p.isDirectory()); + assert (p.isFile()); + assert (p.toString(Path::PATH_WINDOWS) == "\\usr\\local\\bin"); + + p.parse("/usr/local/bin/", Path::PATH_WINDOWS); + assert (!p.isRelative()); + assert (p.isAbsolute()); + assert (p.depth() == 3); + assert (p[0] == "usr"); + assert (p[1] == "local"); + assert (p[2] == "bin"); + assert (p.isDirectory()); + assert (!p.isFile()); + assert (p.toString(Path::PATH_WINDOWS) == "\\usr\\local\\bin\\"); + + p.parse("/usr//local/bin/", Path::PATH_WINDOWS); + assert (!p.isRelative()); + assert (p.isAbsolute()); + assert (p.depth() == 3); + assert (p[0] == "usr"); + assert (p[1] == "local"); + assert (p[2] == "bin"); + assert (p.isDirectory()); + assert (!p.isFile()); + assert (p.toString(Path::PATH_WINDOWS) == "\\usr\\local\\bin\\"); + + p.parse("/usr/local//bin/", Path::PATH_WINDOWS); + assert (!p.isRelative()); + assert (p.isAbsolute()); + assert (p.depth() == 3); + assert (p[0] == "usr"); + assert (p[1] == "local"); + assert (p[2] == "bin"); + assert (p.isDirectory()); + assert (!p.isFile()); + assert (p.toString(Path::PATH_WINDOWS) == "\\usr\\local\\bin\\"); + + p.parse("/usr/local/bin//", Path::PATH_WINDOWS); + assert (!p.isRelative()); + assert (p.isAbsolute()); + assert (p.depth() == 3); + assert (p[0] == "usr"); + assert (p[1] == "local"); + assert (p[2] == "bin"); + assert (p.isDirectory()); + assert (!p.isFile()); + assert (p.toString(Path::PATH_WINDOWS) == "\\usr\\local\\bin\\"); +} + + +void PathTest::testParseWindows3() +{ + Path p; + p.parse("/usr/local/./bin/", Path::PATH_WINDOWS); + assert (!p.isRelative()); + assert (p.isAbsolute()); + assert (p.depth() == 3); + assert (p[0] == "usr"); + assert (p[1] == "local"); + assert (p[2] == "bin"); + assert (p.isDirectory()); + assert (!p.isFile()); + assert (p.toString(Path::PATH_WINDOWS) == "\\usr\\local\\bin\\"); + + p.parse("./usr/local/bin/", Path::PATH_WINDOWS); + assert (p.isRelative()); + assert (!p.isAbsolute()); + assert (p.depth() == 3); + assert (p[0] == "usr"); + assert (p[1] == "local"); + assert (p[2] == "bin"); + assert (p.isDirectory()); + assert (!p.isFile()); + assert (p.toString(Path::PATH_WINDOWS) == "usr\\local\\bin\\"); + + p.parse("./usr/local/bin/./", Path::PATH_WINDOWS); + assert (p.isRelative()); + assert (!p.isAbsolute()); + assert (p.depth() == 3); + assert (p[0] == "usr"); + assert (p[1] == "local"); + assert (p[2] == "bin"); + assert (p.isDirectory()); + assert (!p.isFile()); + assert (p.toString(Path::PATH_WINDOWS) == "usr\\local\\bin\\"); + + p.parse("./usr/local/bin/.", Path::PATH_WINDOWS); + assert (p.isRelative()); + assert (!p.isAbsolute()); + assert (p.depth() == 3); + assert (p[0] == "usr"); + assert (p[1] == "local"); + assert (p[2] == "bin"); + assert (!p.isDirectory()); + assert (p.isFile()); + assert (p.toString(Path::PATH_WINDOWS) == "usr\\local\\bin\\."); + + p.parse("/usr/local/lib/../bin/", Path::PATH_WINDOWS); + assert (!p.isRelative()); + assert (p.isAbsolute()); + assert (p.depth() == 3); + assert (p[0] == "usr"); + assert (p[1] == "local"); + assert (p[2] == "bin"); + assert (p.isDirectory()); + assert (!p.isFile()); + assert (p.toString(Path::PATH_WINDOWS) == "\\usr\\local\\bin\\"); + + p.parse("/usr/local/lib/../bin/", Path::PATH_WINDOWS); + assert (!p.isRelative()); + assert (p.isAbsolute()); + assert (p.depth() == 3); + assert (p[0] == "usr"); + assert (p[1] == "local"); + assert (p[2] == "bin"); + assert (p.isDirectory()); + assert (!p.isFile()); + assert (p.toString(Path::PATH_WINDOWS) == "\\usr\\local\\bin\\"); + + p.parse("\\usr\\local\\lib\\..\\bin\\", Path::PATH_WINDOWS); + assert (!p.isRelative()); + assert (p.isAbsolute()); + assert (p.depth() == 3); + assert (p[0] == "usr"); + assert (p[1] == "local"); + assert (p[2] == "bin"); + assert (p.isDirectory()); + assert (!p.isFile()); + assert (p.toString(Path::PATH_WINDOWS) == "\\usr\\local\\bin\\"); + + p.parse("/usr/local/lib/../../", Path::PATH_WINDOWS); + assert (!p.isRelative()); + assert (p.isAbsolute()); + assert (p.depth() == 1); + assert (p[0] == "usr"); + assert (p.isDirectory()); + assert (!p.isFile()); + assert (p.toString(Path::PATH_WINDOWS) == "\\usr\\"); + + p.parse("/usr/local/lib/..", Path::PATH_WINDOWS); + assert (!p.isRelative()); + assert (p.isAbsolute()); + assert (p.depth() == 3); + assert (p[0] == "usr"); + assert (p[1] == "local"); + assert (p[2] == "lib"); + assert (!p.isDirectory()); + assert (p.isFile()); + assert (p.toString(Path::PATH_WINDOWS) == "\\usr\\local\\lib\\.."); + + p.parse("../usr/local/lib/", Path::PATH_WINDOWS); + assert (p.isRelative()); + assert (!p.isAbsolute()); + assert (p.depth() == 4); + assert (p[0] == ".."); + assert (p[1] == "usr"); + assert (p[2] == "local"); + assert (p[3] == "lib"); + assert (p.isDirectory()); + assert (!p.isFile()); + assert (p.toString(Path::PATH_WINDOWS) == "..\\usr\\local\\lib\\"); + + p.parse("/usr/../lib/", Path::PATH_WINDOWS); + assert (!p.isRelative()); + assert (p.isAbsolute()); + assert (p.depth() == 1); + assert (p[0] == "lib"); + assert (p.isDirectory()); + assert (!p.isFile()); + assert (p.toString(Path::PATH_WINDOWS) == "\\lib\\"); + + p.parse("/usr/../../lib/", Path::PATH_WINDOWS); + assert (!p.isRelative()); + assert (p.isAbsolute()); + assert (p.depth() == 1); + assert (p[0] == "lib"); + assert (p.isDirectory()); + assert (!p.isFile()); + assert (p.toString(Path::PATH_WINDOWS) == "\\lib\\"); + + p.parse("local/../../lib/", Path::PATH_WINDOWS); + assert (p.isRelative()); + assert (!p.isAbsolute()); + assert (p.depth() == 2); + assert (p[0] == ".."); + assert (p[1] == "lib"); + assert (p.isDirectory()); + assert (!p.isFile()); + assert (p.toString(Path::PATH_WINDOWS) == "..\\lib\\"); +} + + +void PathTest::testParseWindows4() +{ + Path p; + p.parse("\\\\server\\files", Path::PATH_WINDOWS); + assert (!p.isRelative()); + assert (p.isAbsolute()); + assert (p.depth() == 1); + assert (p[0] == "files"); + assert (p.getNode() == "server"); + assert (p.isDirectory()); + assert (!p.isFile()); + assert (p.toString(Path::PATH_WINDOWS) == "\\\\server\\files\\"); + + p.parse("\\\\server\\files\\", Path::PATH_WINDOWS); + assert (!p.isRelative()); + assert (p.isAbsolute()); + assert (p.depth() == 1); + assert (p[0] == "files"); + assert (p.getNode() == "server"); + assert (p.isDirectory()); + assert (!p.isFile()); + assert (p.toString(Path::PATH_WINDOWS) == "\\\\server\\files\\"); + + p.parse("\\\\server\\files\\file", Path::PATH_WINDOWS); + assert (!p.isRelative()); + assert (p.isAbsolute()); + assert (p.depth() == 1); + assert (p[0] == "files"); + assert (p.getNode() == "server"); + assert (!p.isDirectory()); + assert (p.isFile()); + assert (p.toString(Path::PATH_WINDOWS) == "\\\\server\\files\\file"); + + p.parse("\\\\server\\files\\dir\\file", Path::PATH_WINDOWS); + assert (!p.isRelative()); + assert (p.isAbsolute()); + assert (p.depth() == 2); + assert (p[0] == "files"); + assert (p[1] == "dir"); + assert (p.getNode() == "server"); + assert (!p.isDirectory()); + assert (p.isFile()); + assert (p.toString(Path::PATH_WINDOWS) == "\\\\server\\files\\dir\\file"); + + p.parse("\\\\server\\files\\dir\\file", Path::PATH_WINDOWS); + assert (!p.isRelative()); + assert (p.isAbsolute()); + assert (p.depth() == 2); + assert (p[0] == "files"); + assert (p[1] == "dir"); + assert (p.getNode() == "server"); + assert (!p.isDirectory()); + assert (p.isFile()); + assert (p.toString(Path::PATH_WINDOWS) == "\\\\server\\files\\dir\\file"); + + p.parse("\\\\server", Path::PATH_WINDOWS); + assert (!p.isRelative()); + assert (p.isAbsolute()); + assert (p.depth() == 0); + assert (p.getNode() == "server"); + assert (p.isDirectory()); + assert (!p.isFile()); + assert (p.toString(Path::PATH_WINDOWS) == "\\\\server\\"); + + p.parse("c:\\", Path::PATH_WINDOWS); + assert (!p.isRelative()); + assert (p.isAbsolute()); + assert (p.depth() == 0); + assert (p.getDevice() == "c"); + assert (p.isDirectory()); + assert (!p.isFile()); + assert (p.toString(Path::PATH_WINDOWS) == "c:\\"); + + p.parse("c:\\WinNT", Path::PATH_WINDOWS); + assert (!p.isRelative()); + assert (p.isAbsolute()); + assert (p.depth() == 0); + assert (p.getDevice() == "c"); + assert (!p.isDirectory()); + assert (p.isFile()); + assert (p.toString(Path::PATH_WINDOWS) == "c:\\WinNT"); + + p.parse("c:\\WinNT\\", Path::PATH_WINDOWS); + assert (!p.isRelative()); + assert (p.isAbsolute()); + assert (p.depth() == 1); + assert (p[0] == "WinNT"); + assert (p.getDevice() == "c"); + assert (p.isDirectory()); + assert (!p.isFile()); + assert (p.toString(Path::PATH_WINDOWS) == "c:\\WinNT\\"); + + try + { + p.parse("ü:\\", Path::PATH_WINDOWS); + fail("bad path - must throw exception"); + } + catch (PathSyntaxException&) + { + } + + try + { + p.parse("c:file.txt", Path::PATH_WINDOWS); + fail("bad path - must throw exception"); + } + catch (PathSyntaxException&) + { + } + + p.parse("a\\b\\c\\d", Path::PATH_WINDOWS); + assert (p.isRelative()); + assert (!p.isAbsolute()); + assert (p.depth() == 3); + assert (p[0] == "a"); + assert (p[1] == "b"); + assert (p[2] == "c"); + assert (!p.isDirectory()); + assert (p.isFile()); + assert (p.toString(Path::PATH_WINDOWS) == "a\\b\\c\\d"); +} + + +void PathTest::testParseVMS1() +{ + Path p; + p.parse("", Path::PATH_VMS); + assert (p.isRelative()); + assert (!p.isAbsolute()); + assert (p.depth() == 0); + assert (p.isDirectory()); + assert (!p.isFile()); + assert (p.toString(Path::PATH_VMS) == ""); + + p.parse("[]", Path::PATH_VMS); + assert (p.isRelative()); + assert (!p.isAbsolute()); + assert (p.depth() == 0); + assert (p.isDirectory()); + assert (!p.isFile()); + assert (p.toString(Path::PATH_VMS) == ""); + + p.parse("[foo]", Path::PATH_VMS); + assert (!p.isRelative()); + assert (p.isAbsolute()); + assert (p.depth() == 1); + assert (p[0] == "foo"); + assert (p.isDirectory()); + assert (!p.isFile()); + assert (p.toString(Path::PATH_VMS) == "[foo]"); + + p.parse("[.foo]", Path::PATH_VMS); + assert (p.isRelative()); + assert (!p.isAbsolute()); + assert (p.depth() == 1); + assert (p[0] == "foo"); + assert (p.isDirectory()); + assert (!p.isFile()); + assert (p.toString(Path::PATH_VMS) == "[.foo]"); + + p.parse("[foo.bar]", Path::PATH_VMS); + assert (!p.isRelative()); + assert (p.isAbsolute()); + assert (p.depth() == 2); + assert (p[0] == "foo"); + assert (p[1] == "bar"); + assert (p.isDirectory()); + assert (!p.isFile()); + assert (p.toString(Path::PATH_VMS) == "[foo.bar]"); + + p.parse("[.foo.bar]", Path::PATH_VMS); + assert (p.isRelative()); + assert (!p.isAbsolute()); + assert (p.depth() == 2); + assert (p[0] == "foo"); + assert (p[1] == "bar"); + assert (p.isDirectory()); + assert (!p.isFile()); + assert (p.toString(Path::PATH_VMS) == "[.foo.bar]"); + + p.parse("[foo.bar.foobar]", Path::PATH_VMS); + assert (!p.isRelative()); + assert (p.isAbsolute()); + assert (p.depth() == 3); + assert (p[0] == "foo"); + assert (p[1] == "bar"); + assert (p[2] == "foobar"); + assert (p.isDirectory()); + assert (!p.isFile()); + assert (p.toString(Path::PATH_VMS) == "[foo.bar.foobar]"); + + p.parse("[.foo.bar.foobar]", Path::PATH_VMS); + assert (p.isRelative()); + assert (!p.isAbsolute()); + assert (p.depth() == 3); + assert (p[0] == "foo"); + assert (p[1] == "bar"); + assert (p[2] == "foobar"); + assert (p.isDirectory()); + assert (!p.isFile()); + assert (p.toString(Path::PATH_VMS) == "[.foo.bar.foobar]"); +} + + +void PathTest::testParseVMS2() +{ + Path p; + p.parse("[foo][bar]", Path::PATH_VMS); + assert (!p.isRelative()); + assert (p.isAbsolute()); + assert (p.depth() == 2); + assert (p[0] == "foo"); + assert (p[1] == "bar"); + assert (p.isDirectory()); + assert (!p.isFile()); + assert (p.toString(Path::PATH_VMS) == "[foo.bar]"); + + p.parse("[foo.][bar]", Path::PATH_VMS); + assert (!p.isRelative()); + assert (p.isAbsolute()); + assert (p.depth() == 2); + assert (p[0] == "foo"); + assert (p[1] == "bar"); + assert (p.isDirectory()); + assert (!p.isFile()); + assert (p.toString(Path::PATH_VMS) == "[foo.bar]"); + + p.parse("[foo.bar][foo]", Path::PATH_VMS); + assert (!p.isRelative()); + assert (p.isAbsolute()); + assert (p.depth() == 3); + assert (p[0] == "foo"); + assert (p[1] == "bar"); + assert (p[2] == "foo"); + assert (p.isDirectory()); + assert (!p.isFile()); + assert (p.toString(Path::PATH_VMS) == "[foo.bar.foo]"); + + try + { + p.parse("[foo.bar][.foo]", Path::PATH_VMS); + failmsg("bad path - must throw exception"); + } + catch (PathSyntaxException&) + { + } + + try + { + p.parse("[.foo.bar][foo]", Path::PATH_VMS); + failmsg("bad path - must throw exception"); + } + catch (PathSyntaxException&) + { + } + + p.parse("[-]", Path::PATH_VMS); + assert (p.isRelative()); + assert (!p.isAbsolute()); + assert (p.depth() == 1); + assert (p[0] == ".."); + assert (p.isDirectory()); + assert (!p.isFile()); + assert (p.toString(Path::PATH_VMS) == "[-]"); + + p.parse("[--]", Path::PATH_VMS); + assert (p.isRelative()); + assert (!p.isAbsolute()); + assert (p.depth() == 2); + assert (p[0] == ".."); + assert (p[1] == ".."); + assert (p.isDirectory()); + assert (!p.isFile()); + assert (p.toString(Path::PATH_VMS) == "[--]"); + + p.parse("[---]", Path::PATH_VMS); + assert (p.isRelative()); + assert (!p.isAbsolute()); + assert (p.depth() == 3); + assert (p[0] == ".."); + assert (p[1] == ".."); + assert (p[2] == ".."); + assert (p.isDirectory()); + assert (!p.isFile()); + assert (p.toString(Path::PATH_VMS) == "[---]"); + + p.parse("[-.-]", Path::PATH_VMS); + assert (p.isRelative()); + assert (!p.isAbsolute()); + assert (p.depth() == 2); + assert (p[0] == ".."); + assert (p[1] == ".."); + assert (p.isDirectory()); + assert (!p.isFile()); + assert (p.toString(Path::PATH_VMS) == "[--]"); + + p.parse("[.-.-]", Path::PATH_VMS); + assert (p.isRelative()); + assert (!p.isAbsolute()); + assert (p.depth() == 2); + assert (p[0] == ".."); + assert (p[1] == ".."); + assert (p.isDirectory()); + assert (!p.isFile()); + assert (p.toString(Path::PATH_VMS) == "[--]"); + + p.parse("[-.-.-]", Path::PATH_VMS); + assert (p.isRelative()); + assert (!p.isAbsolute()); + assert (p.depth() == 3); + assert (p[0] == ".."); + assert (p[1] == ".."); + assert (p[2] == ".."); + assert (p.isDirectory()); + assert (!p.isFile()); + assert (p.toString(Path::PATH_VMS) == "[---]"); + + p.parse("[.-.-.-]", Path::PATH_VMS); + assert (p.isRelative()); + assert (!p.isAbsolute()); + assert (p.depth() == 3); + assert (p[0] == ".."); + assert (p[1] == ".."); + assert (p[2] == ".."); + assert (p.isDirectory()); + assert (!p.isFile()); + assert (p.toString(Path::PATH_VMS) == "[---]"); + + p.parse("[.--.-]", Path::PATH_VMS); + assert (p.isRelative()); + assert (!p.isAbsolute()); + assert (p.depth() == 3); + assert (p[0] == ".."); + assert (p[1] == ".."); + assert (p[2] == ".."); + assert (p.isDirectory()); + assert (!p.isFile()); + assert (p.toString(Path::PATH_VMS) == "[---]"); + + p.parse("[--.-]", Path::PATH_VMS); + assert (p.isRelative()); + assert (!p.isAbsolute()); + assert (p.depth() == 3); + assert (p[0] == ".."); + assert (p[1] == ".."); + assert (p[2] == ".."); + assert (p.isDirectory()); + assert (!p.isFile()); + assert (p.toString(Path::PATH_VMS) == "[---]"); +} + + +void PathTest::testParseVMS3() +{ + Path p; + p.parse("[foo][-]", Path::PATH_VMS); + assert (!p.isRelative()); + assert (p.isAbsolute()); + assert (p.depth() == 1); + assert (p[0] == "foo"); + assert (p.isDirectory()); + assert (!p.isFile()); + assert (p.toString(Path::PATH_VMS) == "[foo]"); + + p.parse("[foo][--]", Path::PATH_VMS); + assert (!p.isRelative()); + assert (p.isAbsolute()); + assert (p.depth() == 1); + assert (p[0] == "foo"); + assert (p.isDirectory()); + assert (!p.isFile()); + assert (p.toString(Path::PATH_VMS) == "[foo]"); + + p.parse("[foo][-.-]", Path::PATH_VMS); + assert (!p.isRelative()); + assert (p.isAbsolute()); + assert (p.depth() == 1); + assert (p[0] == "foo"); + assert (p.isDirectory()); + assert (!p.isFile()); + assert (p.toString(Path::PATH_VMS) == "[foo]"); + + p.parse("[foo][bar.-]", Path::PATH_VMS); + assert (!p.isRelative()); + assert (p.isAbsolute()); + assert (p.depth() == 1); + assert (p[0] == "foo"); + assert (p.isDirectory()); + assert (!p.isFile()); + assert (p.toString(Path::PATH_VMS) == "[foo]"); + + p.parse("[foo][bar.foo.-]", Path::PATH_VMS); + assert (!p.isRelative()); + assert (p.isAbsolute()); + assert (p.depth() == 2); + assert (p[0] == "foo"); + assert (p[1] == "bar"); + assert (p.isDirectory()); + assert (!p.isFile()); + assert (p.toString(Path::PATH_VMS) == "[foo.bar]"); + + p.parse("[foo][bar.foo.--]", Path::PATH_VMS); + assert (!p.isRelative()); + assert (p.isAbsolute()); + assert (p.depth() == 1); + assert (p[0] == "foo"); + assert (p.isDirectory()); + assert (!p.isFile()); + assert (p.toString(Path::PATH_VMS) == "[foo]"); + + p.parse("[foo][bar.foo.---]", Path::PATH_VMS); + assert (!p.isRelative()); + assert (p.isAbsolute()); + assert (p.depth() == 1); + assert (p[0] == "foo"); + assert (p.isDirectory()); + assert (!p.isFile()); + assert (p.toString(Path::PATH_VMS) == "[foo]"); + + p.parse("[foo][bar.foo.-.-.-]", Path::PATH_VMS); + assert (!p.isRelative()); + assert (p.isAbsolute()); + assert (p.depth() == 1); + assert (p[0] == "foo"); + assert (p.isDirectory()); + assert (!p.isFile()); + assert (p.toString(Path::PATH_VMS) == "[foo]"); +} + + +void PathTest::testParseVMS4() +{ + Path p; + p.parse("device:[foo]", Path::PATH_VMS); + assert (!p.isRelative()); + assert (p.isAbsolute()); + assert (p.depth() == 1); + assert (p[0] == "foo"); + assert (p.getDevice() == "device"); + assert (p.isDirectory()); + assert (!p.isFile()); + assert (p.toString(Path::PATH_VMS) == "device:[foo]"); + + p.parse("device:[.foo]", Path::PATH_VMS); + assert (p.isRelative()); + assert (!p.isAbsolute()); + assert (p.depth() == 1); + assert (p[0] == "foo"); + assert (p.getDevice() == "device"); + assert (p.isDirectory()); + assert (!p.isFile()); + assert (p.toString(Path::PATH_VMS) == "device:[.foo]"); + + p.parse("node::device:[foo]", Path::PATH_VMS); + assert (!p.isRelative()); + assert (p.isAbsolute()); + assert (p.depth() == 1); + assert (p[0] == "foo"); + assert (p.getNode() == "node"); + assert (p.getDevice() == "device"); + assert (p.isDirectory()); + assert (!p.isFile()); + assert (p.toString(Path::PATH_VMS) == "node::device:[foo]"); + + p.parse("node::device:[foo.bar]", Path::PATH_VMS); + assert (!p.isRelative()); + assert (p.isAbsolute()); + assert (p.depth() == 2); + assert (p[0] == "foo"); + assert (p[1] == "bar"); + assert (p.getNode() == "node"); + assert (p.getDevice() == "device"); + assert (p.isDirectory()); + assert (!p.isFile()); + assert (p.toString(Path::PATH_VMS) == "node::device:[foo.bar]"); + + p.parse("node::device:[foo.bar.][goo]", Path::PATH_VMS); + assert (!p.isRelative()); + assert (p.isAbsolute()); + assert (p.depth() == 3); + assert (p[0] == "foo"); + assert (p[1] == "bar"); + assert (p[2] == "goo"); + assert (p.getNode() == "node"); + assert (p.getDevice() == "device"); + assert (p.isDirectory()); + assert (!p.isFile()); + assert (p.toString(Path::PATH_VMS) == "node::device:[foo.bar.goo]"); + + p.parse("[]foo.txt", Path::PATH_VMS); + assert (p.isRelative()); + assert (!p.isAbsolute()); + assert (p.depth() == 0); + assert (!p.isDirectory()); + assert (p.isFile()); + assert (p.toString(Path::PATH_VMS) == "foo.txt"); + + p.parse("[foo]bar.txt", Path::PATH_VMS); + assert (!p.isRelative()); + assert (p.isAbsolute()); + assert (p.depth() == 1); + assert (p[0] == "foo"); + assert (!p.isDirectory()); + assert (p.isFile()); + assert (p.toString(Path::PATH_VMS) == "[foo]bar.txt"); + + p.parse("[foo]bar.txt;", Path::PATH_VMS); + assert (!p.isRelative()); + assert (p.isAbsolute()); + assert (p.depth() == 1); + assert (p[0] == "foo"); + assert (!p.isDirectory()); + assert (p.isFile()); + assert (p.toString(Path::PATH_VMS) == "[foo]bar.txt"); + + p.parse("[foo]bar.txt;5", Path::PATH_VMS); + assert (!p.isRelative()); + assert (p.isAbsolute()); + assert (p.depth() == 1); + assert (p[0] == "foo"); + assert (!p.isDirectory()); + assert (p.isFile()); + assert (p.toString(Path::PATH_VMS) == "[foo]bar.txt;5"); + assert (p.version() == "5"); + + p.parse("foo:bar.txt", Path::PATH_VMS); + assert (!p.isRelative()); + assert (p.isAbsolute()); + assert (p.depth() == 0); + assert (p.getDevice() == "foo"); + assert (!p.isDirectory()); + assert (p.isFile()); + assert (p.toString(Path::PATH_VMS) == "foo:bar.txt"); + + p.parse("foo:bar.txt;5", Path::PATH_VMS); + assert (!p.isRelative()); + assert (p.isAbsolute()); + assert (p.depth() == 0); + assert (p.getDevice() == "foo"); + assert (!p.isDirectory()); + assert (p.isFile()); + assert (p.toString(Path::PATH_VMS) == "foo:bar.txt;5"); + assert (p.version() == "5"); + + p.parse("foo:", Path::PATH_VMS); + assert (!p.isRelative()); + assert (p.isAbsolute()); + assert (p.depth() == 0); + assert (p.getDevice() == "foo"); + assert (p.isDirectory()); + assert (!p.isFile()); + assert (p.toString(Path::PATH_VMS) == "foo:"); + + p.parse("bar.txt", Path::PATH_VMS); + assert (p.isRelative()); + assert (!p.isAbsolute()); + assert (p.depth() == 0); + assert (!p.isDirectory()); + assert (p.isFile()); + assert (p.toString(Path::PATH_VMS) == "bar.txt"); + + p.parse("bar.txt;5", Path::PATH_VMS); + assert (p.isRelative()); + assert (!p.isAbsolute()); + assert (p.depth() == 0); + assert (!p.isDirectory()); + assert (p.isFile()); + assert (p.toString(Path::PATH_VMS) == "bar.txt;5"); + assert (p.version() == "5"); +} + + +void PathTest::testParseGuess() +{ + Path p; + + p.parse("foo:bar.txt;5", Path::PATH_GUESS); + assert (!p.isRelative()); + assert (p.isAbsolute()); + assert (p.depth() == 0); + assert (p.getDevice() == "foo"); + assert (!p.isDirectory()); + assert (p.isFile()); + assert (p.toString(Path::PATH_VMS) == "foo:bar.txt;5"); + assert (p.version() == "5"); + + p.parse("/usr/local/bin", Path::PATH_GUESS); + assert (!p.isRelative()); + assert (p.isAbsolute()); + assert (p.depth() == 2); + assert (p[0] == "usr"); + assert (p[1] == "local"); + assert (p[2] == "bin"); + assert (!p.isDirectory()); + assert (p.isFile()); + assert (p.toString(Path::PATH_UNIX) == "/usr/local/bin"); + + p.parse("\\\\server\\files", Path::PATH_GUESS); + assert (!p.isRelative()); + assert (p.isAbsolute()); + assert (p.depth() == 1); + assert (p[0] == "files"); + assert (p.getNode() == "server"); + assert (p.isDirectory()); + assert (!p.isFile()); + assert (p.toString(Path::PATH_WINDOWS) == "\\\\server\\files\\"); + + p.parse("c:\\WinNT", Path::PATH_GUESS); + assert (!p.isRelative()); + assert (p.isAbsolute()); + assert (p.depth() == 0); + assert (p.getDevice() == "c"); + assert (!p.isDirectory()); + assert (p.isFile()); + assert (p.toString(Path::PATH_WINDOWS) == "c:\\WinNT"); + + p.parse("foo:bar.txt;5", Path::PATH_GUESS); + assert (!p.isRelative()); + assert (p.isAbsolute()); + assert (p.depth() == 0); + assert (p.getDevice() == "foo"); + assert (!p.isDirectory()); + assert (p.isFile()); + assert (p.toString(Path::PATH_VMS) == "foo:bar.txt;5"); + assert (p.version() == "5"); + + p.parse("[foo]bar.txt", Path::PATH_GUESS); + assert (!p.isRelative()); + assert (p.isAbsolute()); + assert (p.depth() == 1); + assert (p[0] == "foo"); + assert (!p.isDirectory()); + assert (p.isFile()); + assert (p.toString(Path::PATH_VMS) == "[foo]bar.txt"); +} + + +void PathTest::testTryParse() +{ + Path p; +#if defined(POCO_OS_FAMILY_UNIX) + assert (p.tryParse("/etc/passwd")); + assert (p.toString() == "/etc/passwd"); +#elif defined(POCO_OS_FAMILY_WINDOWS) + assert (p.tryParse("c:\\windows\\system32")); + assert (p.toString() == "c:\\windows\\system32"); + assert (!p.tryParse("c:foo.bar")); + assert (p.toString() == "c:\\windows\\system32"); +#endif + + assert (p.tryParse("c:\\windows\\system", Path::PATH_WINDOWS)); + assert (p.toString(Path::PATH_WINDOWS) == "c:\\windows\\system"); + assert (!p.tryParse("c:foo.bar", Path::PATH_WINDOWS)); + assert (p.toString(Path::PATH_WINDOWS) == "c:\\windows\\system"); +} + + +void PathTest::testStatics() +{ + std::string s = Path::current(); + assert (!s.empty()); + Path p(s); + assert (p.isDirectory() && p.isAbsolute()); + + s = Path::home(); + assert (!s.empty()); + p = s; + assert (p.isDirectory() && p.isAbsolute()); + + s = Path::temp(); + assert (!s.empty()); + p = s; + assert (p.isDirectory() && p.isAbsolute()); + + s = Path::null(); + assert (!s.empty()); + p = s; +} + + +void PathTest::testBaseNameExt() +{ + Path p("foo.bar"); + assert (p.getFileName() == "foo.bar"); + assert (p.getBaseName() == "foo"); + assert (p.getExtension() == "bar"); + + p.setBaseName("readme"); + assert (p.getFileName() == "readme.bar"); + assert (p.getBaseName() == "readme"); + assert (p.getExtension() == "bar"); + + p.setExtension("txt"); + assert (p.getFileName() == "readme.txt"); + assert (p.getBaseName() == "readme"); + assert (p.getExtension() == "txt"); + + p.setExtension("html"); + assert (p.getFileName() == "readme.html"); + assert (p.getBaseName() == "readme"); + assert (p.getExtension() == "html"); + + p.setBaseName("index"); + assert (p.getFileName() == "index.html"); + assert (p.getBaseName() == "index"); + assert (p.getExtension() == "html"); +} + + +void PathTest::testAbsolute() +{ + Path base("C:\\Program Files\\", Path::PATH_WINDOWS); + Path rel("Poco"); + Path abs = rel.absolute(base); + assert (abs.toString(Path::PATH_WINDOWS) == "C:\\Program Files\\Poco"); + + base.parse("/usr/local", Path::PATH_UNIX); + rel.parse("Poco/include", Path::PATH_UNIX); + abs = rel.absolute(base); + assert (abs.toString(Path::PATH_UNIX) == "/usr/local/Poco/include"); + + base.parse("/usr/local/bin", Path::PATH_UNIX); + rel.parse("../Poco/include", Path::PATH_UNIX); + abs = rel.absolute(base); + assert (abs.toString(Path::PATH_UNIX) == "/usr/local/Poco/include"); +} + + +void PathTest::testRobustness() +{ + Random r; + for (int i = 0; i < 256; ++i) + { + int len = r.next(1024); + std::string s; + for (int i = 0; i < len; ++i) s += r.nextChar(); + try + { + Path p(s, Path::PATH_WINDOWS); + } + catch (PathSyntaxException&) + { + } + try + { + Path p(s, Path::PATH_UNIX); + } + catch (PathSyntaxException&) + { + } + try + { + Path p(s, Path::PATH_VMS); + } + catch (PathSyntaxException&) + { + } + try + { + Path p(s, Path::PATH_GUESS); + } + catch (PathSyntaxException&) + { + } + } +} + + +void PathTest::testParent() +{ + Path p("/usr/local/include", Path::PATH_UNIX); + p.makeParent(); + assert (p.toString(Path::PATH_UNIX) == "/usr/local/"); + p.makeParent(); + assert (p.toString(Path::PATH_UNIX) == "/usr/"); + p.makeParent(); + assert (p.toString(Path::PATH_UNIX) == "/"); + p.makeParent(); + assert (p.toString(Path::PATH_UNIX) == "/"); +} + + +void PathTest::testForDirectory() +{ + Path p = Path::forDirectory("/usr/local/include", Path::PATH_UNIX); + assert (p.toString(Path::PATH_UNIX) == "/usr/local/include/"); + + p = Path::forDirectory("/usr/local/include/", Path::PATH_UNIX); + assert (p.toString(Path::PATH_UNIX) == "/usr/local/include/"); +} + + +void PathTest::testExpand() +{ +#if defined(POCO_OS_FAMILY_UNIX) + std::string s = Path::expand("~/.bashrc"); + assert (s == Path::expand("$HOME/.bashrc")); + assert (s == Environment::get("HOME") + "/.bashrc" || + s == Environment::get("HOME") + "//.bashrc"); + Path p(s); + s = Path::expand("$HOME/.bashrc"); + assert (s == Path::expand("~/.bashrc")); + s = Path::expand("${HOME}/.bashrc"); + assert (s == Path::expand("~/.bashrc")); +#elif defined(POCO_OS_FAMILY_WINDOWS) + std::string s = Path::expand("%TMP%\\foo"); + assert (s == Environment::get("TMP") + "\\foo"); + Path p(s); +#else + std::string s = Path::expand("SYS$LOGIN:[projects]"); + assert (s.find(":[projects]") != std::string::npos); + Path p(s); +#endif +} + + +void PathTest::testListRoots() +{ + std::vector devs; + Path::listRoots(devs); + assert (devs.size() > 0); + for (std::vector::iterator it = devs.begin(); it != devs.end(); ++it) + { + std::cout << *it << std::endl; + } +} + + +void PathTest::testFind() +{ + Path p; +#if defined(POCO_OS_FAMILY_UNIX) + bool found = Path::find(Environment::get("PATH"), "ls", p); + bool notfound = Path::find(Environment::get("PATH"), "xxxyyy123", p); +#elif defined(POCO_OS_FAMILY_WINDOWS) + bool found = Path::find(Environment::get("PATH"), "cmd.exe", p); + bool notfound = Path::find(Environment::get("PATH"), "xxxyyy123.zzz", p); +#else + bool found = true; + bool notfound = false; +#endif + assert (found); + assert (!notfound); + + std::string fn = p.toString(); + assert (fn.size() > 0); +} + + +void PathTest::testSwap() +{ + Path p1("c:\\temp\\foo.bar"); + Path p2("\\\\server\\files\\foo.bar"); + p1.swap(p2); + assert (p1.toString() == "\\\\server\\files\\foo.bar"); + assert (p2.toString() == "c:\\temp\\foo.bar"); +} + + +void PathTest::testResolve() +{ + Path p("c:\\foo\\", Path::PATH_WINDOWS); + p.resolve("test.dat"); + assert (p.toString(Path::PATH_WINDOWS) == "c:\\foo\\test.dat"); + + p.assign("c:\\foo\\", Path::PATH_WINDOWS); + p.resolve(Path("d:\\bar.txt", Path::PATH_WINDOWS)); + assert (p.toString(Path::PATH_WINDOWS) == "d:\\bar.txt"); + + p.assign("c:\\foo\\bar.txt", Path::PATH_WINDOWS); + p.resolve("foo.txt"); + assert (p.toString(Path::PATH_WINDOWS) == "c:\\foo\\foo.txt"); + + p.assign("c:\\foo\\bar\\", Path::PATH_WINDOWS); + p.resolve(Path("..\\baz\\test.dat", Path::PATH_WINDOWS)); + assert (p.toString(Path::PATH_WINDOWS) == "c:\\foo\\baz\\test.dat"); +} + + +void PathTest::setUp() +{ +} + + +void PathTest::tearDown() +{ +} + + +CppUnit::Test* PathTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("PathTest"); + + CppUnit_addTest(pSuite, PathTest, testParseUnix1); + CppUnit_addTest(pSuite, PathTest, testParseUnix2); + CppUnit_addTest(pSuite, PathTest, testParseUnix3); + CppUnit_addTest(pSuite, PathTest, testParseUnix4); + CppUnit_addTest(pSuite, PathTest, testParseUnix5); + CppUnit_addTest(pSuite, PathTest, testParseWindows1); + CppUnit_addTest(pSuite, PathTest, testParseWindows2); + CppUnit_addTest(pSuite, PathTest, testParseWindows3); + CppUnit_addTest(pSuite, PathTest, testParseWindows4); + CppUnit_addTest(pSuite, PathTest, testParseVMS1); + CppUnit_addTest(pSuite, PathTest, testParseVMS2); + CppUnit_addTest(pSuite, PathTest, testParseVMS3); + CppUnit_addTest(pSuite, PathTest, testParseVMS4); + CppUnit_addTest(pSuite, PathTest, testParseGuess); + CppUnit_addTest(pSuite, PathTest, testTryParse); + CppUnit_addTest(pSuite, PathTest, testStatics); + CppUnit_addTest(pSuite, PathTest, testBaseNameExt); + CppUnit_addTest(pSuite, PathTest, testAbsolute); + CppUnit_addTest(pSuite, PathTest, testRobustness); + CppUnit_addTest(pSuite, PathTest, testParent); + CppUnit_addTest(pSuite, PathTest, testForDirectory); + CppUnit_addTest(pSuite, PathTest, testExpand); + CppUnit_addTest(pSuite, PathTest, testListRoots); + CppUnit_addTest(pSuite, PathTest, testFind); + CppUnit_addTest(pSuite, PathTest, testSwap); + CppUnit_addTest(pSuite, PathTest, testResolve); + + return pSuite; +} diff --git a/Foundation/testsuite/src/PathTest.h b/Foundation/testsuite/src/PathTest.h index 644f81161..b0c35b269 100644 --- a/Foundation/testsuite/src/PathTest.h +++ b/Foundation/testsuite/src/PathTest.h @@ -1,85 +1,85 @@ -// -// PathTest.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/PathTest.h#1 $ -// -// Definition of the PathTest class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 PathTest_INCLUDED -#define PathTest_INCLUDED - - -#include "Poco/Foundation.h" -#include "CppUnit/TestCase.h" - - -class PathTest: public CppUnit::TestCase -{ -public: - PathTest(const std::string& name); - ~PathTest(); - - void testParseUnix1(); - void testParseUnix2(); - void testParseUnix3(); - void testParseUnix4(); - void testParseUnix5(); - void testParseWindows1(); - void testParseWindows2(); - void testParseWindows3(); - void testParseWindows4(); - void testParseVMS1(); - void testParseVMS2(); - void testParseVMS3(); - void testParseVMS4(); - void testParseGuess(); - void testTryParse(); - void testStatics(); - void testBaseNameExt(); - void testAbsolute(); - void testRobustness(); - void testParent(); - void testForDirectory(); - void testExpand(); - void testListRoots(); - void testFind(); - void testSwap(); - void testResolve(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // PathTest_INCLUDED +// +// PathTest.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/PathTest.h#1 $ +// +// Definition of the PathTest class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 PathTest_INCLUDED +#define PathTest_INCLUDED + + +#include "Poco/Foundation.h" +#include "CppUnit/TestCase.h" + + +class PathTest: public CppUnit::TestCase +{ +public: + PathTest(const std::string& name); + ~PathTest(); + + void testParseUnix1(); + void testParseUnix2(); + void testParseUnix3(); + void testParseUnix4(); + void testParseUnix5(); + void testParseWindows1(); + void testParseWindows2(); + void testParseWindows3(); + void testParseWindows4(); + void testParseVMS1(); + void testParseVMS2(); + void testParseVMS3(); + void testParseVMS4(); + void testParseGuess(); + void testTryParse(); + void testStatics(); + void testBaseNameExt(); + void testAbsolute(); + void testRobustness(); + void testParent(); + void testForDirectory(); + void testExpand(); + void testListRoots(); + void testFind(); + void testSwap(); + void testResolve(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // PathTest_INCLUDED diff --git a/Foundation/testsuite/src/PatternFormatterTest.cpp b/Foundation/testsuite/src/PatternFormatterTest.cpp index a984d45c2..42c15c8b5 100644 --- a/Foundation/testsuite/src/PatternFormatterTest.cpp +++ b/Foundation/testsuite/src/PatternFormatterTest.cpp @@ -1,111 +1,111 @@ -// -// PatternFormatterTest.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/PatternFormatterTest.cpp#1 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "PatternFormatterTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/PatternFormatter.h" -#include "Poco/Message.h" -#include "Poco/DateTime.h" - - -using Poco::PatternFormatter; -using Poco::Message; -using Poco::DateTime; - - -PatternFormatterTest::PatternFormatterTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -PatternFormatterTest::~PatternFormatterTest() -{ -} - - -void PatternFormatterTest::testPatternFormatter() -{ - Message msg; - PatternFormatter fmt; - msg.setSource("TestSource"); - msg.setText("Test message text"); - msg.setPid(1234); - msg.setTid(1); - msg.setThread("TestThread"); - msg.setPriority(Message::PRIO_ERROR); - msg.setTime(DateTime(2005, 1, 1, 14, 30, 15, 500).timestamp()); - msg["testParam"] = "Test Parameter"; - - std::string result; - fmt.setProperty("pattern", "%Y-%m-%dT%H:%M:%S [%s] %p: %t"); - fmt.format(msg, result); - assert (result == "2005-01-01T14:30:15 [TestSource] Error: Test message text"); - - result.clear(); - fmt.setProperty("pattern", "%w, %e %b %y %H:%M:%S.%i [%s:%I:%T] %q: %t"); - fmt.format(msg, result); - assert (result == "Sat, 1 Jan 05 14:30:15.500 [TestSource:1:TestThread] E: Test message text"); - - result.clear(); - fmt.setProperty("pattern", "%Y-%m-%d %H:%M:%S [%N:%P:%s]%l-%t"); - fmt.format(msg, result); - assert (result.find("2005-01-01 14:30:15 [") == 0); - assert (result.find(":TestSource]3-Test message text") != std::string::npos); - - result.clear(); - assert (fmt.getProperty("times") == "UTC"); - fmt.setProperty("times", "local"); - fmt.format(msg, result); - assert (result.find("2005-01-01 ") == 0); - assert (result.find(":TestSource]3-Test message text") != std::string::npos); -} - - -void PatternFormatterTest::setUp() -{ -} - - -void PatternFormatterTest::tearDown() -{ -} - - -CppUnit::Test* PatternFormatterTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("PatternFormatterTest"); - - CppUnit_addTest(pSuite, PatternFormatterTest, testPatternFormatter); - - return pSuite; -} +// +// PatternFormatterTest.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/PatternFormatterTest.cpp#1 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "PatternFormatterTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/PatternFormatter.h" +#include "Poco/Message.h" +#include "Poco/DateTime.h" + + +using Poco::PatternFormatter; +using Poco::Message; +using Poco::DateTime; + + +PatternFormatterTest::PatternFormatterTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +PatternFormatterTest::~PatternFormatterTest() +{ +} + + +void PatternFormatterTest::testPatternFormatter() +{ + Message msg; + PatternFormatter fmt; + msg.setSource("TestSource"); + msg.setText("Test message text"); + msg.setPid(1234); + msg.setTid(1); + msg.setThread("TestThread"); + msg.setPriority(Message::PRIO_ERROR); + msg.setTime(DateTime(2005, 1, 1, 14, 30, 15, 500).timestamp()); + msg["testParam"] = "Test Parameter"; + + std::string result; + fmt.setProperty("pattern", "%Y-%m-%dT%H:%M:%S [%s] %p: %t"); + fmt.format(msg, result); + assert (result == "2005-01-01T14:30:15 [TestSource] Error: Test message text"); + + result.clear(); + fmt.setProperty("pattern", "%w, %e %b %y %H:%M:%S.%i [%s:%I:%T] %q: %t"); + fmt.format(msg, result); + assert (result == "Sat, 1 Jan 05 14:30:15.500 [TestSource:1:TestThread] E: Test message text"); + + result.clear(); + fmt.setProperty("pattern", "%Y-%m-%d %H:%M:%S [%N:%P:%s]%l-%t"); + fmt.format(msg, result); + assert (result.find("2005-01-01 14:30:15 [") == 0); + assert (result.find(":TestSource]3-Test message text") != std::string::npos); + + result.clear(); + assert (fmt.getProperty("times") == "UTC"); + fmt.setProperty("times", "local"); + fmt.format(msg, result); + assert (result.find("2005-01-01 ") == 0); + assert (result.find(":TestSource]3-Test message text") != std::string::npos); +} + + +void PatternFormatterTest::setUp() +{ +} + + +void PatternFormatterTest::tearDown() +{ +} + + +CppUnit::Test* PatternFormatterTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("PatternFormatterTest"); + + CppUnit_addTest(pSuite, PatternFormatterTest, testPatternFormatter); + + return pSuite; +} diff --git a/Foundation/testsuite/src/PatternFormatterTest.h b/Foundation/testsuite/src/PatternFormatterTest.h index 7d57cc292..da41266dc 100644 --- a/Foundation/testsuite/src/PatternFormatterTest.h +++ b/Foundation/testsuite/src/PatternFormatterTest.h @@ -1,60 +1,60 @@ -// -// PatternFormatterTest.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/PatternFormatterTest.h#1 $ -// -// Definition of the PatternFormatterTest class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 PatternFormatterTest_INCLUDED -#define PatternFormatterTest_INCLUDED - - -#include "Poco/Foundation.h" -#include "CppUnit/TestCase.h" - - -class PatternFormatterTest: public CppUnit::TestCase -{ -public: - PatternFormatterTest(const std::string& name); - ~PatternFormatterTest(); - - void testPatternFormatter(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // PatternFormatterTest_INCLUDED +// +// PatternFormatterTest.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/PatternFormatterTest.h#1 $ +// +// Definition of the PatternFormatterTest class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 PatternFormatterTest_INCLUDED +#define PatternFormatterTest_INCLUDED + + +#include "Poco/Foundation.h" +#include "CppUnit/TestCase.h" + + +class PatternFormatterTest: public CppUnit::TestCase +{ +public: + PatternFormatterTest(const std::string& name); + ~PatternFormatterTest(); + + void testPatternFormatter(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // PatternFormatterTest_INCLUDED diff --git a/Foundation/testsuite/src/PriorityEventTest.cpp b/Foundation/testsuite/src/PriorityEventTest.cpp index 55e40f9c4..e64ecc26c 100644 --- a/Foundation/testsuite/src/PriorityEventTest.cpp +++ b/Foundation/testsuite/src/PriorityEventTest.cpp @@ -1,469 +1,469 @@ -// -// PriorityEventTest.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/PriorityEventTest.cpp#2 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "PriorityEventTest.h" -#include "DummyDelegate.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/PriorityDelegate.h" -#include "Poco/PriorityExpire.h" -#include "Poco/Thread.h" -#include "Poco/Exception.h" - - -using namespace Poco; - - -#define LARGEINC 100 - - -PriorityEventTest::PriorityEventTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -PriorityEventTest::~PriorityEventTest() -{ -} - -void PriorityEventTest::testNoDelegate() -{ - int tmp = 0; - EventArgs args; - - assert (_count == 0); - Simple.notify(this, tmp); - assert (_count == 0); - - Simple += PriorityDelegate(this, &PriorityEventTest::onSimple, 0); - Simple -= PriorityDelegate(this, &PriorityEventTest::onSimple, 0); - Simple.notify(this, tmp); - assert (_count == 0); - - ConstSimple += PriorityDelegate(this, &PriorityEventTest::onConstSimple, 0); - ConstSimple -= PriorityDelegate(this, &PriorityEventTest::onConstSimple, 0); - ConstSimple.notify(this, tmp); - assert (_count == 0); - - //Note: passing &args will not work due to & - EventArgs* pArgs = &args; - Complex += PriorityDelegate(this, &PriorityEventTest::onComplex, 0); - Complex -= PriorityDelegate(this, &PriorityEventTest::onComplex, 0); - Complex.notify(this, pArgs); - assert (_count == 0); - - Complex2 += PriorityDelegate(this, &PriorityEventTest::onComplex2, 0); - Complex2 -= PriorityDelegate(this, &PriorityEventTest::onComplex2, 0); - Complex2.notify(this, args); - assert (_count == 0); - - const EventArgs* pCArgs = &args; - ConstComplex += PriorityDelegate(this, &PriorityEventTest::onConstComplex, 0); - ConstComplex -= PriorityDelegate(this, &PriorityEventTest::onConstComplex, 0); - ConstComplex.notify(this, pCArgs); - assert (_count == 0); - - Const2Complex += PriorityDelegate(this, &PriorityEventTest::onConst2Complex, 0); - Const2Complex -= PriorityDelegate(this, &PriorityEventTest::onConst2Complex, 0); - Const2Complex.notify(this, pArgs); - assert (_count == 0); -} - -void PriorityEventTest::testSingleDelegate() -{ - int tmp = 0; - EventArgs args; - - assert (_count == 0); - - Simple += PriorityDelegate(this, &PriorityEventTest::onSimple, 0); - // unregistering with a different priority --> different observer, is ignored - Simple -= PriorityDelegate(this, &PriorityEventTest::onSimple, 3); - Simple.notify(this, tmp); - assert (_count == 1); - - ConstSimple += PriorityDelegate(this, &PriorityEventTest::onConstSimple, 0); - ConstSimple -= PriorityDelegate(this, &PriorityEventTest::onConstSimple, 3); - ConstSimple.notify(this, tmp); - assert (_count == 2); - - EventArgs* pArgs = &args; - Complex += PriorityDelegate(this, &PriorityEventTest::onComplex, 0); - Complex -= PriorityDelegate(this, &PriorityEventTest::onComplex, 3); - Complex.notify(this, pArgs); - assert (_count == 3); - - Complex2 += PriorityDelegate(this, &PriorityEventTest::onComplex2, 0); - Complex2 -= PriorityDelegate(this, &PriorityEventTest::onComplex2, 3); - Complex2.notify(this, args); - assert (_count == 4); - - const EventArgs* pCArgs = &args; - ConstComplex += PriorityDelegate(this, &PriorityEventTest::onConstComplex, 0); - ConstComplex -= PriorityDelegate(this, &PriorityEventTest::onConstComplex, 3); - ConstComplex.notify(this, pCArgs); - assert (_count == 5); - - Const2Complex += PriorityDelegate(this, &PriorityEventTest::onConst2Complex, 0); - Const2Complex -= PriorityDelegate(this, &PriorityEventTest::onConst2Complex, 3); - Const2Complex.notify(this, pArgs); - assert (_count == 6); - // check if 2nd notify also works - Const2Complex.notify(this, pArgs); - assert (_count == 7); - -} - -void PriorityEventTest::testDuplicateRegister() -{ - int tmp = 0; - - assert (_count == 0); - - Simple += PriorityDelegate(this, &PriorityEventTest::onSimple, 0); - Simple += PriorityDelegate(this, &PriorityEventTest::onSimple, 0); - Simple.notify(this, tmp); - assert (_count == 1); - Simple -= PriorityDelegate(this, &PriorityEventTest::onSimple, 0); - Simple.notify(this, tmp); - assert (_count == 1); - - Simple += PriorityDelegate(this, &PriorityEventTest::onSimple, 0); - Simple += PriorityDelegate(this, &PriorityEventTest::onSimpleOther, 1); - Simple.notify(this, tmp); - assert (_count == 2 + LARGEINC); - Simple -= PriorityDelegate(this, &PriorityEventTest::onSimpleOther, 1); - Simple.notify(this, tmp); - assert (_count == 3 + LARGEINC); -} - -void PriorityEventTest::testDuplicateUnregister() -{ - // duplicate unregister shouldn't give an error, - int tmp = 0; - - assert (_count == 0); - - Simple -= PriorityDelegate(this, &PriorityEventTest::onSimple, 0); // should work - Simple.notify(this, tmp); - assert (_count == 0); - - Simple += PriorityDelegate(this, &PriorityEventTest::onSimple, 0); - Simple.notify(this, tmp); - assert (_count == 1); - - Simple -= PriorityDelegate(this, &PriorityEventTest::onSimple, 0); - Simple.notify(this, tmp); - assert (_count == 1); - - Simple -= PriorityDelegate(this, &PriorityEventTest::onSimple, 0); - Simple.notify(this, tmp); - assert (_count == 1); -} - - -void PriorityEventTest::testDisabling() -{ - int tmp = 0; - - assert (_count == 0); - - Simple += PriorityDelegate(this, &PriorityEventTest::onSimple, 0); - Simple.disable(); - Simple.notify(this, tmp); - assert (_count == 0); - Simple.enable(); - Simple.notify(this, tmp); - assert (_count == 1); - - // unregister should also work with disabled event - Simple.disable(); - Simple -= PriorityDelegate(this, &PriorityEventTest::onSimple, 0); - Simple.enable(); - Simple.notify(this, tmp); - assert (_count == 1); -} - -void PriorityEventTest::testPriorityOrder() -{ - DummyDelegate o1; - DummyDelegate o2; - - assert (_count == 0); - - Simple += PriorityDelegate(&o2, &DummyDelegate::onSimple2, 1); - Simple += PriorityDelegate(&o1, &DummyDelegate::onSimple, 0); - - int tmp = 0; - Simple.notify(this, tmp); - assert (tmp == 2); - - Simple -= PriorityDelegate(&o1, &DummyDelegate::onSimple, 0); - Simple -= PriorityDelegate(&o2, &DummyDelegate::onSimple2, 1); - - // now try with the wrong order - Simple += PriorityDelegate(&o2, &DummyDelegate::onSimple2, 0); - Simple += PriorityDelegate(&o1, &DummyDelegate::onSimple, 1); - - try - { - tmp = 0; - Simple.notify(this, tmp); - failmsg ("Notify should not work"); - } - catch (Poco::InvalidArgumentException&) - { - } - - Simple -= PriorityDelegate(&o2, &DummyDelegate::onSimple2, 0); - Simple -= PriorityDelegate(&o1, &DummyDelegate::onSimple, 1); -} - -void PriorityEventTest::testPriorityOrderExpire() -{ - // expire must not break order! - DummyDelegate o1; - DummyDelegate o2; - - assert (_count == 0); - - Simple += PriorityExpire(PriorityDelegate(&o2, &DummyDelegate::onSimple2, 1), 500000); - Simple += PriorityExpire(PriorityDelegate(&o1, &DummyDelegate::onSimple, 0), 500000); - int tmp = 0; - Simple.notify(this, tmp); - assert (tmp == 2); - - // both ways of unregistering should work - Simple -= PriorityExpire(PriorityDelegate(&o1, &DummyDelegate::onSimple, 0), 600000); - Simple -= PriorityDelegate(&o2, &DummyDelegate::onSimple2, 1); - Simple.notify(this, tmp); - assert (tmp == 2); - - // now start mixing of expire and non expire - tmp = 0; - Simple += PriorityExpire(PriorityDelegate(&o2, &DummyDelegate::onSimple2, 1), 500000); - Simple += PriorityDelegate(&o1, &DummyDelegate::onSimple, 0); - - Simple.notify(this, tmp); - assert (tmp == 2); - - Simple -= PriorityDelegate(&o2, &DummyDelegate::onSimple2, 1); - // it is not forbidden to unregister a non expiring event with an expire decorator (it is just stupid ;-)) - Simple -= PriorityExpire(PriorityDelegate(&o1, &DummyDelegate::onSimple, 0), 600000); - Simple.notify(this, tmp); - assert (tmp == 2); - - // now try with the wrong order - Simple += PriorityExpire(PriorityDelegate(&o2, &DummyDelegate::onSimple2, 0), 500000); - Simple += PriorityDelegate(&o1, &DummyDelegate::onSimple, 1); - - try - { - tmp = 0; - Simple.notify(this, tmp); - failmsg ("Notify should not work"); - } - catch (Poco::InvalidArgumentException&) - { - } - - Simple -= PriorityExpire(PriorityDelegate(&o2, &DummyDelegate::onSimple2, 0), 500000); - Simple -= PriorityDelegate(&o1, &DummyDelegate::onSimple, 1); - -} - -void PriorityEventTest::testExpire() -{ - int tmp = 0; - - assert (_count == 0); - - Simple += PriorityExpire(PriorityDelegate(this, &PriorityEventTest::onSimple, 1), 500); - Simple.notify(this, tmp); - assert (_count == 1); - Poco::Thread::sleep(700); - Simple.notify(this, tmp); - assert (_count == 1); - Simple -= PriorityExpire(PriorityDelegate(this, &PriorityEventTest::onSimple, 1), 500); -} - - -void PriorityEventTest::testExpireReRegister() -{ - int tmp = 0; - - assert (_count == 0); - - Simple += PriorityExpire(PriorityDelegate(this, &PriorityEventTest::onSimple, 1), 500); - Simple.notify(this, tmp); - assert (_count == 1); - Poco::Thread::sleep(200); - Simple.notify(this, tmp); - assert (_count == 2); - // renew registration - Simple += PriorityExpire(PriorityDelegate(this, &PriorityEventTest::onSimple, 1), 600); - Poco::Thread::sleep(400); - Simple.notify(this, tmp); - assert (_count == 3); - Poco::Thread::sleep(300); - Simple.notify(this, tmp); - assert (_count == 3); -} - - -void PriorityEventTest::testReturnParams() -{ - DummyDelegate o1; - Simple += PriorityDelegate(&o1, &DummyDelegate::onSimple, 0); - - int tmp = 0; - Simple.notify(this, tmp); - assert (tmp == 1); -} - -void PriorityEventTest::testOverwriteDelegate() -{ - DummyDelegate o1; - Simple += PriorityDelegate(&o1, &DummyDelegate::onSimple2, 0); - // o1 can only have one entry per priority, thus the next line will replace the entry - Simple += PriorityDelegate(&o1, &DummyDelegate::onSimple, 0); - - int tmp = 0; // onsimple requires 0 as input - Simple.notify(this, tmp); - assert (tmp == 1); - // now overwrite with onsimple2 with requires as input tmp = 1 - Simple += PriorityExpire(PriorityDelegate(&o1, &DummyDelegate::onSimple2, 0), 23000); - Simple.notify(this, tmp); - assert (tmp == 2); - Simple -= PriorityExpire(PriorityDelegate(&o1, &DummyDelegate::onSimple2, 0), 23000); -} - -void PriorityEventTest::testAsyncNotify() -{ - Poco::PriorityEvent* pSimple= new Poco::PriorityEvent(); - (*pSimple) += PriorityDelegate(this, &PriorityEventTest::onAsync, 0); - assert (_count == 0); - int tmp = 0; - Poco::ActiveResultretArg = pSimple->notifyAsync(this, tmp); - delete pSimple; // must work even when the event got deleted! - pSimple = NULL; - assert (_count == 0); - retArg.wait(); - assert (retArg.data() == tmp); - assert (_count == LARGEINC); - -} - -void PriorityEventTest::onSimple(const void* pSender, int& i) -{ - _count++; -} - -void PriorityEventTest::onSimpleOther(const void* pSender, int& i) -{ - _count += LARGEINC ; -} - -void PriorityEventTest::onConstSimple(const void* pSender, const int& i) -{ - _count++; -} - -void PriorityEventTest::onComplex(const void* pSender, Poco::EventArgs* & i) -{ - _count++; -} - -void PriorityEventTest::onComplex2(const void* pSender, Poco::EventArgs & i) -{ - _count++; -} - -void PriorityEventTest::onConstComplex(const void* pSender, const Poco::EventArgs*& i) -{ - _count++; -} - -void PriorityEventTest::onConst2Complex(const void* pSender, const Poco::EventArgs * const & i) -{ - _count++; -} - -void PriorityEventTest::onAsync(const void* pSender, int& i) -{ - Poco::Thread::sleep(700); - _count += LARGEINC ; -} - -int PriorityEventTest::getCount() const -{ - return _count; -} - -void PriorityEventTest::setUp() -{ - _count = 0; - // must clear events, otherwise repeating test executions will fail - // because tests are only created once, only setup is called before - // each test run - Simple.clear(); - ConstSimple.clear(); - Complex.clear(); - Complex2.clear(); - ConstComplex.clear(); - Const2Complex.clear(); -} - - -void PriorityEventTest::tearDown() -{ -} - - -CppUnit::Test* PriorityEventTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("PriorityEventTest"); - - CppUnit_addTest(pSuite, PriorityEventTest, testNoDelegate); - CppUnit_addTest(pSuite, PriorityEventTest, testSingleDelegate); - CppUnit_addTest(pSuite, PriorityEventTest, testReturnParams); - CppUnit_addTest(pSuite, PriorityEventTest, testDuplicateRegister); - CppUnit_addTest(pSuite, PriorityEventTest, testDuplicateUnregister); - CppUnit_addTest(pSuite, PriorityEventTest, testDisabling); - CppUnit_addTest(pSuite, PriorityEventTest, testPriorityOrder); - CppUnit_addTest(pSuite, PriorityEventTest, testPriorityOrderExpire); - CppUnit_addTest(pSuite, PriorityEventTest, testExpire); - CppUnit_addTest(pSuite, PriorityEventTest, testExpireReRegister); - CppUnit_addTest(pSuite, PriorityEventTest, testOverwriteDelegate); - CppUnit_addTest(pSuite, PriorityEventTest, testAsyncNotify); - return pSuite; -} +// +// PriorityEventTest.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/PriorityEventTest.cpp#2 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "PriorityEventTest.h" +#include "DummyDelegate.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/PriorityDelegate.h" +#include "Poco/PriorityExpire.h" +#include "Poco/Thread.h" +#include "Poco/Exception.h" + + +using namespace Poco; + + +#define LARGEINC 100 + + +PriorityEventTest::PriorityEventTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +PriorityEventTest::~PriorityEventTest() +{ +} + +void PriorityEventTest::testNoDelegate() +{ + int tmp = 0; + EventArgs args; + + assert (_count == 0); + Simple.notify(this, tmp); + assert (_count == 0); + + Simple += PriorityDelegate(this, &PriorityEventTest::onSimple, 0); + Simple -= PriorityDelegate(this, &PriorityEventTest::onSimple, 0); + Simple.notify(this, tmp); + assert (_count == 0); + + ConstSimple += PriorityDelegate(this, &PriorityEventTest::onConstSimple, 0); + ConstSimple -= PriorityDelegate(this, &PriorityEventTest::onConstSimple, 0); + ConstSimple.notify(this, tmp); + assert (_count == 0); + + //Note: passing &args will not work due to & + EventArgs* pArgs = &args; + Complex += PriorityDelegate(this, &PriorityEventTest::onComplex, 0); + Complex -= PriorityDelegate(this, &PriorityEventTest::onComplex, 0); + Complex.notify(this, pArgs); + assert (_count == 0); + + Complex2 += PriorityDelegate(this, &PriorityEventTest::onComplex2, 0); + Complex2 -= PriorityDelegate(this, &PriorityEventTest::onComplex2, 0); + Complex2.notify(this, args); + assert (_count == 0); + + const EventArgs* pCArgs = &args; + ConstComplex += PriorityDelegate(this, &PriorityEventTest::onConstComplex, 0); + ConstComplex -= PriorityDelegate(this, &PriorityEventTest::onConstComplex, 0); + ConstComplex.notify(this, pCArgs); + assert (_count == 0); + + Const2Complex += PriorityDelegate(this, &PriorityEventTest::onConst2Complex, 0); + Const2Complex -= PriorityDelegate(this, &PriorityEventTest::onConst2Complex, 0); + Const2Complex.notify(this, pArgs); + assert (_count == 0); +} + +void PriorityEventTest::testSingleDelegate() +{ + int tmp = 0; + EventArgs args; + + assert (_count == 0); + + Simple += PriorityDelegate(this, &PriorityEventTest::onSimple, 0); + // unregistering with a different priority --> different observer, is ignored + Simple -= PriorityDelegate(this, &PriorityEventTest::onSimple, 3); + Simple.notify(this, tmp); + assert (_count == 1); + + ConstSimple += PriorityDelegate(this, &PriorityEventTest::onConstSimple, 0); + ConstSimple -= PriorityDelegate(this, &PriorityEventTest::onConstSimple, 3); + ConstSimple.notify(this, tmp); + assert (_count == 2); + + EventArgs* pArgs = &args; + Complex += PriorityDelegate(this, &PriorityEventTest::onComplex, 0); + Complex -= PriorityDelegate(this, &PriorityEventTest::onComplex, 3); + Complex.notify(this, pArgs); + assert (_count == 3); + + Complex2 += PriorityDelegate(this, &PriorityEventTest::onComplex2, 0); + Complex2 -= PriorityDelegate(this, &PriorityEventTest::onComplex2, 3); + Complex2.notify(this, args); + assert (_count == 4); + + const EventArgs* pCArgs = &args; + ConstComplex += PriorityDelegate(this, &PriorityEventTest::onConstComplex, 0); + ConstComplex -= PriorityDelegate(this, &PriorityEventTest::onConstComplex, 3); + ConstComplex.notify(this, pCArgs); + assert (_count == 5); + + Const2Complex += PriorityDelegate(this, &PriorityEventTest::onConst2Complex, 0); + Const2Complex -= PriorityDelegate(this, &PriorityEventTest::onConst2Complex, 3); + Const2Complex.notify(this, pArgs); + assert (_count == 6); + // check if 2nd notify also works + Const2Complex.notify(this, pArgs); + assert (_count == 7); + +} + +void PriorityEventTest::testDuplicateRegister() +{ + int tmp = 0; + + assert (_count == 0); + + Simple += PriorityDelegate(this, &PriorityEventTest::onSimple, 0); + Simple += PriorityDelegate(this, &PriorityEventTest::onSimple, 0); + Simple.notify(this, tmp); + assert (_count == 1); + Simple -= PriorityDelegate(this, &PriorityEventTest::onSimple, 0); + Simple.notify(this, tmp); + assert (_count == 1); + + Simple += PriorityDelegate(this, &PriorityEventTest::onSimple, 0); + Simple += PriorityDelegate(this, &PriorityEventTest::onSimpleOther, 1); + Simple.notify(this, tmp); + assert (_count == 2 + LARGEINC); + Simple -= PriorityDelegate(this, &PriorityEventTest::onSimpleOther, 1); + Simple.notify(this, tmp); + assert (_count == 3 + LARGEINC); +} + +void PriorityEventTest::testDuplicateUnregister() +{ + // duplicate unregister shouldn't give an error, + int tmp = 0; + + assert (_count == 0); + + Simple -= PriorityDelegate(this, &PriorityEventTest::onSimple, 0); // should work + Simple.notify(this, tmp); + assert (_count == 0); + + Simple += PriorityDelegate(this, &PriorityEventTest::onSimple, 0); + Simple.notify(this, tmp); + assert (_count == 1); + + Simple -= PriorityDelegate(this, &PriorityEventTest::onSimple, 0); + Simple.notify(this, tmp); + assert (_count == 1); + + Simple -= PriorityDelegate(this, &PriorityEventTest::onSimple, 0); + Simple.notify(this, tmp); + assert (_count == 1); +} + + +void PriorityEventTest::testDisabling() +{ + int tmp = 0; + + assert (_count == 0); + + Simple += PriorityDelegate(this, &PriorityEventTest::onSimple, 0); + Simple.disable(); + Simple.notify(this, tmp); + assert (_count == 0); + Simple.enable(); + Simple.notify(this, tmp); + assert (_count == 1); + + // unregister should also work with disabled event + Simple.disable(); + Simple -= PriorityDelegate(this, &PriorityEventTest::onSimple, 0); + Simple.enable(); + Simple.notify(this, tmp); + assert (_count == 1); +} + +void PriorityEventTest::testPriorityOrder() +{ + DummyDelegate o1; + DummyDelegate o2; + + assert (_count == 0); + + Simple += PriorityDelegate(&o2, &DummyDelegate::onSimple2, 1); + Simple += PriorityDelegate(&o1, &DummyDelegate::onSimple, 0); + + int tmp = 0; + Simple.notify(this, tmp); + assert (tmp == 2); + + Simple -= PriorityDelegate(&o1, &DummyDelegate::onSimple, 0); + Simple -= PriorityDelegate(&o2, &DummyDelegate::onSimple2, 1); + + // now try with the wrong order + Simple += PriorityDelegate(&o2, &DummyDelegate::onSimple2, 0); + Simple += PriorityDelegate(&o1, &DummyDelegate::onSimple, 1); + + try + { + tmp = 0; + Simple.notify(this, tmp); + failmsg ("Notify should not work"); + } + catch (Poco::InvalidArgumentException&) + { + } + + Simple -= PriorityDelegate(&o2, &DummyDelegate::onSimple2, 0); + Simple -= PriorityDelegate(&o1, &DummyDelegate::onSimple, 1); +} + +void PriorityEventTest::testPriorityOrderExpire() +{ + // expire must not break order! + DummyDelegate o1; + DummyDelegate o2; + + assert (_count == 0); + + Simple += PriorityExpire(PriorityDelegate(&o2, &DummyDelegate::onSimple2, 1), 500000); + Simple += PriorityExpire(PriorityDelegate(&o1, &DummyDelegate::onSimple, 0), 500000); + int tmp = 0; + Simple.notify(this, tmp); + assert (tmp == 2); + + // both ways of unregistering should work + Simple -= PriorityExpire(PriorityDelegate(&o1, &DummyDelegate::onSimple, 0), 600000); + Simple -= PriorityDelegate(&o2, &DummyDelegate::onSimple2, 1); + Simple.notify(this, tmp); + assert (tmp == 2); + + // now start mixing of expire and non expire + tmp = 0; + Simple += PriorityExpire(PriorityDelegate(&o2, &DummyDelegate::onSimple2, 1), 500000); + Simple += PriorityDelegate(&o1, &DummyDelegate::onSimple, 0); + + Simple.notify(this, tmp); + assert (tmp == 2); + + Simple -= PriorityDelegate(&o2, &DummyDelegate::onSimple2, 1); + // it is not forbidden to unregister a non expiring event with an expire decorator (it is just stupid ;-)) + Simple -= PriorityExpire(PriorityDelegate(&o1, &DummyDelegate::onSimple, 0), 600000); + Simple.notify(this, tmp); + assert (tmp == 2); + + // now try with the wrong order + Simple += PriorityExpire(PriorityDelegate(&o2, &DummyDelegate::onSimple2, 0), 500000); + Simple += PriorityDelegate(&o1, &DummyDelegate::onSimple, 1); + + try + { + tmp = 0; + Simple.notify(this, tmp); + failmsg ("Notify should not work"); + } + catch (Poco::InvalidArgumentException&) + { + } + + Simple -= PriorityExpire(PriorityDelegate(&o2, &DummyDelegate::onSimple2, 0), 500000); + Simple -= PriorityDelegate(&o1, &DummyDelegate::onSimple, 1); + +} + +void PriorityEventTest::testExpire() +{ + int tmp = 0; + + assert (_count == 0); + + Simple += PriorityExpire(PriorityDelegate(this, &PriorityEventTest::onSimple, 1), 500); + Simple.notify(this, tmp); + assert (_count == 1); + Poco::Thread::sleep(700); + Simple.notify(this, tmp); + assert (_count == 1); + Simple -= PriorityExpire(PriorityDelegate(this, &PriorityEventTest::onSimple, 1), 500); +} + + +void PriorityEventTest::testExpireReRegister() +{ + int tmp = 0; + + assert (_count == 0); + + Simple += PriorityExpire(PriorityDelegate(this, &PriorityEventTest::onSimple, 1), 500); + Simple.notify(this, tmp); + assert (_count == 1); + Poco::Thread::sleep(200); + Simple.notify(this, tmp); + assert (_count == 2); + // renew registration + Simple += PriorityExpire(PriorityDelegate(this, &PriorityEventTest::onSimple, 1), 600); + Poco::Thread::sleep(400); + Simple.notify(this, tmp); + assert (_count == 3); + Poco::Thread::sleep(300); + Simple.notify(this, tmp); + assert (_count == 3); +} + + +void PriorityEventTest::testReturnParams() +{ + DummyDelegate o1; + Simple += PriorityDelegate(&o1, &DummyDelegate::onSimple, 0); + + int tmp = 0; + Simple.notify(this, tmp); + assert (tmp == 1); +} + +void PriorityEventTest::testOverwriteDelegate() +{ + DummyDelegate o1; + Simple += PriorityDelegate(&o1, &DummyDelegate::onSimple2, 0); + // o1 can only have one entry per priority, thus the next line will replace the entry + Simple += PriorityDelegate(&o1, &DummyDelegate::onSimple, 0); + + int tmp = 0; // onsimple requires 0 as input + Simple.notify(this, tmp); + assert (tmp == 1); + // now overwrite with onsimple2 with requires as input tmp = 1 + Simple += PriorityExpire(PriorityDelegate(&o1, &DummyDelegate::onSimple2, 0), 23000); + Simple.notify(this, tmp); + assert (tmp == 2); + Simple -= PriorityExpire(PriorityDelegate(&o1, &DummyDelegate::onSimple2, 0), 23000); +} + +void PriorityEventTest::testAsyncNotify() +{ + Poco::PriorityEvent* pSimple= new Poco::PriorityEvent(); + (*pSimple) += PriorityDelegate(this, &PriorityEventTest::onAsync, 0); + assert (_count == 0); + int tmp = 0; + Poco::ActiveResultretArg = pSimple->notifyAsync(this, tmp); + delete pSimple; // must work even when the event got deleted! + pSimple = NULL; + assert (_count == 0); + retArg.wait(); + assert (retArg.data() == tmp); + assert (_count == LARGEINC); + +} + +void PriorityEventTest::onSimple(const void* pSender, int& i) +{ + _count++; +} + +void PriorityEventTest::onSimpleOther(const void* pSender, int& i) +{ + _count += LARGEINC ; +} + +void PriorityEventTest::onConstSimple(const void* pSender, const int& i) +{ + _count++; +} + +void PriorityEventTest::onComplex(const void* pSender, Poco::EventArgs* & i) +{ + _count++; +} + +void PriorityEventTest::onComplex2(const void* pSender, Poco::EventArgs & i) +{ + _count++; +} + +void PriorityEventTest::onConstComplex(const void* pSender, const Poco::EventArgs*& i) +{ + _count++; +} + +void PriorityEventTest::onConst2Complex(const void* pSender, const Poco::EventArgs * const & i) +{ + _count++; +} + +void PriorityEventTest::onAsync(const void* pSender, int& i) +{ + Poco::Thread::sleep(700); + _count += LARGEINC ; +} + +int PriorityEventTest::getCount() const +{ + return _count; +} + +void PriorityEventTest::setUp() +{ + _count = 0; + // must clear events, otherwise repeating test executions will fail + // because tests are only created once, only setup is called before + // each test run + Simple.clear(); + ConstSimple.clear(); + Complex.clear(); + Complex2.clear(); + ConstComplex.clear(); + Const2Complex.clear(); +} + + +void PriorityEventTest::tearDown() +{ +} + + +CppUnit::Test* PriorityEventTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("PriorityEventTest"); + + CppUnit_addTest(pSuite, PriorityEventTest, testNoDelegate); + CppUnit_addTest(pSuite, PriorityEventTest, testSingleDelegate); + CppUnit_addTest(pSuite, PriorityEventTest, testReturnParams); + CppUnit_addTest(pSuite, PriorityEventTest, testDuplicateRegister); + CppUnit_addTest(pSuite, PriorityEventTest, testDuplicateUnregister); + CppUnit_addTest(pSuite, PriorityEventTest, testDisabling); + CppUnit_addTest(pSuite, PriorityEventTest, testPriorityOrder); + CppUnit_addTest(pSuite, PriorityEventTest, testPriorityOrderExpire); + CppUnit_addTest(pSuite, PriorityEventTest, testExpire); + CppUnit_addTest(pSuite, PriorityEventTest, testExpireReRegister); + CppUnit_addTest(pSuite, PriorityEventTest, testOverwriteDelegate); + CppUnit_addTest(pSuite, PriorityEventTest, testAsyncNotify); + return pSuite; +} diff --git a/Foundation/testsuite/src/PriorityEventTest.h b/Foundation/testsuite/src/PriorityEventTest.h index 56082bfba..e87618022 100644 --- a/Foundation/testsuite/src/PriorityEventTest.h +++ b/Foundation/testsuite/src/PriorityEventTest.h @@ -1,91 +1,91 @@ -// -// PriorityEventTest.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/PriorityEventTest.h#2 $ -// -// Definition of the PriorityEventTest class. -// -// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 PriorityEventTest_INCLUDED -#define PriorityEventTest_INCLUDED - - -#include "Poco/Foundation.h" -#include "CppUnit/TestCase.h" -#include "Poco/PriorityEvent.h" -#include "Poco/EventArgs.h" - - -class PriorityEventTest: public CppUnit::TestCase -{ - Poco::PriorityEvent Simple; - Poco::PriorityEvent ConstSimple; - Poco::PriorityEvent Complex; - Poco::PriorityEvent Complex2; - Poco::PriorityEvent ConstComplex; - Poco::PriorityEvent Const2Complex; -public: - PriorityEventTest(const std::string& name); - ~PriorityEventTest(); - - void testNoDelegate(); - void testSingleDelegate(); - void testDuplicateRegister(); - void testDuplicateUnregister(); - void testDisabling(); - void testPriorityOrder(); - void testPriorityOrderExpire(); - void testExpire(); - void testExpireReRegister(); - void testReturnParams(); - void testOverwriteDelegate(); - void testAsyncNotify(); - - void setUp(); - void tearDown(); - static CppUnit::Test* suite(); - -protected: - - void onSimple(const void* pSender, int& i); - void onSimpleOther(const void* pSender, int& i); - void onConstSimple(const void* pSender, const int& i); - void onComplex(const void* pSender, Poco::EventArgs* & i); - void onComplex2(const void* pSender, Poco::EventArgs & i); - void onConstComplex(const void* pSender, const Poco::EventArgs*& i); - void onConst2Complex(const void* pSender, const Poco::EventArgs * const & i); - void onAsync(const void* pSender, int& i); - - int getCount() const; -private: - int _count; -}; - - -#endif // PriorityEventTest_INCLUDED +// +// PriorityEventTest.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/PriorityEventTest.h#2 $ +// +// Definition of the PriorityEventTest class. +// +// Copyright (c) 2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 PriorityEventTest_INCLUDED +#define PriorityEventTest_INCLUDED + + +#include "Poco/Foundation.h" +#include "CppUnit/TestCase.h" +#include "Poco/PriorityEvent.h" +#include "Poco/EventArgs.h" + + +class PriorityEventTest: public CppUnit::TestCase +{ + Poco::PriorityEvent Simple; + Poco::PriorityEvent ConstSimple; + Poco::PriorityEvent Complex; + Poco::PriorityEvent Complex2; + Poco::PriorityEvent ConstComplex; + Poco::PriorityEvent Const2Complex; +public: + PriorityEventTest(const std::string& name); + ~PriorityEventTest(); + + void testNoDelegate(); + void testSingleDelegate(); + void testDuplicateRegister(); + void testDuplicateUnregister(); + void testDisabling(); + void testPriorityOrder(); + void testPriorityOrderExpire(); + void testExpire(); + void testExpireReRegister(); + void testReturnParams(); + void testOverwriteDelegate(); + void testAsyncNotify(); + + void setUp(); + void tearDown(); + static CppUnit::Test* suite(); + +protected: + + void onSimple(const void* pSender, int& i); + void onSimpleOther(const void* pSender, int& i); + void onConstSimple(const void* pSender, const int& i); + void onComplex(const void* pSender, Poco::EventArgs* & i); + void onComplex2(const void* pSender, Poco::EventArgs & i); + void onConstComplex(const void* pSender, const Poco::EventArgs*& i); + void onConst2Complex(const void* pSender, const Poco::EventArgs * const & i); + void onAsync(const void* pSender, int& i); + + int getCount() const; +private: + int _count; +}; + + +#endif // PriorityEventTest_INCLUDED diff --git a/Foundation/testsuite/src/ProcessTest.cpp b/Foundation/testsuite/src/ProcessTest.cpp index 51dfdfa62..a982c1b36 100644 --- a/Foundation/testsuite/src/ProcessTest.cpp +++ b/Foundation/testsuite/src/ProcessTest.cpp @@ -1,158 +1,158 @@ -// -// ProcessTest.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/ProcessTest.cpp#1 $ -// -// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "ProcessTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/Process.h" -#include "Poco/Pipe.h" -#include "Poco/PipeStream.h" - - -using Poco::Process; -using Poco::ProcessHandle; -using Poco::Pipe; -using Poco::PipeInputStream; -using Poco::PipeOutputStream; - - -ProcessTest::ProcessTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -ProcessTest::~ProcessTest() -{ -} - - -void ProcessTest::testLaunch() -{ - std::string name("TestApp"); - std::string cmd; -#if defined(_DEBUG) - name += "d"; -#endif - -#if defined(POCO_OS_FAMILY_UNIX) - cmd = "./"; - cmd += name; -#else - cmd = name; -#endif - - std::vector args; - args.push_back("arg1"); - args.push_back("arg2"); - args.push_back("arg3"); - ProcessHandle ph = Process::launch(cmd, args); - int rc = ph.wait(); - assert (rc == 3); -} - - -void ProcessTest::testLaunchRedirectIn() -{ - std::string name("TestApp"); - std::string cmd; -#if defined(_DEBUG) - name += "d"; -#endif - -#if defined(POCO_OS_FAMILY_UNIX) - cmd = "./"; - cmd += name; -#else - cmd = name; -#endif - - std::vector args; - args.push_back("-count"); - Pipe inPipe; - ProcessHandle ph = Process::launch(cmd, args, &inPipe, 0, 0); - PipeOutputStream ostr(inPipe); - ostr << std::string(100, 'x'); - ostr.close(); - int rc = ph.wait(); - assert (rc == 100); -} - - -void ProcessTest::testLaunchRedirectOut() -{ - std::string name("TestApp"); - std::string cmd; -#if defined(_DEBUG) - name += "d"; -#endif - -#if defined(POCO_OS_FAMILY_UNIX) - cmd = "./"; - cmd += name; -#else - cmd = name; -#endif - - std::vector args; - args.push_back("-hello"); - Pipe outPipe; - ProcessHandle ph = Process::launch(cmd, args, 0, &outPipe, 0); - PipeInputStream istr(outPipe); - std::string s; - int c = istr.get(); - while (c != -1) { s += (char) c; c = istr.get(); } - assert (s == "Hello, world!"); - int rc = ph.wait(); - assert (rc == 1); -} - - -void ProcessTest::setUp() -{ -} - - -void ProcessTest::tearDown() -{ -} - - -CppUnit::Test* ProcessTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("ProcessTest"); - - CppUnit_addTest(pSuite, ProcessTest, testLaunch); - CppUnit_addTest(pSuite, ProcessTest, testLaunchRedirectIn); - CppUnit_addTest(pSuite, ProcessTest, testLaunchRedirectOut); - - return pSuite; -} +// +// ProcessTest.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/ProcessTest.cpp#1 $ +// +// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "ProcessTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/Process.h" +#include "Poco/Pipe.h" +#include "Poco/PipeStream.h" + + +using Poco::Process; +using Poco::ProcessHandle; +using Poco::Pipe; +using Poco::PipeInputStream; +using Poco::PipeOutputStream; + + +ProcessTest::ProcessTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +ProcessTest::~ProcessTest() +{ +} + + +void ProcessTest::testLaunch() +{ + std::string name("TestApp"); + std::string cmd; +#if defined(_DEBUG) + name += "d"; +#endif + +#if defined(POCO_OS_FAMILY_UNIX) + cmd = "./"; + cmd += name; +#else + cmd = name; +#endif + + std::vector args; + args.push_back("arg1"); + args.push_back("arg2"); + args.push_back("arg3"); + ProcessHandle ph = Process::launch(cmd, args); + int rc = ph.wait(); + assert (rc == 3); +} + + +void ProcessTest::testLaunchRedirectIn() +{ + std::string name("TestApp"); + std::string cmd; +#if defined(_DEBUG) + name += "d"; +#endif + +#if defined(POCO_OS_FAMILY_UNIX) + cmd = "./"; + cmd += name; +#else + cmd = name; +#endif + + std::vector args; + args.push_back("-count"); + Pipe inPipe; + ProcessHandle ph = Process::launch(cmd, args, &inPipe, 0, 0); + PipeOutputStream ostr(inPipe); + ostr << std::string(100, 'x'); + ostr.close(); + int rc = ph.wait(); + assert (rc == 100); +} + + +void ProcessTest::testLaunchRedirectOut() +{ + std::string name("TestApp"); + std::string cmd; +#if defined(_DEBUG) + name += "d"; +#endif + +#if defined(POCO_OS_FAMILY_UNIX) + cmd = "./"; + cmd += name; +#else + cmd = name; +#endif + + std::vector args; + args.push_back("-hello"); + Pipe outPipe; + ProcessHandle ph = Process::launch(cmd, args, 0, &outPipe, 0); + PipeInputStream istr(outPipe); + std::string s; + int c = istr.get(); + while (c != -1) { s += (char) c; c = istr.get(); } + assert (s == "Hello, world!"); + int rc = ph.wait(); + assert (rc == 1); +} + + +void ProcessTest::setUp() +{ +} + + +void ProcessTest::tearDown() +{ +} + + +CppUnit::Test* ProcessTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("ProcessTest"); + + CppUnit_addTest(pSuite, ProcessTest, testLaunch); + CppUnit_addTest(pSuite, ProcessTest, testLaunchRedirectIn); + CppUnit_addTest(pSuite, ProcessTest, testLaunchRedirectOut); + + return pSuite; +} diff --git a/Foundation/testsuite/src/ProcessTest.h b/Foundation/testsuite/src/ProcessTest.h index b144d2620..ddfbae723 100644 --- a/Foundation/testsuite/src/ProcessTest.h +++ b/Foundation/testsuite/src/ProcessTest.h @@ -1,62 +1,62 @@ -// -// ProcessTest.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/ProcessTest.h#1 $ -// -// Definition of the ProcessTest class. -// -// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 ProcessTest_INCLUDED -#define ProcessTest_INCLUDED - - -#include "Poco/Foundation.h" -#include "CppUnit/TestCase.h" - - -class ProcessTest: public CppUnit::TestCase -{ -public: - ProcessTest(const std::string& name); - ~ProcessTest(); - - void testLaunch(); - void testLaunchRedirectIn(); - void testLaunchRedirectOut(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // ProcessTest_INCLUDED +// +// ProcessTest.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/ProcessTest.h#1 $ +// +// Definition of the ProcessTest class. +// +// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 ProcessTest_INCLUDED +#define ProcessTest_INCLUDED + + +#include "Poco/Foundation.h" +#include "CppUnit/TestCase.h" + + +class ProcessTest: public CppUnit::TestCase +{ +public: + ProcessTest(const std::string& name); + ~ProcessTest(); + + void testLaunch(); + void testLaunchRedirectIn(); + void testLaunchRedirectOut(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // ProcessTest_INCLUDED diff --git a/Foundation/testsuite/src/ProcessesTestSuite.cpp b/Foundation/testsuite/src/ProcessesTestSuite.cpp index ab601a5d5..96a7ef54a 100644 --- a/Foundation/testsuite/src/ProcessesTestSuite.cpp +++ b/Foundation/testsuite/src/ProcessesTestSuite.cpp @@ -1,48 +1,48 @@ -// -// ProcessesTestSuite.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/ProcessesTestSuite.cpp#1 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "ProcessesTestSuite.h" -#include "ProcessTest.h" -#include "NamedMutexTest.h" -#include "NamedEventTest.h" - - -CppUnit::Test* ProcessesTestSuite::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("ProcessesTestSuite"); - - pSuite->addTest(ProcessTest::suite()); - pSuite->addTest(NamedMutexTest::suite()); - pSuite->addTest(NamedEventTest::suite()); - - return pSuite; -} +// +// ProcessesTestSuite.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/ProcessesTestSuite.cpp#1 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "ProcessesTestSuite.h" +#include "ProcessTest.h" +#include "NamedMutexTest.h" +#include "NamedEventTest.h" + + +CppUnit::Test* ProcessesTestSuite::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("ProcessesTestSuite"); + + pSuite->addTest(ProcessTest::suite()); + pSuite->addTest(NamedMutexTest::suite()); + pSuite->addTest(NamedEventTest::suite()); + + return pSuite; +} diff --git a/Foundation/testsuite/src/ProcessesTestSuite.h b/Foundation/testsuite/src/ProcessesTestSuite.h index e308949fb..94b1829da 100644 --- a/Foundation/testsuite/src/ProcessesTestSuite.h +++ b/Foundation/testsuite/src/ProcessesTestSuite.h @@ -1,49 +1,49 @@ -// -// ProcessesTestSuite.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/ProcessesTestSuite.h#1 $ -// -// Definition of the ProcessesTestSuite class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 ProcessesTestSuite_INCLUDED -#define ProcessesTestSuite_INCLUDED - - -#include "CppUnit/TestSuite.h" - - -class ProcessesTestSuite -{ -public: - static CppUnit::Test* suite(); -}; - - -#endif // ProcessesTestSuite_INCLUDED +// +// ProcessesTestSuite.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/ProcessesTestSuite.h#1 $ +// +// Definition of the ProcessesTestSuite class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 ProcessesTestSuite_INCLUDED +#define ProcessesTestSuite_INCLUDED + + +#include "CppUnit/TestSuite.h" + + +class ProcessesTestSuite +{ +public: + static CppUnit::Test* suite(); +}; + + +#endif // ProcessesTestSuite_INCLUDED diff --git a/Foundation/testsuite/src/RWLockTest.cpp b/Foundation/testsuite/src/RWLockTest.cpp index 7238072e8..00bf17313 100644 --- a/Foundation/testsuite/src/RWLockTest.cpp +++ b/Foundation/testsuite/src/RWLockTest.cpp @@ -1,224 +1,224 @@ -// -// RWLockTest.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/RWLockTest.cpp#1 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "RWLockTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/RWLock.h" -#include "Poco/Thread.h" -#include "Poco/Runnable.h" - - -using Poco::RWLock; -using Poco::Thread; -using Poco::Runnable; - - -class RWLockRunnable: public Runnable -{ -public: - RWLockRunnable(RWLock& lock, volatile int& counter): _lock(lock), _counter(counter), _ok(true) - { - } - - void run() - { - int lastCount = 0; - for (int i = 0; i < 10000; ++i) - { - _lock.readLock(); - lastCount = _counter; - for (int k = 0; k < 100; ++k) - { - if (_counter != lastCount) _ok = false; - } - _lock.unlock(); - _lock.writeLock(); - for (int k = 0; k < 100; ++k) - --_counter; - for (int k = 0; k < 100; ++k) - ++_counter; - ++_counter; - if (_counter <= lastCount) _ok = false; - _lock.unlock(); - } - } - - bool ok() const - { - return _ok; - } - -private: - RWLock& _lock; - volatile int& _counter; - bool _ok; -}; - - -class RWTryLockRunnable: public Runnable -{ -public: - RWTryLockRunnable(RWLock& lock, volatile int& counter): _lock(lock), _counter(counter), _ok(true) - { - } - - void run() - { - int lastCount = 0; - for (int i = 0; i < 10000; ++i) - { - while (!_lock.tryReadLock()) Thread::yield(); - lastCount = _counter; - for (int k = 0; k < 100; ++k) - { - if (_counter != lastCount) _ok = false; - } - _lock.unlock(); - while (!_lock.tryWriteLock()) Thread::yield(); - for (int k = 0; k < 100; ++k) - --_counter; - for (int k = 0; k < 100; ++k) - ++_counter; - ++_counter; - if (_counter <= lastCount) _ok = false; - _lock.unlock(); - } - } - - bool ok() const - { - return _ok; - } - -private: - RWLock& _lock; - volatile int& _counter; - bool _ok; -}; - - -RWLockTest::RWLockTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -RWLockTest::~RWLockTest() -{ -} - - -void RWLockTest::testLock() -{ - RWLock lock; - int counter = 0; - RWLockRunnable r1(lock, counter); - RWLockRunnable r2(lock, counter); - RWLockRunnable r3(lock, counter); - RWLockRunnable r4(lock, counter); - RWLockRunnable r5(lock, counter); - Thread t1; - Thread t2; - Thread t3; - Thread t4; - Thread t5; - t1.start(r1); - t2.start(r2); - t3.start(r3); - t4.start(r4); - t5.start(r5); - t1.join(); - t2.join(); - t3.join(); - t4.join(); - t5.join(); - assert (counter == 50000); - assert (r1.ok()); - assert (r2.ok()); - assert (r3.ok()); - assert (r4.ok()); - assert (r5.ok()); -} - - -void RWLockTest::testTryLock() -{ - RWLock lock; - int counter = 0; - RWTryLockRunnable r1(lock, counter); - RWTryLockRunnable r2(lock, counter); - RWTryLockRunnable r3(lock, counter); - RWTryLockRunnable r4(lock, counter); - RWTryLockRunnable r5(lock, counter); - Thread t1; - Thread t2; - Thread t3; - Thread t4; - Thread t5; - t1.start(r1); - t2.start(r2); - t3.start(r3); - t4.start(r4); - t5.start(r5); - t1.join(); - t2.join(); - t3.join(); - t4.join(); - t5.join(); - assert (counter == 50000); - assert (r1.ok()); - assert (r2.ok()); - assert (r3.ok()); - assert (r4.ok()); - assert (r5.ok()); -} - - -void RWLockTest::setUp() -{ -} - - -void RWLockTest::tearDown() -{ -} - - -CppUnit::Test* RWLockTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("RWLockTest"); - - CppUnit_addTest(pSuite, RWLockTest, testLock); - CppUnit_addTest(pSuite, RWLockTest, testTryLock); - - return pSuite; -} +// +// RWLockTest.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/RWLockTest.cpp#1 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "RWLockTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/RWLock.h" +#include "Poco/Thread.h" +#include "Poco/Runnable.h" + + +using Poco::RWLock; +using Poco::Thread; +using Poco::Runnable; + + +class RWLockRunnable: public Runnable +{ +public: + RWLockRunnable(RWLock& lock, volatile int& counter): _lock(lock), _counter(counter), _ok(true) + { + } + + void run() + { + int lastCount = 0; + for (int i = 0; i < 10000; ++i) + { + _lock.readLock(); + lastCount = _counter; + for (int k = 0; k < 100; ++k) + { + if (_counter != lastCount) _ok = false; + } + _lock.unlock(); + _lock.writeLock(); + for (int k = 0; k < 100; ++k) + --_counter; + for (int k = 0; k < 100; ++k) + ++_counter; + ++_counter; + if (_counter <= lastCount) _ok = false; + _lock.unlock(); + } + } + + bool ok() const + { + return _ok; + } + +private: + RWLock& _lock; + volatile int& _counter; + bool _ok; +}; + + +class RWTryLockRunnable: public Runnable +{ +public: + RWTryLockRunnable(RWLock& lock, volatile int& counter): _lock(lock), _counter(counter), _ok(true) + { + } + + void run() + { + int lastCount = 0; + for (int i = 0; i < 10000; ++i) + { + while (!_lock.tryReadLock()) Thread::yield(); + lastCount = _counter; + for (int k = 0; k < 100; ++k) + { + if (_counter != lastCount) _ok = false; + } + _lock.unlock(); + while (!_lock.tryWriteLock()) Thread::yield(); + for (int k = 0; k < 100; ++k) + --_counter; + for (int k = 0; k < 100; ++k) + ++_counter; + ++_counter; + if (_counter <= lastCount) _ok = false; + _lock.unlock(); + } + } + + bool ok() const + { + return _ok; + } + +private: + RWLock& _lock; + volatile int& _counter; + bool _ok; +}; + + +RWLockTest::RWLockTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +RWLockTest::~RWLockTest() +{ +} + + +void RWLockTest::testLock() +{ + RWLock lock; + int counter = 0; + RWLockRunnable r1(lock, counter); + RWLockRunnable r2(lock, counter); + RWLockRunnable r3(lock, counter); + RWLockRunnable r4(lock, counter); + RWLockRunnable r5(lock, counter); + Thread t1; + Thread t2; + Thread t3; + Thread t4; + Thread t5; + t1.start(r1); + t2.start(r2); + t3.start(r3); + t4.start(r4); + t5.start(r5); + t1.join(); + t2.join(); + t3.join(); + t4.join(); + t5.join(); + assert (counter == 50000); + assert (r1.ok()); + assert (r2.ok()); + assert (r3.ok()); + assert (r4.ok()); + assert (r5.ok()); +} + + +void RWLockTest::testTryLock() +{ + RWLock lock; + int counter = 0; + RWTryLockRunnable r1(lock, counter); + RWTryLockRunnable r2(lock, counter); + RWTryLockRunnable r3(lock, counter); + RWTryLockRunnable r4(lock, counter); + RWTryLockRunnable r5(lock, counter); + Thread t1; + Thread t2; + Thread t3; + Thread t4; + Thread t5; + t1.start(r1); + t2.start(r2); + t3.start(r3); + t4.start(r4); + t5.start(r5); + t1.join(); + t2.join(); + t3.join(); + t4.join(); + t5.join(); + assert (counter == 50000); + assert (r1.ok()); + assert (r2.ok()); + assert (r3.ok()); + assert (r4.ok()); + assert (r5.ok()); +} + + +void RWLockTest::setUp() +{ +} + + +void RWLockTest::tearDown() +{ +} + + +CppUnit::Test* RWLockTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("RWLockTest"); + + CppUnit_addTest(pSuite, RWLockTest, testLock); + CppUnit_addTest(pSuite, RWLockTest, testTryLock); + + return pSuite; +} diff --git a/Foundation/testsuite/src/RWLockTest.h b/Foundation/testsuite/src/RWLockTest.h index 409351667..c6fb259f5 100644 --- a/Foundation/testsuite/src/RWLockTest.h +++ b/Foundation/testsuite/src/RWLockTest.h @@ -1,61 +1,61 @@ -// -// RWLockTest.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/RWLockTest.h#1 $ -// -// Definition of the RWLockTest class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 RWLockTest_INCLUDED -#define RWLockTest_INCLUDED - - -#include "Poco/Foundation.h" -#include "CppUnit/TestCase.h" - - -class RWLockTest: public CppUnit::TestCase -{ -public: - RWLockTest(const std::string& name); - ~RWLockTest(); - - void testLock(); - void testTryLock(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // RWLockTest_INCLUDED +// +// RWLockTest.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/RWLockTest.h#1 $ +// +// Definition of the RWLockTest class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 RWLockTest_INCLUDED +#define RWLockTest_INCLUDED + + +#include "Poco/Foundation.h" +#include "CppUnit/TestCase.h" + + +class RWLockTest: public CppUnit::TestCase +{ +public: + RWLockTest(const std::string& name); + ~RWLockTest(); + + void testLock(); + void testTryLock(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // RWLockTest_INCLUDED diff --git a/Foundation/testsuite/src/RandomStreamTest.cpp b/Foundation/testsuite/src/RandomStreamTest.cpp index 8fbc82539..cbf9141e8 100644 --- a/Foundation/testsuite/src/RandomStreamTest.cpp +++ b/Foundation/testsuite/src/RandomStreamTest.cpp @@ -1,97 +1,97 @@ -// -// RandomStreamTest.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/RandomStreamTest.cpp#1 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "RandomStreamTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/RandomStream.h" -#include -#include - - -using Poco::RandomInputStream; - - -RandomStreamTest::RandomStreamTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -RandomStreamTest::~RandomStreamTest() -{ -} - - -void RandomStreamTest::testStream() -{ - RandomInputStream rnd; - - const int n = 16; - std::vector d(n, 0); - for (int i = 0; i < 1000; ++i) - { - unsigned char c; - rnd >> c; - d[c & 0x0F]++; - d[(c >> 4) & 0x0F]++; - } - int sum = 0; - for (int k = 0; k < n; ++k) sum += d[k]; - int avg = sum/n; - int var = 0; - for (int k = 0; k < n; ++k) var += (d[k] - avg)*(d[k] - avg); - var /= n; - int sd = int(sqrt((double) var)); - - assert (110 < avg && avg < 140); - assert (sd < 20); -} - - -void RandomStreamTest::setUp() -{ -} - - -void RandomStreamTest::tearDown() -{ -} - - -CppUnit::Test* RandomStreamTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("RandomStreamTest"); - - CppUnit_addTest(pSuite, RandomStreamTest, testStream); - - return pSuite; -} +// +// RandomStreamTest.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/RandomStreamTest.cpp#1 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "RandomStreamTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/RandomStream.h" +#include +#include + + +using Poco::RandomInputStream; + + +RandomStreamTest::RandomStreamTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +RandomStreamTest::~RandomStreamTest() +{ +} + + +void RandomStreamTest::testStream() +{ + RandomInputStream rnd; + + const int n = 16; + std::vector d(n, 0); + for (int i = 0; i < 1000; ++i) + { + unsigned char c; + rnd >> c; + d[c & 0x0F]++; + d[(c >> 4) & 0x0F]++; + } + int sum = 0; + for (int k = 0; k < n; ++k) sum += d[k]; + int avg = sum/n; + int var = 0; + for (int k = 0; k < n; ++k) var += (d[k] - avg)*(d[k] - avg); + var /= n; + int sd = int(sqrt((double) var)); + + assert (110 < avg && avg < 140); + assert (sd < 20); +} + + +void RandomStreamTest::setUp() +{ +} + + +void RandomStreamTest::tearDown() +{ +} + + +CppUnit::Test* RandomStreamTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("RandomStreamTest"); + + CppUnit_addTest(pSuite, RandomStreamTest, testStream); + + return pSuite; +} diff --git a/Foundation/testsuite/src/RandomStreamTest.h b/Foundation/testsuite/src/RandomStreamTest.h index 9650382db..994b55669 100644 --- a/Foundation/testsuite/src/RandomStreamTest.h +++ b/Foundation/testsuite/src/RandomStreamTest.h @@ -1,60 +1,60 @@ -// -// RandomStreamTest.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/RandomStreamTest.h#1 $ -// -// Definition of the RandomStreamTest class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 RandomStreamTest_INCLUDED -#define RandomStreamTest_INCLUDED - - -#include "Poco/Foundation.h" -#include "CppUnit/TestCase.h" - - -class RandomStreamTest: public CppUnit::TestCase -{ -public: - RandomStreamTest(const std::string& name); - ~RandomStreamTest(); - - void testStream(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // RandomStreamTest_INCLUDED +// +// RandomStreamTest.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/RandomStreamTest.h#1 $ +// +// Definition of the RandomStreamTest class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 RandomStreamTest_INCLUDED +#define RandomStreamTest_INCLUDED + + +#include "Poco/Foundation.h" +#include "CppUnit/TestCase.h" + + +class RandomStreamTest: public CppUnit::TestCase +{ +public: + RandomStreamTest(const std::string& name); + ~RandomStreamTest(); + + void testStream(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // RandomStreamTest_INCLUDED diff --git a/Foundation/testsuite/src/RandomTest.cpp b/Foundation/testsuite/src/RandomTest.cpp index dd7b2f2d3..3f54b5a2a 100644 --- a/Foundation/testsuite/src/RandomTest.cpp +++ b/Foundation/testsuite/src/RandomTest.cpp @@ -1,172 +1,172 @@ -// -// RandomTest.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/RandomTest.cpp#1 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "RandomTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/Random.h" -#include -#include - - -using Poco::Random; -using Poco::UInt32; - - -RandomTest::RandomTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -RandomTest::~RandomTest() -{ -} - - -void RandomTest::testSequence1() -{ - Random rnd1; - Random rnd2; - rnd1.seed(12345); - rnd2.seed(12345); - for (int i = 0; i < 100; ++i) - { - assert (rnd1.next() == rnd2.next()); - } -} - - -void RandomTest::testSequence2() -{ - Random rnd1; - Random rnd2; - rnd1.seed(12345); - rnd2.seed(54321); - - bool equals = true; - for (int i = 0; i < 20; ++i) - { - if (rnd1.next() != rnd2.next()) - { - equals = false; - break; - } - } - assert (!equals); -} - - -void RandomTest::testDistribution1() -{ - Random rnd; - rnd.seed(123456); - const int n = 11; - int d[n] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; - for (int i = 0; i < 100; ++i) - { - d[rnd.next() % n] = 1; - } - int sum = 0; - for (int k = 0; k < n; ++k) sum += d[k]; - - assert (sum == n); -} - - -void RandomTest::testDistribution2() -{ - Random rnd; - rnd.seed(); - const int n = 101; - std::vector d(n, 0); - for (int i = 0; i < 10000; ++i) - { - d[rnd.next(n)]++; - } - int sum = 0; - for (int k = 0; k < n; ++k) sum += d[k]; - int avg = sum/n; - int var = 0; - for (int k = 0; k < n; ++k) var += (d[k] - avg)*(d[k] - avg); - var /= n; - int sd = int(sqrt((double) var)); - - assert (95 < avg && avg < 105); - assert (sd < 15); -} - - -void RandomTest::testDistribution3() -{ - Random rnd; - rnd.seed(); - const int n = 101; - std::vector d(n, 0); - for (int i = 0; i < 10000; ++i) - { - d[int(rnd.nextFloat()*n)]++; - } - int sum = 0; - for (int k = 0; k < n; ++k) sum += d[k]; - int avg = sum/n; - int var = 0; - for (int k = 0; k < n; ++k) var += (d[k] - avg)*(d[k] - avg); - var /= n; - int sd = int(sqrt((double) var)); - - assert (95 < avg && avg < 105); - assert (sd < 15); -} - - -void RandomTest::setUp() -{ -} - - -void RandomTest::tearDown() -{ -} - - -CppUnit::Test* RandomTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("RandomTest"); - - CppUnit_addTest(pSuite, RandomTest, testSequence1); - CppUnit_addTest(pSuite, RandomTest, testSequence2); - CppUnit_addTest(pSuite, RandomTest, testDistribution1); - CppUnit_addTest(pSuite, RandomTest, testDistribution2); - CppUnit_addTest(pSuite, RandomTest, testDistribution3); - - return pSuite; -} +// +// RandomTest.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/RandomTest.cpp#1 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "RandomTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/Random.h" +#include +#include + + +using Poco::Random; +using Poco::UInt32; + + +RandomTest::RandomTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +RandomTest::~RandomTest() +{ +} + + +void RandomTest::testSequence1() +{ + Random rnd1; + Random rnd2; + rnd1.seed(12345); + rnd2.seed(12345); + for (int i = 0; i < 100; ++i) + { + assert (rnd1.next() == rnd2.next()); + } +} + + +void RandomTest::testSequence2() +{ + Random rnd1; + Random rnd2; + rnd1.seed(12345); + rnd2.seed(54321); + + bool equals = true; + for (int i = 0; i < 20; ++i) + { + if (rnd1.next() != rnd2.next()) + { + equals = false; + break; + } + } + assert (!equals); +} + + +void RandomTest::testDistribution1() +{ + Random rnd; + rnd.seed(123456); + const int n = 11; + int d[n] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; + for (int i = 0; i < 100; ++i) + { + d[rnd.next() % n] = 1; + } + int sum = 0; + for (int k = 0; k < n; ++k) sum += d[k]; + + assert (sum == n); +} + + +void RandomTest::testDistribution2() +{ + Random rnd; + rnd.seed(); + const int n = 101; + std::vector d(n, 0); + for (int i = 0; i < 10000; ++i) + { + d[rnd.next(n)]++; + } + int sum = 0; + for (int k = 0; k < n; ++k) sum += d[k]; + int avg = sum/n; + int var = 0; + for (int k = 0; k < n; ++k) var += (d[k] - avg)*(d[k] - avg); + var /= n; + int sd = int(sqrt((double) var)); + + assert (95 < avg && avg < 105); + assert (sd < 15); +} + + +void RandomTest::testDistribution3() +{ + Random rnd; + rnd.seed(); + const int n = 101; + std::vector d(n, 0); + for (int i = 0; i < 10000; ++i) + { + d[int(rnd.nextFloat()*n)]++; + } + int sum = 0; + for (int k = 0; k < n; ++k) sum += d[k]; + int avg = sum/n; + int var = 0; + for (int k = 0; k < n; ++k) var += (d[k] - avg)*(d[k] - avg); + var /= n; + int sd = int(sqrt((double) var)); + + assert (95 < avg && avg < 105); + assert (sd < 15); +} + + +void RandomTest::setUp() +{ +} + + +void RandomTest::tearDown() +{ +} + + +CppUnit::Test* RandomTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("RandomTest"); + + CppUnit_addTest(pSuite, RandomTest, testSequence1); + CppUnit_addTest(pSuite, RandomTest, testSequence2); + CppUnit_addTest(pSuite, RandomTest, testDistribution1); + CppUnit_addTest(pSuite, RandomTest, testDistribution2); + CppUnit_addTest(pSuite, RandomTest, testDistribution3); + + return pSuite; +} diff --git a/Foundation/testsuite/src/RandomTest.h b/Foundation/testsuite/src/RandomTest.h index cdad10e6d..caccf59da 100644 --- a/Foundation/testsuite/src/RandomTest.h +++ b/Foundation/testsuite/src/RandomTest.h @@ -1,64 +1,64 @@ -// -// RandomTest.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/RandomTest.h#1 $ -// -// Definition of the RandomTest class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 RandomTest_INCLUDED -#define RandomTest_INCLUDED - - -#include "Poco/Foundation.h" -#include "CppUnit/TestCase.h" - - -class RandomTest: public CppUnit::TestCase -{ -public: - RandomTest(const std::string& name); - ~RandomTest(); - - void testSequence1(); - void testSequence2(); - void testDistribution1(); - void testDistribution2(); - void testDistribution3(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // RandomTest_INCLUDED +// +// RandomTest.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/RandomTest.h#1 $ +// +// Definition of the RandomTest class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 RandomTest_INCLUDED +#define RandomTest_INCLUDED + + +#include "Poco/Foundation.h" +#include "CppUnit/TestCase.h" + + +class RandomTest: public CppUnit::TestCase +{ +public: + RandomTest(const std::string& name); + ~RandomTest(); + + void testSequence1(); + void testSequence2(); + void testDistribution1(); + void testDistribution2(); + void testDistribution3(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // RandomTest_INCLUDED diff --git a/Foundation/testsuite/src/RegularExpressionTest.cpp b/Foundation/testsuite/src/RegularExpressionTest.cpp index 0b262477c..6008a085e 100644 --- a/Foundation/testsuite/src/RegularExpressionTest.cpp +++ b/Foundation/testsuite/src/RegularExpressionTest.cpp @@ -1,309 +1,309 @@ -// -// RegularExpressionTest.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/RegularExpressionTest.cpp#1 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "RegularExpressionTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/RegularExpression.h" -#include "Poco/Exception.h" - - -using Poco::RegularExpression; -using Poco::RegularExpressionException; - - -RegularExpressionTest::RegularExpressionTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -RegularExpressionTest::~RegularExpressionTest() -{ -} - - -void RegularExpressionTest::testIndex() -{ - RegularExpression re("[0-9]+"); - RegularExpression::Match match; - assert (re.match("", 0, match) == 0); - assert (re.match("123", 3, match) == 0); -} - - -void RegularExpressionTest::testMatch1() -{ - RegularExpression re("[0-9]+"); - assert (re.match("123")); - assert (!re.match("123cd")); - assert (!re.match("abcde")); - assert (re.match("ab123", 2)); -} - - -void RegularExpressionTest::testMatch2() -{ - RegularExpression re("[0-9]+"); - RegularExpression::Match match; - assert (re.match("123", 0, match) == 1); - assert (match.offset == 0); - assert (match.length == 3); - - assert (re.match("abc123def", 0, match) == 1); - assert (match.offset == 3); - assert (match.length == 3); - - assert (re.match("abcdef", 0, match) == 0); - assert (match.offset == std::string::npos); - assert (match.length == 0); - - assert (re.match("abc123def", 3, match) == 1); - assert (match.offset == 3); - assert (match.length == 3); -} - - -void RegularExpressionTest::testMatch3() -{ - RegularExpression re("[0-9]+"); - RegularExpression::MatchVec match; - assert (re.match("123", 0, match) == 1); - assert (match.size() == 1); - assert (match[0].offset == 0); - assert (match[0].length == 3); - - assert (re.match("abc123def", 0, match) == 1); - assert (match.size() == 1); - assert (match[0].offset == 3); - assert (match[0].length == 3); - - assert (re.match("abcdef", 0, match) == 0); - assert (match.size() == 0); - - assert (re.match("abc123def", 3, match) == 1); - assert (match.size() == 1); - assert (match[0].offset == 3); - assert (match[0].length == 3); -} - - -void RegularExpressionTest::testMatch4() -{ - RegularExpression re("([0-9]+) ([0-9]+)"); - RegularExpression::MatchVec matches; - assert (re.match("123 456", 0, matches) == 3); - assert (matches.size() == 3); - assert (matches[0].offset == 0); - assert (matches[0].length == 7); - assert (matches[1].offset == 0); - assert (matches[1].length == 3); - assert (matches[2].offset == 4); - assert (matches[2].length == 3); - - assert (re.match("abc123 456def", 0, matches) == 3); - assert (matches.size() == 3); - assert (matches[0].offset == 3); - assert (matches[0].length == 7); - assert (matches[1].offset == 3); - assert (matches[1].length == 3); - assert (matches[2].offset == 7); - assert (matches[2].length == 3); -} - - -void RegularExpressionTest::testMatch5() -{ - std::string digits = "0123"; - assert (RegularExpression::match(digits, "[0-9]+")); - std::string alphas = "abcd"; - assert (!RegularExpression::match(alphas, "[0-9]+")); -} - - -void RegularExpressionTest::testExtract() -{ - RegularExpression re("[0-9]+"); - std::string str; - assert (re.extract("123", str) == 1); - assert (str == "123"); - - assert (re.extract("abc123def", 0, str) == 1); - assert (str == "123"); - - assert (re.extract("abcdef", 0, str) == 0); - assert (str == ""); - - assert (re.extract("abc123def", 3, str) == 1); - assert (str == "123"); -} - - -void RegularExpressionTest::testSplit1() -{ - RegularExpression re("[0-9]+"); - std::vector strings; - assert (re.split("123", 0, strings) == 1); - assert (strings.size() == 1); - assert (strings[0] == "123"); - - assert (re.split("abc123def", 0, strings) == 1); - assert (strings.size() == 1); - assert (strings[0] == "123"); - - assert (re.split("abcdef", 0, strings) == 0); - assert (strings.empty()); - - assert (re.split("abc123def", 3, strings) == 1); - assert (strings.size() == 1); - assert (strings[0] == "123"); -} - - -void RegularExpressionTest::testSplit2() -{ - RegularExpression re("([0-9]+) ([0-9]+)"); - std::vector strings; - assert (re.split("123 456", 0, strings) == 3); - assert (strings.size() == 3); - assert (strings[0] == "123 456"); - assert (strings[1] == "123"); - assert (strings[2] == "456"); - - assert (re.split("abc123 456def", 0, strings) == 3); - assert (strings.size() == 3); - assert (strings[0] == "123 456"); - assert (strings[1] == "123"); - assert (strings[2] == "456"); -} - - -void RegularExpressionTest::testSubst1() -{ - RegularExpression re("[0-9]+"); - std::string s = "123"; - assert (re.subst(s, "ABC") == 1); - assert (s == "ABC"); - assert (re.subst(s, "123") == 0); - - s = "123"; - assert (re.subst(s, "AB$0CD") == 1); - assert (s == "AB123CD"); - - s = "123"; - assert (re.subst(s, "AB$1CD") == 1); - assert (s == "ABCD"); - - s = "123"; - assert (re.subst(s, "AB$2CD") == 1); - assert (s == "ABCD"); - - s = "123"; - assert (re.subst(s, "AB$$CD") == 1); - assert (s == "AB$$CD"); - - s = "123"; - assert (re.subst(s, "AB$0CD", RegularExpression::RE_NO_VARS) == 1); - assert (s == "AB$0CD"); -} - - -void RegularExpressionTest::testSubst2() -{ - RegularExpression re("([0-9]+) ([0-9]+)"); - std::string s = "123 456"; - assert (re.subst(s, "$2-$1") == 1); - assert (s == "456-123"); -} - - -void RegularExpressionTest::testSubst3() -{ - RegularExpression re("[0-9]+"); - std::string s = "123 456 789"; - assert (re.subst(s, "n", RegularExpression::RE_GLOBAL) == 3); - assert (s == "n n n"); -} - - -void RegularExpressionTest::testSubst4() -{ - RegularExpression re("[0-9]+"); - std::string s = "ABC 123 456 789 DEF"; - assert (re.subst(s, "n", RegularExpression::RE_GLOBAL) == 3); - assert (s == "ABC n n n DEF"); -} - - -void RegularExpressionTest::testError() -{ - try - { - RegularExpression re("(0-9]"); - failmsg("bad regexp - must throw exception"); - } - catch (RegularExpressionException&) - { - } -} - - -void RegularExpressionTest::setUp() -{ -} - - -void RegularExpressionTest::tearDown() -{ -} - - -CppUnit::Test* RegularExpressionTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("RegularExpressionTest"); - - CppUnit_addTest(pSuite, RegularExpressionTest, testIndex); - CppUnit_addTest(pSuite, RegularExpressionTest, testMatch1); - CppUnit_addTest(pSuite, RegularExpressionTest, testMatch2); - CppUnit_addTest(pSuite, RegularExpressionTest, testMatch3); - CppUnit_addTest(pSuite, RegularExpressionTest, testMatch4); - CppUnit_addTest(pSuite, RegularExpressionTest, testMatch5); - CppUnit_addTest(pSuite, RegularExpressionTest, testExtract); - CppUnit_addTest(pSuite, RegularExpressionTest, testSplit1); - CppUnit_addTest(pSuite, RegularExpressionTest, testSplit2); - CppUnit_addTest(pSuite, RegularExpressionTest, testSubst1); - CppUnit_addTest(pSuite, RegularExpressionTest, testSubst2); - CppUnit_addTest(pSuite, RegularExpressionTest, testSubst3); - CppUnit_addTest(pSuite, RegularExpressionTest, testSubst4); - CppUnit_addTest(pSuite, RegularExpressionTest, testError); - - return pSuite; -} +// +// RegularExpressionTest.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/RegularExpressionTest.cpp#1 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "RegularExpressionTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/RegularExpression.h" +#include "Poco/Exception.h" + + +using Poco::RegularExpression; +using Poco::RegularExpressionException; + + +RegularExpressionTest::RegularExpressionTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +RegularExpressionTest::~RegularExpressionTest() +{ +} + + +void RegularExpressionTest::testIndex() +{ + RegularExpression re("[0-9]+"); + RegularExpression::Match match; + assert (re.match("", 0, match) == 0); + assert (re.match("123", 3, match) == 0); +} + + +void RegularExpressionTest::testMatch1() +{ + RegularExpression re("[0-9]+"); + assert (re.match("123")); + assert (!re.match("123cd")); + assert (!re.match("abcde")); + assert (re.match("ab123", 2)); +} + + +void RegularExpressionTest::testMatch2() +{ + RegularExpression re("[0-9]+"); + RegularExpression::Match match; + assert (re.match("123", 0, match) == 1); + assert (match.offset == 0); + assert (match.length == 3); + + assert (re.match("abc123def", 0, match) == 1); + assert (match.offset == 3); + assert (match.length == 3); + + assert (re.match("abcdef", 0, match) == 0); + assert (match.offset == std::string::npos); + assert (match.length == 0); + + assert (re.match("abc123def", 3, match) == 1); + assert (match.offset == 3); + assert (match.length == 3); +} + + +void RegularExpressionTest::testMatch3() +{ + RegularExpression re("[0-9]+"); + RegularExpression::MatchVec match; + assert (re.match("123", 0, match) == 1); + assert (match.size() == 1); + assert (match[0].offset == 0); + assert (match[0].length == 3); + + assert (re.match("abc123def", 0, match) == 1); + assert (match.size() == 1); + assert (match[0].offset == 3); + assert (match[0].length == 3); + + assert (re.match("abcdef", 0, match) == 0); + assert (match.size() == 0); + + assert (re.match("abc123def", 3, match) == 1); + assert (match.size() == 1); + assert (match[0].offset == 3); + assert (match[0].length == 3); +} + + +void RegularExpressionTest::testMatch4() +{ + RegularExpression re("([0-9]+) ([0-9]+)"); + RegularExpression::MatchVec matches; + assert (re.match("123 456", 0, matches) == 3); + assert (matches.size() == 3); + assert (matches[0].offset == 0); + assert (matches[0].length == 7); + assert (matches[1].offset == 0); + assert (matches[1].length == 3); + assert (matches[2].offset == 4); + assert (matches[2].length == 3); + + assert (re.match("abc123 456def", 0, matches) == 3); + assert (matches.size() == 3); + assert (matches[0].offset == 3); + assert (matches[0].length == 7); + assert (matches[1].offset == 3); + assert (matches[1].length == 3); + assert (matches[2].offset == 7); + assert (matches[2].length == 3); +} + + +void RegularExpressionTest::testMatch5() +{ + std::string digits = "0123"; + assert (RegularExpression::match(digits, "[0-9]+")); + std::string alphas = "abcd"; + assert (!RegularExpression::match(alphas, "[0-9]+")); +} + + +void RegularExpressionTest::testExtract() +{ + RegularExpression re("[0-9]+"); + std::string str; + assert (re.extract("123", str) == 1); + assert (str == "123"); + + assert (re.extract("abc123def", 0, str) == 1); + assert (str == "123"); + + assert (re.extract("abcdef", 0, str) == 0); + assert (str == ""); + + assert (re.extract("abc123def", 3, str) == 1); + assert (str == "123"); +} + + +void RegularExpressionTest::testSplit1() +{ + RegularExpression re("[0-9]+"); + std::vector strings; + assert (re.split("123", 0, strings) == 1); + assert (strings.size() == 1); + assert (strings[0] == "123"); + + assert (re.split("abc123def", 0, strings) == 1); + assert (strings.size() == 1); + assert (strings[0] == "123"); + + assert (re.split("abcdef", 0, strings) == 0); + assert (strings.empty()); + + assert (re.split("abc123def", 3, strings) == 1); + assert (strings.size() == 1); + assert (strings[0] == "123"); +} + + +void RegularExpressionTest::testSplit2() +{ + RegularExpression re("([0-9]+) ([0-9]+)"); + std::vector strings; + assert (re.split("123 456", 0, strings) == 3); + assert (strings.size() == 3); + assert (strings[0] == "123 456"); + assert (strings[1] == "123"); + assert (strings[2] == "456"); + + assert (re.split("abc123 456def", 0, strings) == 3); + assert (strings.size() == 3); + assert (strings[0] == "123 456"); + assert (strings[1] == "123"); + assert (strings[2] == "456"); +} + + +void RegularExpressionTest::testSubst1() +{ + RegularExpression re("[0-9]+"); + std::string s = "123"; + assert (re.subst(s, "ABC") == 1); + assert (s == "ABC"); + assert (re.subst(s, "123") == 0); + + s = "123"; + assert (re.subst(s, "AB$0CD") == 1); + assert (s == "AB123CD"); + + s = "123"; + assert (re.subst(s, "AB$1CD") == 1); + assert (s == "ABCD"); + + s = "123"; + assert (re.subst(s, "AB$2CD") == 1); + assert (s == "ABCD"); + + s = "123"; + assert (re.subst(s, "AB$$CD") == 1); + assert (s == "AB$$CD"); + + s = "123"; + assert (re.subst(s, "AB$0CD", RegularExpression::RE_NO_VARS) == 1); + assert (s == "AB$0CD"); +} + + +void RegularExpressionTest::testSubst2() +{ + RegularExpression re("([0-9]+) ([0-9]+)"); + std::string s = "123 456"; + assert (re.subst(s, "$2-$1") == 1); + assert (s == "456-123"); +} + + +void RegularExpressionTest::testSubst3() +{ + RegularExpression re("[0-9]+"); + std::string s = "123 456 789"; + assert (re.subst(s, "n", RegularExpression::RE_GLOBAL) == 3); + assert (s == "n n n"); +} + + +void RegularExpressionTest::testSubst4() +{ + RegularExpression re("[0-9]+"); + std::string s = "ABC 123 456 789 DEF"; + assert (re.subst(s, "n", RegularExpression::RE_GLOBAL) == 3); + assert (s == "ABC n n n DEF"); +} + + +void RegularExpressionTest::testError() +{ + try + { + RegularExpression re("(0-9]"); + failmsg("bad regexp - must throw exception"); + } + catch (RegularExpressionException&) + { + } +} + + +void RegularExpressionTest::setUp() +{ +} + + +void RegularExpressionTest::tearDown() +{ +} + + +CppUnit::Test* RegularExpressionTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("RegularExpressionTest"); + + CppUnit_addTest(pSuite, RegularExpressionTest, testIndex); + CppUnit_addTest(pSuite, RegularExpressionTest, testMatch1); + CppUnit_addTest(pSuite, RegularExpressionTest, testMatch2); + CppUnit_addTest(pSuite, RegularExpressionTest, testMatch3); + CppUnit_addTest(pSuite, RegularExpressionTest, testMatch4); + CppUnit_addTest(pSuite, RegularExpressionTest, testMatch5); + CppUnit_addTest(pSuite, RegularExpressionTest, testExtract); + CppUnit_addTest(pSuite, RegularExpressionTest, testSplit1); + CppUnit_addTest(pSuite, RegularExpressionTest, testSplit2); + CppUnit_addTest(pSuite, RegularExpressionTest, testSubst1); + CppUnit_addTest(pSuite, RegularExpressionTest, testSubst2); + CppUnit_addTest(pSuite, RegularExpressionTest, testSubst3); + CppUnit_addTest(pSuite, RegularExpressionTest, testSubst4); + CppUnit_addTest(pSuite, RegularExpressionTest, testError); + + return pSuite; +} diff --git a/Foundation/testsuite/src/RegularExpressionTest.h b/Foundation/testsuite/src/RegularExpressionTest.h index dd9a5c902..76f9b1ad0 100644 --- a/Foundation/testsuite/src/RegularExpressionTest.h +++ b/Foundation/testsuite/src/RegularExpressionTest.h @@ -1,73 +1,73 @@ -// -// RegularExpressionTest.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/RegularExpressionTest.h#1 $ -// -// Definition of the RegularExpressionTest class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 RegularExpressionTest_INCLUDED -#define RegularExpressionTest_INCLUDED - - -#include "Poco/Foundation.h" -#include "CppUnit/TestCase.h" - - -class RegularExpressionTest: public CppUnit::TestCase -{ -public: - RegularExpressionTest(const std::string& name); - ~RegularExpressionTest(); - - void testIndex(); - void testMatch1(); - void testMatch2(); - void testMatch3(); - void testMatch4(); - void testMatch5(); - void testExtract(); - void testSplit1(); - void testSplit2(); - void testSubst1(); - void testSubst2(); - void testSubst3(); - void testSubst4(); - void testError(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // RegularExpressionTest_INCLUDED +// +// RegularExpressionTest.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/RegularExpressionTest.h#1 $ +// +// Definition of the RegularExpressionTest class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 RegularExpressionTest_INCLUDED +#define RegularExpressionTest_INCLUDED + + +#include "Poco/Foundation.h" +#include "CppUnit/TestCase.h" + + +class RegularExpressionTest: public CppUnit::TestCase +{ +public: + RegularExpressionTest(const std::string& name); + ~RegularExpressionTest(); + + void testIndex(); + void testMatch1(); + void testMatch2(); + void testMatch3(); + void testMatch4(); + void testMatch5(); + void testExtract(); + void testSplit1(); + void testSplit2(); + void testSubst1(); + void testSubst2(); + void testSubst3(); + void testSubst4(); + void testError(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // RegularExpressionTest_INCLUDED diff --git a/Foundation/testsuite/src/SHA1EngineTest.cpp b/Foundation/testsuite/src/SHA1EngineTest.cpp index aaeea311c..3bda0beb1 100644 --- a/Foundation/testsuite/src/SHA1EngineTest.cpp +++ b/Foundation/testsuite/src/SHA1EngineTest.cpp @@ -1,88 +1,88 @@ -// -// SHA1EngineTest.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/SHA1EngineTest.cpp#1 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "SHA1EngineTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/SHA1Engine.h" - - -using Poco::SHA1Engine; -using Poco::DigestEngine; - - -SHA1EngineTest::SHA1EngineTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -SHA1EngineTest::~SHA1EngineTest() -{ -} - - -void SHA1EngineTest::testSHA1() -{ - SHA1Engine engine; - - // test vectors from FIPS 180-1 - - engine.update("abc"); - assert (DigestEngine::digestToHex(engine.digest()) == "a9993e364706816aba3e25717850c26c9cd0d89d"); - - engine.update("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"); - assert (DigestEngine::digestToHex(engine.digest()) == "84983e441c3bd26ebaae4aa1f95129e5e54670f1"); - - for (int i = 0; i < 1000000; ++i) - engine.update('a'); - assert (DigestEngine::digestToHex(engine.digest()) == "34aa973cd4c4daa4f61eeb2bdbad27316534016f"); -} - - -void SHA1EngineTest::setUp() -{ -} - - -void SHA1EngineTest::tearDown() -{ -} - - -CppUnit::Test* SHA1EngineTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("SHA1EngineTest"); - - CppUnit_addTest(pSuite, SHA1EngineTest, testSHA1); - - return pSuite; -} +// +// SHA1EngineTest.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/SHA1EngineTest.cpp#1 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "SHA1EngineTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/SHA1Engine.h" + + +using Poco::SHA1Engine; +using Poco::DigestEngine; + + +SHA1EngineTest::SHA1EngineTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +SHA1EngineTest::~SHA1EngineTest() +{ +} + + +void SHA1EngineTest::testSHA1() +{ + SHA1Engine engine; + + // test vectors from FIPS 180-1 + + engine.update("abc"); + assert (DigestEngine::digestToHex(engine.digest()) == "a9993e364706816aba3e25717850c26c9cd0d89d"); + + engine.update("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"); + assert (DigestEngine::digestToHex(engine.digest()) == "84983e441c3bd26ebaae4aa1f95129e5e54670f1"); + + for (int i = 0; i < 1000000; ++i) + engine.update('a'); + assert (DigestEngine::digestToHex(engine.digest()) == "34aa973cd4c4daa4f61eeb2bdbad27316534016f"); +} + + +void SHA1EngineTest::setUp() +{ +} + + +void SHA1EngineTest::tearDown() +{ +} + + +CppUnit::Test* SHA1EngineTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("SHA1EngineTest"); + + CppUnit_addTest(pSuite, SHA1EngineTest, testSHA1); + + return pSuite; +} diff --git a/Foundation/testsuite/src/SHA1EngineTest.h b/Foundation/testsuite/src/SHA1EngineTest.h index e74219a39..a34cde544 100644 --- a/Foundation/testsuite/src/SHA1EngineTest.h +++ b/Foundation/testsuite/src/SHA1EngineTest.h @@ -1,60 +1,60 @@ -// -// SHA1EngineTest.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/SHA1EngineTest.h#1 $ -// -// Definition of the SHA1EngineTest class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 SHA1EngineTest_INCLUDED -#define SHA1EngineTest_INCLUDED - - -#include "Poco/Foundation.h" -#include "CppUnit/TestCase.h" - - -class SHA1EngineTest: public CppUnit::TestCase -{ -public: - SHA1EngineTest(const std::string& name); - ~SHA1EngineTest(); - - void testSHA1(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // SHA1EngineTest_INCLUDED +// +// SHA1EngineTest.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/SHA1EngineTest.h#1 $ +// +// Definition of the SHA1EngineTest class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 SHA1EngineTest_INCLUDED +#define SHA1EngineTest_INCLUDED + + +#include "Poco/Foundation.h" +#include "CppUnit/TestCase.h" + + +class SHA1EngineTest: public CppUnit::TestCase +{ +public: + SHA1EngineTest(const std::string& name); + ~SHA1EngineTest(); + + void testSHA1(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // SHA1EngineTest_INCLUDED diff --git a/Foundation/testsuite/src/SemaphoreTest.cpp b/Foundation/testsuite/src/SemaphoreTest.cpp index da7472faf..5d5dbd3ba 100644 --- a/Foundation/testsuite/src/SemaphoreTest.cpp +++ b/Foundation/testsuite/src/SemaphoreTest.cpp @@ -1,167 +1,167 @@ -// -// SemaphoreTest.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/SemaphoreTest.cpp#1 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "SemaphoreTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/Thread.h" -#include "Poco/Runnable.h" -#include "Poco/Semaphore.h" -#include "Poco/Exception.h" - - -using Poco::Thread; -using Poco::Runnable; -using Poco::Semaphore; -using Poco::TimeoutException; - - -class SemaRunnable: public Runnable -{ -public: - SemaRunnable(int n, int max): _ran(false), _sema(n, max) - { - } - - void run() - { - _sema.wait(); - _ran = true; - } - - bool ran() const - { - return _ran; - } - - void set() - { - _sema.set(); - } - - void wait() - { - _sema.wait(); - } - - void wait(long milliseconds) - { - _sema.wait(milliseconds); - } - - bool tryWait(long milliseconds) - { - return _sema.tryWait(milliseconds); - } - -private: - bool _ran; - Semaphore _sema; -}; - - -SemaphoreTest::SemaphoreTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -SemaphoreTest::~SemaphoreTest() -{ -} - - -void SemaphoreTest::testInitZero() -{ - SemaRunnable r(0, 3); - assert (!r.tryWait(10)); - r.set(); - r.wait(); - try - { - r.wait(100); - failmsg("must timeout"); - } - catch (TimeoutException&) - { - } - catch (...) - { - failmsg("wrong exception"); - } - r.set(); - r.set(); - assert (r.tryWait(0)); - r.wait(); - assert (!r.tryWait(10)); - - Thread t; - t.start(r); - Thread::sleep(100); - assert (!r.ran()); - r.set(); - t.join(); - assert (r.ran()); - assert (!r.tryWait(10)); -} - - -void SemaphoreTest::testInitNonZero() -{ - SemaRunnable r(2, 2); - r.wait(); - assert (r.tryWait(10)); - assert (!r.tryWait(10)); - r.set(); - assert (r.tryWait(10)); - assert (!r.tryWait(10)); -} - - -void SemaphoreTest::setUp() -{ -} - - -void SemaphoreTest::tearDown() -{ -} - - -CppUnit::Test* SemaphoreTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("SemaphoreTest"); - - CppUnit_addTest(pSuite, SemaphoreTest, testInitZero); - CppUnit_addTest(pSuite, SemaphoreTest, testInitNonZero); - - return pSuite; -} +// +// SemaphoreTest.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/SemaphoreTest.cpp#1 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "SemaphoreTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/Thread.h" +#include "Poco/Runnable.h" +#include "Poco/Semaphore.h" +#include "Poco/Exception.h" + + +using Poco::Thread; +using Poco::Runnable; +using Poco::Semaphore; +using Poco::TimeoutException; + + +class SemaRunnable: public Runnable +{ +public: + SemaRunnable(int n, int max): _ran(false), _sema(n, max) + { + } + + void run() + { + _sema.wait(); + _ran = true; + } + + bool ran() const + { + return _ran; + } + + void set() + { + _sema.set(); + } + + void wait() + { + _sema.wait(); + } + + void wait(long milliseconds) + { + _sema.wait(milliseconds); + } + + bool tryWait(long milliseconds) + { + return _sema.tryWait(milliseconds); + } + +private: + bool _ran; + Semaphore _sema; +}; + + +SemaphoreTest::SemaphoreTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +SemaphoreTest::~SemaphoreTest() +{ +} + + +void SemaphoreTest::testInitZero() +{ + SemaRunnable r(0, 3); + assert (!r.tryWait(10)); + r.set(); + r.wait(); + try + { + r.wait(100); + failmsg("must timeout"); + } + catch (TimeoutException&) + { + } + catch (...) + { + failmsg("wrong exception"); + } + r.set(); + r.set(); + assert (r.tryWait(0)); + r.wait(); + assert (!r.tryWait(10)); + + Thread t; + t.start(r); + Thread::sleep(100); + assert (!r.ran()); + r.set(); + t.join(); + assert (r.ran()); + assert (!r.tryWait(10)); +} + + +void SemaphoreTest::testInitNonZero() +{ + SemaRunnable r(2, 2); + r.wait(); + assert (r.tryWait(10)); + assert (!r.tryWait(10)); + r.set(); + assert (r.tryWait(10)); + assert (!r.tryWait(10)); +} + + +void SemaphoreTest::setUp() +{ +} + + +void SemaphoreTest::tearDown() +{ +} + + +CppUnit::Test* SemaphoreTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("SemaphoreTest"); + + CppUnit_addTest(pSuite, SemaphoreTest, testInitZero); + CppUnit_addTest(pSuite, SemaphoreTest, testInitNonZero); + + return pSuite; +} diff --git a/Foundation/testsuite/src/SemaphoreTest.h b/Foundation/testsuite/src/SemaphoreTest.h index df4b0dd00..7fee2006e 100644 --- a/Foundation/testsuite/src/SemaphoreTest.h +++ b/Foundation/testsuite/src/SemaphoreTest.h @@ -1,61 +1,61 @@ -// -// SemaphoreTest.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/SemaphoreTest.h#1 $ -// -// Definition of the SemaphoreTest class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 SemaphoreTest_INCLUDED -#define SemaphoreTest_INCLUDED - - -#include "Poco/Foundation.h" -#include "CppUnit/TestCase.h" - - -class SemaphoreTest: public CppUnit::TestCase -{ -public: - SemaphoreTest(const std::string& name); - ~SemaphoreTest(); - - void testInitZero(); - void testInitNonZero(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // SemaphoreTest_INCLUDED +// +// SemaphoreTest.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/SemaphoreTest.h#1 $ +// +// Definition of the SemaphoreTest class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 SemaphoreTest_INCLUDED +#define SemaphoreTest_INCLUDED + + +#include "Poco/Foundation.h" +#include "CppUnit/TestCase.h" + + +class SemaphoreTest: public CppUnit::TestCase +{ +public: + SemaphoreTest(const std::string& name); + ~SemaphoreTest(); + + void testInitZero(); + void testInitNonZero(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // SemaphoreTest_INCLUDED diff --git a/Foundation/testsuite/src/SharedLibraryTest.cpp b/Foundation/testsuite/src/SharedLibraryTest.cpp index 187804f26..a7f312878 100644 --- a/Foundation/testsuite/src/SharedLibraryTest.cpp +++ b/Foundation/testsuite/src/SharedLibraryTest.cpp @@ -1,171 +1,171 @@ -// -// SharedLibraryTest.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/SharedLibraryTest.cpp#1 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "SharedLibraryTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/SharedLibrary.h" -#include "Poco/Exception.h" - - -using Poco::SharedLibrary; -using Poco::NotFoundException; -using Poco::LibraryLoadException; -using Poco::LibraryAlreadyLoadedException; - - -typedef int (*GimmeFiveFunc)(); - - -SharedLibraryTest::SharedLibraryTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -SharedLibraryTest::~SharedLibraryTest() -{ -} - - -void SharedLibraryTest::testSharedLibrary1() -{ - std::string path = "TestLibrary"; - path.append(SharedLibrary::suffix()); - SharedLibrary sl; - assert (!sl.isLoaded()); - sl.load(path); - assert (sl.getPath() == path); - assert (sl.isLoaded()); - assert (sl.hasSymbol("pocoBuildManifest")); - assert (sl.hasSymbol("pocoInitializeLibrary")); - assert (sl.hasSymbol("pocoUninitializeLibrary")); - assert (sl.hasSymbol("gimmeFive")); - assert (!sl.hasSymbol("fooBar123")); - - void* p1 = sl.getSymbol("pocoBuildManifest"); - assertNotNullPtr(p1); - try - { - p1 = sl.getSymbol("fooBar123"); - failmsg("no such symbol - must throw exception"); - } - catch (NotFoundException&) - { - } - catch (...) - { - failmsg("wrong exception"); - } - sl.unload(); - assert (!sl.isLoaded()); -} - - -void SharedLibraryTest::testSharedLibrary2() -{ - std::string path = "TestLibrary"; - path.append(SharedLibrary::suffix()); - SharedLibrary sl(path); - assert (sl.getPath() == path); - assert (sl.isLoaded()); - - GimmeFiveFunc gimmeFive = (GimmeFiveFunc) sl.getSymbol("gimmeFive"); - assert (gimmeFive() == 5); - - sl.unload(); - assert (!sl.isLoaded()); -} - - -void SharedLibraryTest::testSharedLibrary3() -{ - std::string path = "NonexistentLibrary"; - path.append(SharedLibrary::suffix()); - SharedLibrary sl; - try - { - sl.load(path); - failmsg("no such library - must throw exception"); - } - catch (LibraryLoadException&) - { - } - catch (...) - { - failmsg("wrong exception"); - } - assert (!sl.isLoaded()); - - path = "TestLibrary"; - path.append(SharedLibrary::suffix()); - sl.load(path); - assert (sl.isLoaded()); - - try - { - sl.load(path); - failmsg("library already loaded - must throw exception"); - } - catch (LibraryAlreadyLoadedException&) - { - } - catch (...) - { - failmsg("wrong exception"); - } - assert (sl.isLoaded()); - - sl.unload(); - assert (!sl.isLoaded()); -} - - -void SharedLibraryTest::setUp() -{ -} - - -void SharedLibraryTest::tearDown() -{ -} - - -CppUnit::Test* SharedLibraryTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("SharedLibraryTest"); - - CppUnit_addTest(pSuite, SharedLibraryTest, testSharedLibrary1); - CppUnit_addTest(pSuite, SharedLibraryTest, testSharedLibrary2); - CppUnit_addTest(pSuite, SharedLibraryTest, testSharedLibrary3); - - return pSuite; -} +// +// SharedLibraryTest.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/SharedLibraryTest.cpp#1 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "SharedLibraryTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/SharedLibrary.h" +#include "Poco/Exception.h" + + +using Poco::SharedLibrary; +using Poco::NotFoundException; +using Poco::LibraryLoadException; +using Poco::LibraryAlreadyLoadedException; + + +typedef int (*GimmeFiveFunc)(); + + +SharedLibraryTest::SharedLibraryTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +SharedLibraryTest::~SharedLibraryTest() +{ +} + + +void SharedLibraryTest::testSharedLibrary1() +{ + std::string path = "TestLibrary"; + path.append(SharedLibrary::suffix()); + SharedLibrary sl; + assert (!sl.isLoaded()); + sl.load(path); + assert (sl.getPath() == path); + assert (sl.isLoaded()); + assert (sl.hasSymbol("pocoBuildManifest")); + assert (sl.hasSymbol("pocoInitializeLibrary")); + assert (sl.hasSymbol("pocoUninitializeLibrary")); + assert (sl.hasSymbol("gimmeFive")); + assert (!sl.hasSymbol("fooBar123")); + + void* p1 = sl.getSymbol("pocoBuildManifest"); + assertNotNullPtr(p1); + try + { + p1 = sl.getSymbol("fooBar123"); + failmsg("no such symbol - must throw exception"); + } + catch (NotFoundException&) + { + } + catch (...) + { + failmsg("wrong exception"); + } + sl.unload(); + assert (!sl.isLoaded()); +} + + +void SharedLibraryTest::testSharedLibrary2() +{ + std::string path = "TestLibrary"; + path.append(SharedLibrary::suffix()); + SharedLibrary sl(path); + assert (sl.getPath() == path); + assert (sl.isLoaded()); + + GimmeFiveFunc gimmeFive = (GimmeFiveFunc) sl.getSymbol("gimmeFive"); + assert (gimmeFive() == 5); + + sl.unload(); + assert (!sl.isLoaded()); +} + + +void SharedLibraryTest::testSharedLibrary3() +{ + std::string path = "NonexistentLibrary"; + path.append(SharedLibrary::suffix()); + SharedLibrary sl; + try + { + sl.load(path); + failmsg("no such library - must throw exception"); + } + catch (LibraryLoadException&) + { + } + catch (...) + { + failmsg("wrong exception"); + } + assert (!sl.isLoaded()); + + path = "TestLibrary"; + path.append(SharedLibrary::suffix()); + sl.load(path); + assert (sl.isLoaded()); + + try + { + sl.load(path); + failmsg("library already loaded - must throw exception"); + } + catch (LibraryAlreadyLoadedException&) + { + } + catch (...) + { + failmsg("wrong exception"); + } + assert (sl.isLoaded()); + + sl.unload(); + assert (!sl.isLoaded()); +} + + +void SharedLibraryTest::setUp() +{ +} + + +void SharedLibraryTest::tearDown() +{ +} + + +CppUnit::Test* SharedLibraryTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("SharedLibraryTest"); + + CppUnit_addTest(pSuite, SharedLibraryTest, testSharedLibrary1); + CppUnit_addTest(pSuite, SharedLibraryTest, testSharedLibrary2); + CppUnit_addTest(pSuite, SharedLibraryTest, testSharedLibrary3); + + return pSuite; +} diff --git a/Foundation/testsuite/src/SharedLibraryTest.h b/Foundation/testsuite/src/SharedLibraryTest.h index ea0f6073c..3f0070c89 100644 --- a/Foundation/testsuite/src/SharedLibraryTest.h +++ b/Foundation/testsuite/src/SharedLibraryTest.h @@ -1,62 +1,62 @@ -// -// SharedLibraryTest.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/SharedLibraryTest.h#1 $ -// -// Definition of the SharedLibraryTest class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 SharedLibraryTest_INCLUDED -#define SharedLibraryTest_INCLUDED - - -#include "Poco/Foundation.h" -#include "CppUnit/TestCase.h" - - -class SharedLibraryTest: public CppUnit::TestCase -{ -public: - SharedLibraryTest(const std::string& name); - ~SharedLibraryTest(); - - void testSharedLibrary1(); - void testSharedLibrary2(); - void testSharedLibrary3(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // SharedLibraryTest_INCLUDED +// +// SharedLibraryTest.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/SharedLibraryTest.h#1 $ +// +// Definition of the SharedLibraryTest class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 SharedLibraryTest_INCLUDED +#define SharedLibraryTest_INCLUDED + + +#include "Poco/Foundation.h" +#include "CppUnit/TestCase.h" + + +class SharedLibraryTest: public CppUnit::TestCase +{ +public: + SharedLibraryTest(const std::string& name); + ~SharedLibraryTest(); + + void testSharedLibrary1(); + void testSharedLibrary2(); + void testSharedLibrary3(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // SharedLibraryTest_INCLUDED diff --git a/Foundation/testsuite/src/SharedLibraryTestSuite.cpp b/Foundation/testsuite/src/SharedLibraryTestSuite.cpp index b2430659a..ea32003c1 100644 --- a/Foundation/testsuite/src/SharedLibraryTestSuite.cpp +++ b/Foundation/testsuite/src/SharedLibraryTestSuite.cpp @@ -1,48 +1,48 @@ -// -// SharedLibraryTestSuite.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/SharedLibraryTestSuite.cpp#1 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "SharedLibraryTestSuite.h" -#include "ClassLoaderTest.h" -#include "ManifestTest.h" -#include "SharedLibraryTest.h" - - -CppUnit::Test* SharedLibraryTestSuite::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("SharedLibraryTestSuite"); - - pSuite->addTest(SharedLibraryTest::suite()); - pSuite->addTest(ManifestTest::suite()); - pSuite->addTest(ClassLoaderTest::suite()); - - return pSuite; -} +// +// SharedLibraryTestSuite.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/SharedLibraryTestSuite.cpp#1 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "SharedLibraryTestSuite.h" +#include "ClassLoaderTest.h" +#include "ManifestTest.h" +#include "SharedLibraryTest.h" + + +CppUnit::Test* SharedLibraryTestSuite::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("SharedLibraryTestSuite"); + + pSuite->addTest(SharedLibraryTest::suite()); + pSuite->addTest(ManifestTest::suite()); + pSuite->addTest(ClassLoaderTest::suite()); + + return pSuite; +} diff --git a/Foundation/testsuite/src/SharedLibraryTestSuite.h b/Foundation/testsuite/src/SharedLibraryTestSuite.h index 9b080bfff..71d1ec9f9 100644 --- a/Foundation/testsuite/src/SharedLibraryTestSuite.h +++ b/Foundation/testsuite/src/SharedLibraryTestSuite.h @@ -1,49 +1,49 @@ -// -// SharedLibraryTestSuite.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/SharedLibraryTestSuite.h#1 $ -// -// Definition of the SharedLibraryTestSuite class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 SharedLibraryTestSuite_INCLUDED -#define SharedLibraryTestSuite_INCLUDED - - -#include "CppUnit/TestSuite.h" - - -class SharedLibraryTestSuite -{ -public: - static CppUnit::Test* suite(); -}; - - -#endif // SharedLibraryTestSuite_INCLUDED +// +// SharedLibraryTestSuite.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/SharedLibraryTestSuite.h#1 $ +// +// Definition of the SharedLibraryTestSuite class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 SharedLibraryTestSuite_INCLUDED +#define SharedLibraryTestSuite_INCLUDED + + +#include "CppUnit/TestSuite.h" + + +class SharedLibraryTestSuite +{ +public: + static CppUnit::Test* suite(); +}; + + +#endif // SharedLibraryTestSuite_INCLUDED diff --git a/Foundation/testsuite/src/SharedPtrTest.cpp b/Foundation/testsuite/src/SharedPtrTest.cpp index 897346328..d72f587d2 100644 --- a/Foundation/testsuite/src/SharedPtrTest.cpp +++ b/Foundation/testsuite/src/SharedPtrTest.cpp @@ -1,234 +1,234 @@ -// -// SharedPtrTest.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/SharedPtrTest.cpp#2 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "SharedPtrTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/SharedPtr.h" -#include "Poco/Exception.h" - - -using Poco::SharedPtr; -using Poco::NullPointerException; - - -namespace -{ - class TestObject - { - public: - TestObject(const std::string& data): _data(data) - { - ++_count; - } - - virtual ~TestObject() - { - --_count; - } - - const std::string& data() - { - return _data; - } - - static int count() - { - return _count; - } - - private: - std::string _data; - static int _count; - }; - - int TestObject::_count = 0; - - class DerivedObject: public TestObject - { - public: - DerivedObject(const std::string& s, int i): TestObject(s), _number(i) - { - } - - int number() const - { - return _number; - } - private: - int _number; - }; -} - - -SharedPtrTest::SharedPtrTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -SharedPtrTest::~SharedPtrTest() -{ -} - - -void SharedPtrTest::testSharedPtr() -{ - SharedPtr ptr1; - assertNull(ptr1.get()); - TestObject* pTO1 = new TestObject("one"); - TestObject* pTO2 = new TestObject("two"); - if (pTO2 < pTO1) - { - TestObject* pTmp = pTO1; - pTO1 = pTO2; - pTO2 = pTmp; - } - assert (pTO1 < pTO2); - ptr1 = pTO1; - SharedPtr ptr2 = pTO2; - SharedPtr ptr3 = ptr1; - SharedPtr ptr4; - assert (ptr1.get() == pTO1); - assert (ptr1 == pTO1); - assert (ptr2.get() == pTO2); - assert (ptr2 == pTO2); - assert (ptr3.get() == pTO1); - assert (ptr3 == pTO1); - - assert (ptr1 == pTO1); - assert (ptr1 != pTO2); - assert (ptr1 < pTO2); - assert (ptr1 <= pTO2); - assert (ptr2 > pTO1); - assert (ptr2 >= pTO1); - - assert (ptr1 == ptr3); - assert (ptr1 != ptr2); - assert (ptr1 < ptr2); - assert (ptr1 <= ptr2); - assert (ptr2 > ptr1); - assert (ptr2 >= ptr1); - - ptr1.swap(ptr2); - assert (ptr2 < ptr1); - ptr2.swap(ptr1); - - assert (ptr1->data() == "one" && ptr2->data() == "two" || ptr1->data() == "two" && ptr2->data() == "one"); - - try - { - assert (ptr4->data() == "four"); - fail ("must throw NullPointerException"); - } - catch (NullPointerException&) - { - } - - assert (!(ptr4 == ptr1)); - assert (!(ptr4 == ptr2)); - assert (ptr4 != ptr1); - assert (ptr4 != ptr2); - - ptr4 = ptr2; - assert (ptr4 == ptr2); - assert (!(ptr4 != ptr2)); - - assert (TestObject::count() == 2); - ptr1 = 0; - ptr2 = 0; - ptr3 = 0; - ptr4 = 0; - assert (TestObject::count() == 0); - - { - SharedPtr ptr = new TestObject(""); - assert (TestObject::count() == 1); - } - assert (TestObject::count() == 0); -} - - -void SharedPtrTest::testImplicitCast() -{ - { - // null assign test - SharedPtr ptr2; - assertNull(ptr2.get()); - SharedPtr ptr1 = ptr2; - } - { - SharedPtr ptr2(new DerivedObject("test", 666)); - assert (TestObject::count() == 1); - SharedPtr ptr1 = ptr2; - assert (TestObject::count() == 1); - } - assert (TestObject::count() == 0); - SharedPtr ptr1 = new DerivedObject("test", 666); - assert (TestObject::count() == 1); - ptr1 = 0; - assert (TestObject::count() == 0); -} - -void SharedPtrTest::testExplicitCast() -{ - SharedPtr ptr1 = new DerivedObject("test", 666); - SharedPtr ptr2 = ptr1.cast(); - assert (ptr2.get() != 0); - - // cast the other way round must fail - ptr1 = new TestObject("test"); - assert (TestObject::count() == 2); - ptr2 = ptr1.cast(); - assert (TestObject::count() == 1); - assert (ptr2.get() == 0); -} - -void SharedPtrTest::setUp() -{ -} - - -void SharedPtrTest::tearDown() -{ -} - - -CppUnit::Test* SharedPtrTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("SharedPtrTest"); - - CppUnit_addTest(pSuite, SharedPtrTest, testSharedPtr); - CppUnit_addTest(pSuite, SharedPtrTest, testImplicitCast); - CppUnit_addTest(pSuite, SharedPtrTest, testExplicitCast); - - return pSuite; -} +// +// SharedPtrTest.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/SharedPtrTest.cpp#2 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "SharedPtrTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/SharedPtr.h" +#include "Poco/Exception.h" + + +using Poco::SharedPtr; +using Poco::NullPointerException; + + +namespace +{ + class TestObject + { + public: + TestObject(const std::string& data): _data(data) + { + ++_count; + } + + virtual ~TestObject() + { + --_count; + } + + const std::string& data() + { + return _data; + } + + static int count() + { + return _count; + } + + private: + std::string _data; + static int _count; + }; + + int TestObject::_count = 0; + + class DerivedObject: public TestObject + { + public: + DerivedObject(const std::string& s, int i): TestObject(s), _number(i) + { + } + + int number() const + { + return _number; + } + private: + int _number; + }; +} + + +SharedPtrTest::SharedPtrTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +SharedPtrTest::~SharedPtrTest() +{ +} + + +void SharedPtrTest::testSharedPtr() +{ + SharedPtr ptr1; + assertNull(ptr1.get()); + TestObject* pTO1 = new TestObject("one"); + TestObject* pTO2 = new TestObject("two"); + if (pTO2 < pTO1) + { + TestObject* pTmp = pTO1; + pTO1 = pTO2; + pTO2 = pTmp; + } + assert (pTO1 < pTO2); + ptr1 = pTO1; + SharedPtr ptr2 = pTO2; + SharedPtr ptr3 = ptr1; + SharedPtr ptr4; + assert (ptr1.get() == pTO1); + assert (ptr1 == pTO1); + assert (ptr2.get() == pTO2); + assert (ptr2 == pTO2); + assert (ptr3.get() == pTO1); + assert (ptr3 == pTO1); + + assert (ptr1 == pTO1); + assert (ptr1 != pTO2); + assert (ptr1 < pTO2); + assert (ptr1 <= pTO2); + assert (ptr2 > pTO1); + assert (ptr2 >= pTO1); + + assert (ptr1 == ptr3); + assert (ptr1 != ptr2); + assert (ptr1 < ptr2); + assert (ptr1 <= ptr2); + assert (ptr2 > ptr1); + assert (ptr2 >= ptr1); + + ptr1.swap(ptr2); + assert (ptr2 < ptr1); + ptr2.swap(ptr1); + + assert (ptr1->data() == "one" && ptr2->data() == "two" || ptr1->data() == "two" && ptr2->data() == "one"); + + try + { + assert (ptr4->data() == "four"); + fail ("must throw NullPointerException"); + } + catch (NullPointerException&) + { + } + + assert (!(ptr4 == ptr1)); + assert (!(ptr4 == ptr2)); + assert (ptr4 != ptr1); + assert (ptr4 != ptr2); + + ptr4 = ptr2; + assert (ptr4 == ptr2); + assert (!(ptr4 != ptr2)); + + assert (TestObject::count() == 2); + ptr1 = 0; + ptr2 = 0; + ptr3 = 0; + ptr4 = 0; + assert (TestObject::count() == 0); + + { + SharedPtr ptr = new TestObject(""); + assert (TestObject::count() == 1); + } + assert (TestObject::count() == 0); +} + + +void SharedPtrTest::testImplicitCast() +{ + { + // null assign test + SharedPtr ptr2; + assertNull(ptr2.get()); + SharedPtr ptr1 = ptr2; + } + { + SharedPtr ptr2(new DerivedObject("test", 666)); + assert (TestObject::count() == 1); + SharedPtr ptr1 = ptr2; + assert (TestObject::count() == 1); + } + assert (TestObject::count() == 0); + SharedPtr ptr1 = new DerivedObject("test", 666); + assert (TestObject::count() == 1); + ptr1 = 0; + assert (TestObject::count() == 0); +} + +void SharedPtrTest::testExplicitCast() +{ + SharedPtr ptr1 = new DerivedObject("test", 666); + SharedPtr ptr2 = ptr1.cast(); + assert (ptr2.get() != 0); + + // cast the other way round must fail + ptr1 = new TestObject("test"); + assert (TestObject::count() == 2); + ptr2 = ptr1.cast(); + assert (TestObject::count() == 1); + assert (ptr2.get() == 0); +} + +void SharedPtrTest::setUp() +{ +} + + +void SharedPtrTest::tearDown() +{ +} + + +CppUnit::Test* SharedPtrTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("SharedPtrTest"); + + CppUnit_addTest(pSuite, SharedPtrTest, testSharedPtr); + CppUnit_addTest(pSuite, SharedPtrTest, testImplicitCast); + CppUnit_addTest(pSuite, SharedPtrTest, testExplicitCast); + + return pSuite; +} diff --git a/Foundation/testsuite/src/SharedPtrTest.h b/Foundation/testsuite/src/SharedPtrTest.h index 8f0affea4..791bec69c 100644 --- a/Foundation/testsuite/src/SharedPtrTest.h +++ b/Foundation/testsuite/src/SharedPtrTest.h @@ -1,63 +1,63 @@ -// -// SharedPtrTest.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/SharedPtrTest.h#1 $ -// -// Definition of the SharedPtrTest class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 SharedPtrTest_INCLUDED -#define SharedPtrTest_INCLUDED - - -#include "Poco/Foundation.h" -#include "CppUnit/TestCase.h" - - -class SharedPtrTest: public CppUnit::TestCase -{ -public: - SharedPtrTest(const std::string& name); - ~SharedPtrTest(); - - void testSharedPtr(); - - void testImplicitCast(); - void testExplicitCast(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // SharedPtrTest_INCLUDED +// +// SharedPtrTest.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/SharedPtrTest.h#1 $ +// +// Definition of the SharedPtrTest class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 SharedPtrTest_INCLUDED +#define SharedPtrTest_INCLUDED + + +#include "Poco/Foundation.h" +#include "CppUnit/TestCase.h" + + +class SharedPtrTest: public CppUnit::TestCase +{ +public: + SharedPtrTest(const std::string& name); + ~SharedPtrTest(); + + void testSharedPtr(); + + void testImplicitCast(); + void testExplicitCast(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // SharedPtrTest_INCLUDED diff --git a/Foundation/testsuite/src/SimpleFileChannelTest.cpp b/Foundation/testsuite/src/SimpleFileChannelTest.cpp index c470172b8..b1f734f7b 100644 --- a/Foundation/testsuite/src/SimpleFileChannelTest.cpp +++ b/Foundation/testsuite/src/SimpleFileChannelTest.cpp @@ -1,147 +1,147 @@ -// -// SimpleFileChannelTest.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/SimpleFileChannelTest.cpp#1 $ -// -// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "Poco/SimpleFileChannel.h" -#include "Poco/Message.h" -#include "Poco/Path.h" -#include "Poco/File.h" -#include "Poco/DirectoryIterator.h" -#include "Poco/Timestamp.h" -#include "Poco/DateTimeFormatter.h" -#include "Poco/AutoPtr.h" -#include "SimpleFileChannelTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" - - -using Poco::SimpleFileChannel; -using Poco::Message; -using Poco::Path; -using Poco::File; -using Poco::DirectoryIterator; -using Poco::Timestamp; -using Poco::DateTimeFormatter; -using Poco::AutoPtr; - - -SimpleFileChannelTest::SimpleFileChannelTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -SimpleFileChannelTest::~SimpleFileChannelTest() -{ -} - - -void SimpleFileChannelTest::testRotate() -{ - std::string name = filename(); - try - { - AutoPtr pChannel = new SimpleFileChannel(name); - pChannel->setProperty(SimpleFileChannel::PROP_ROTATION, "2 K"); - pChannel->open(); - Message msg("source", "This is a log file entry", Message::PRIO_INFORMATION); - for (int i = 0; i < 200; ++i) - { - pChannel->log(msg); - } - File f(name); - assert (f.exists()); - f = name + ".0"; - assert (f.exists()); - assert (f.getSize() >= 2048); - } - catch (...) - { - remove(name); - throw; - } - remove(name); -} - - -void SimpleFileChannelTest::setUp() -{ -} - - -void SimpleFileChannelTest::tearDown() -{ -} - - -void SimpleFileChannelTest::remove(const std::string& baseName) -{ - DirectoryIterator it(Path::current()); - DirectoryIterator end; - std::vector files; - while (it != end) - { - if (it.name().find(baseName) == 0) - { - files.push_back(it.name()); - } - ++it; - } - for (std::vector::iterator it = files.begin(); it != files.end(); ++it) - { - try - { - File f(*it); - f.remove(); - } - catch (...) - { - } - } -} - - -std::string SimpleFileChannelTest::filename() const -{ - std::string name = "log_"; - name.append(DateTimeFormatter::format(Timestamp(), "%Y%m%d%H%M%S")); - name.append(".log"); - return name; -} - - -CppUnit::Test* SimpleFileChannelTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("SimpleFileChannelTest"); - - CppUnit_addTest(pSuite, SimpleFileChannelTest, testRotate); - - return pSuite; -} +// +// SimpleFileChannelTest.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/SimpleFileChannelTest.cpp#1 $ +// +// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "Poco/SimpleFileChannel.h" +#include "Poco/Message.h" +#include "Poco/Path.h" +#include "Poco/File.h" +#include "Poco/DirectoryIterator.h" +#include "Poco/Timestamp.h" +#include "Poco/DateTimeFormatter.h" +#include "Poco/AutoPtr.h" +#include "SimpleFileChannelTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" + + +using Poco::SimpleFileChannel; +using Poco::Message; +using Poco::Path; +using Poco::File; +using Poco::DirectoryIterator; +using Poco::Timestamp; +using Poco::DateTimeFormatter; +using Poco::AutoPtr; + + +SimpleFileChannelTest::SimpleFileChannelTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +SimpleFileChannelTest::~SimpleFileChannelTest() +{ +} + + +void SimpleFileChannelTest::testRotate() +{ + std::string name = filename(); + try + { + AutoPtr pChannel = new SimpleFileChannel(name); + pChannel->setProperty(SimpleFileChannel::PROP_ROTATION, "2 K"); + pChannel->open(); + Message msg("source", "This is a log file entry", Message::PRIO_INFORMATION); + for (int i = 0; i < 200; ++i) + { + pChannel->log(msg); + } + File f(name); + assert (f.exists()); + f = name + ".0"; + assert (f.exists()); + assert (f.getSize() >= 2048); + } + catch (...) + { + remove(name); + throw; + } + remove(name); +} + + +void SimpleFileChannelTest::setUp() +{ +} + + +void SimpleFileChannelTest::tearDown() +{ +} + + +void SimpleFileChannelTest::remove(const std::string& baseName) +{ + DirectoryIterator it(Path::current()); + DirectoryIterator end; + std::vector files; + while (it != end) + { + if (it.name().find(baseName) == 0) + { + files.push_back(it.name()); + } + ++it; + } + for (std::vector::iterator it = files.begin(); it != files.end(); ++it) + { + try + { + File f(*it); + f.remove(); + } + catch (...) + { + } + } +} + + +std::string SimpleFileChannelTest::filename() const +{ + std::string name = "log_"; + name.append(DateTimeFormatter::format(Timestamp(), "%Y%m%d%H%M%S")); + name.append(".log"); + return name; +} + + +CppUnit::Test* SimpleFileChannelTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("SimpleFileChannelTest"); + + CppUnit_addTest(pSuite, SimpleFileChannelTest, testRotate); + + return pSuite; +} diff --git a/Foundation/testsuite/src/SimpleFileChannelTest.h b/Foundation/testsuite/src/SimpleFileChannelTest.h index 4204fe583..b11930f63 100644 --- a/Foundation/testsuite/src/SimpleFileChannelTest.h +++ b/Foundation/testsuite/src/SimpleFileChannelTest.h @@ -1,62 +1,62 @@ -// -// SimpleFileChannelTest.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/SimpleFileChannelTest.h#1 $ -// -// Definition of the SimpleFileChannelTest class. -// -// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 SimpleFileChannelTest_INCLUDED -#define SimpleFileChannelTest_INCLUDED - - -#include "Poco/Foundation.h" -#include "CppUnit/TestCase.h" - - -class SimpleFileChannelTest: public CppUnit::TestCase -{ -public: - SimpleFileChannelTest(const std::string& name); - ~SimpleFileChannelTest(); - - void testRotate(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: - void remove(const std::string& baseName); - std::string filename() const; -}; - - -#endif // SimpleFileChannelTest_INCLUDED +// +// SimpleFileChannelTest.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/SimpleFileChannelTest.h#1 $ +// +// Definition of the SimpleFileChannelTest class. +// +// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 SimpleFileChannelTest_INCLUDED +#define SimpleFileChannelTest_INCLUDED + + +#include "Poco/Foundation.h" +#include "CppUnit/TestCase.h" + + +class SimpleFileChannelTest: public CppUnit::TestCase +{ +public: + SimpleFileChannelTest(const std::string& name); + ~SimpleFileChannelTest(); + + void testRotate(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: + void remove(const std::string& baseName); + std::string filename() const; +}; + + +#endif // SimpleFileChannelTest_INCLUDED diff --git a/Foundation/testsuite/src/StopwatchTest.cpp b/Foundation/testsuite/src/StopwatchTest.cpp index b619f4c40..544da569b 100644 --- a/Foundation/testsuite/src/StopwatchTest.cpp +++ b/Foundation/testsuite/src/StopwatchTest.cpp @@ -1,98 +1,98 @@ -// -// StopwatchTest.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/StopwatchTest.cpp#1 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "StopwatchTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/Stopwatch.h" -#include "Poco/Timestamp.h" -#include "Poco/Thread.h" - - -using Poco::Stopwatch; -using Poco::Timestamp; -using Poco::Thread; - - -StopwatchTest::StopwatchTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -StopwatchTest::~StopwatchTest() -{ -} - - -void StopwatchTest::testStopwatch() -{ - Stopwatch sw; - sw.start(); - Thread::sleep(200); - sw.stop(); - Timestamp::TimeDiff d = sw.elapsed(); - assert (d >= 180000 && d <= 300000); - sw.start(); - Thread::sleep(100); - d = sw.elapsed(); - assert (d >= 280000 && d <= 400000); - Thread::sleep(100); - sw.stop(); - d = sw.elapsed(); - assert (d >= 380000 && d <= 500000); - sw.reset(); - sw.start(); - Thread::sleep(200); - sw.stop(); - d = sw.elapsed(); - assert (d >= 180000 && d <= 300000); -} - - -void StopwatchTest::setUp() -{ -} - - -void StopwatchTest::tearDown() -{ -} - - -CppUnit::Test* StopwatchTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("StopwatchTest"); - - CppUnit_addTest(pSuite, StopwatchTest, testStopwatch); - - return pSuite; -} +// +// StopwatchTest.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/StopwatchTest.cpp#1 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "StopwatchTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/Stopwatch.h" +#include "Poco/Timestamp.h" +#include "Poco/Thread.h" + + +using Poco::Stopwatch; +using Poco::Timestamp; +using Poco::Thread; + + +StopwatchTest::StopwatchTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +StopwatchTest::~StopwatchTest() +{ +} + + +void StopwatchTest::testStopwatch() +{ + Stopwatch sw; + sw.start(); + Thread::sleep(200); + sw.stop(); + Timestamp::TimeDiff d = sw.elapsed(); + assert (d >= 180000 && d <= 300000); + sw.start(); + Thread::sleep(100); + d = sw.elapsed(); + assert (d >= 280000 && d <= 400000); + Thread::sleep(100); + sw.stop(); + d = sw.elapsed(); + assert (d >= 380000 && d <= 500000); + sw.reset(); + sw.start(); + Thread::sleep(200); + sw.stop(); + d = sw.elapsed(); + assert (d >= 180000 && d <= 300000); +} + + +void StopwatchTest::setUp() +{ +} + + +void StopwatchTest::tearDown() +{ +} + + +CppUnit::Test* StopwatchTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("StopwatchTest"); + + CppUnit_addTest(pSuite, StopwatchTest, testStopwatch); + + return pSuite; +} diff --git a/Foundation/testsuite/src/StopwatchTest.h b/Foundation/testsuite/src/StopwatchTest.h index 526df1d2e..536fabf14 100644 --- a/Foundation/testsuite/src/StopwatchTest.h +++ b/Foundation/testsuite/src/StopwatchTest.h @@ -1,60 +1,60 @@ -// -// StopwatchTest.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/StopwatchTest.h#1 $ -// -// Definition of the StopwatchTest class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 StopwatchTest_INCLUDED -#define StopwatchTest_INCLUDED - - -#include "Poco/Foundation.h" -#include "CppUnit/TestCase.h" - - -class StopwatchTest: public CppUnit::TestCase -{ -public: - StopwatchTest(const std::string& name); - ~StopwatchTest(); - - void testStopwatch(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // StopwatchTest_INCLUDED +// +// StopwatchTest.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/StopwatchTest.h#1 $ +// +// Definition of the StopwatchTest class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 StopwatchTest_INCLUDED +#define StopwatchTest_INCLUDED + + +#include "Poco/Foundation.h" +#include "CppUnit/TestCase.h" + + +class StopwatchTest: public CppUnit::TestCase +{ +public: + StopwatchTest(const std::string& name); + ~StopwatchTest(); + + void testStopwatch(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // StopwatchTest_INCLUDED diff --git a/Foundation/testsuite/src/StreamConverterTest.cpp b/Foundation/testsuite/src/StreamConverterTest.cpp index db1a116f8..7736562b2 100644 --- a/Foundation/testsuite/src/StreamConverterTest.cpp +++ b/Foundation/testsuite/src/StreamConverterTest.cpp @@ -1,323 +1,323 @@ -// -// StreamConverterTest.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/StreamConverterTest.cpp#1 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "StreamConverterTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/StreamConverter.h" -#include "Poco/ASCIIEncoding.h" -#include "Poco/Latin1Encoding.h" -#include "Poco/UTF8Encoding.h" -#include "Poco/StreamCopier.h" -#include - - -using Poco::InputStreamConverter; -using Poco::OutputStreamConverter; -using Poco::Latin1Encoding; -using Poco::UTF8Encoding; -using Poco::ASCIIEncoding; -using Poco::StreamCopier; - - -StreamConverterTest::StreamConverterTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -StreamConverterTest::~StreamConverterTest() -{ -} - - -void StreamConverterTest::testIdentityASCIIIn() -{ - ASCIIEncoding encoding; - - std::istringstream istr1(""); - std::ostringstream ostr1; - InputStreamConverter converter1(istr1, encoding, encoding); - StreamCopier::copyStream(converter1, ostr1); - assert (ostr1.str() == ""); - assert (converter1.errors() == 0); - - std::istringstream istr2("foo bar"); - std::ostringstream ostr2; - InputStreamConverter converter2(istr2, encoding, encoding); - StreamCopier::copyStream(converter2, ostr2); - assert (ostr2.str() == "foo bar"); - assert (converter2.errors() == 0); - - std::istringstream istr3("x"); - std::ostringstream ostr3; - InputStreamConverter converter3(istr3, encoding, encoding); - StreamCopier::copyStream(converter3, ostr3); - assert (ostr3.str() == "x"); - assert (converter3.errors() == 0); -} - - -void StreamConverterTest::testIdentityASCIIOut() -{ - ASCIIEncoding encoding; - - std::ostringstream ostr1; - OutputStreamConverter converter1(ostr1, encoding, encoding); - converter1 << ""; - assert (ostr1.str() == ""); - assert (converter1.errors() == 0); - - std::ostringstream ostr2; - OutputStreamConverter converter2(ostr2, encoding, encoding); - converter2 << "foo bar"; - assert (ostr2.str() == "foo bar"); - assert (converter2.errors() == 0); - - std::ostringstream ostr3; - OutputStreamConverter converter3(ostr3, encoding, encoding); - converter3 << "x"; - assert (ostr3.str() == "x"); - assert (converter3.errors() == 0); -} - - -void StreamConverterTest::testIdentityUTF8In() -{ - UTF8Encoding encoding; - - std::istringstream istr1(""); - std::ostringstream ostr1; - InputStreamConverter converter1(istr1, encoding, encoding); - StreamCopier::copyStream(converter1, ostr1); - assert (ostr1.str() == ""); - assert (converter1.errors() == 0); - - std::istringstream istr2("foo bar"); - std::ostringstream ostr2; - InputStreamConverter converter2(istr2, encoding, encoding); - StreamCopier::copyStream(converter2, ostr2); - assert (ostr2.str() == "foo bar"); - assert (converter2.errors() == 0); - - std::istringstream istr3("x"); - std::ostringstream ostr3; - InputStreamConverter converter3(istr3, encoding, encoding); - StreamCopier::copyStream(converter3, ostr3); - assert (ostr3.str() == "x"); - assert (converter3.errors() == 0); - - const unsigned char greek[] = {0x20, 0xce, 0xba, 0xe1, 0xbd, 0xb9, 0xcf, 0x83, 0xce, 0xbc, 0xce, 0xb5, 0x20, 0x00}; - std::string text((const char*) greek); - - std::istringstream istr4(text); - std::ostringstream ostr4; - InputStreamConverter converter4(istr4, encoding, encoding); - StreamCopier::copyStream(converter4, ostr4); - assert (ostr4.str() == text); - assert (converter4.errors() == 0); -} - - -void StreamConverterTest::testIdentityUTF8Out() -{ - UTF8Encoding encoding; - - std::ostringstream ostr1; - OutputStreamConverter converter1(ostr1, encoding, encoding); - converter1 << ""; - assert (ostr1.str() == ""); - assert (converter1.errors() == 0); - - std::ostringstream ostr2; - OutputStreamConverter converter2(ostr2, encoding, encoding); - converter2 << "foo bar"; - assert (ostr2.str() == "foo bar"); - assert (converter2.errors() == 0); - - std::ostringstream ostr3; - OutputStreamConverter converter3(ostr3, encoding, encoding); - converter3 << "x"; - assert (ostr3.str() == "x"); - assert (converter3.errors() == 0); - - const unsigned char greek[] = {0x20, 0xce, 0xba, 0xe1, 0xbd, 0xb9, 0xcf, 0x83, 0xce, 0xbc, 0xce, 0xb5, 0x20, 0x00}; - std::string text((const char*) greek); - - std::ostringstream ostr4; - OutputStreamConverter converter4(ostr4, encoding, encoding); - converter4 << text; - assert (ostr4.str() == text); - assert (converter4.errors() == 0); -} - - -void StreamConverterTest::testUTF8toASCIIIn() -{ - UTF8Encoding utf8Encoding; - ASCIIEncoding asciiEncoding; - - const unsigned char greek[] = {0x20, 0xce, 0xba, 0xe1, 0xbd, 0xb9, 0xcf, 0x83, 0xce, 0xbc, 0xce, 0xb5, 0x20, 0x41, 0x42, 0x00}; - std::string text((const char*) greek); - - std::istringstream istr1(text); - std::ostringstream ostr1; - InputStreamConverter converter1(istr1, utf8Encoding, asciiEncoding); - StreamCopier::copyStream(converter1, ostr1); - assert (ostr1.str() == " ????? AB"); - assert (converter1.errors() == 0); - - std::istringstream istr2("abcde"); - std::ostringstream ostr2; - InputStreamConverter converter2(istr2, utf8Encoding, asciiEncoding); - StreamCopier::copyStream(converter2, ostr2); - assert (ostr2.str() == "abcde"); - assert (converter2.errors() == 0); -} - - -void StreamConverterTest::testUTF8toASCIIOut() -{ - UTF8Encoding utf8Encoding; - ASCIIEncoding asciiEncoding; - - const unsigned char greek[] = {0x20, 0xce, 0xba, 0xe1, 0xbd, 0xb9, 0xcf, 0x83, 0xce, 0xbc, 0xce, 0xb5, 0x20, 0x41, 0x42, 0x00}; - std::string text((const char*) greek); - - std::ostringstream ostr1; - OutputStreamConverter converter1(ostr1, utf8Encoding, asciiEncoding); - converter1 << text; - assert (ostr1.str() == " ????? AB"); - assert (converter1.errors() == 0); - - std::ostringstream ostr2; - OutputStreamConverter converter2(ostr2, utf8Encoding, asciiEncoding); - converter2 << "abcde"; - assert (ostr2.str() == "abcde"); - assert (converter2.errors() == 0); -} - - -void StreamConverterTest::testLatin1toUTF8In() -{ - UTF8Encoding utf8Encoding; - Latin1Encoding latin1Encoding; - - const unsigned char latin1Chars[] = {'g', 252, 'n', 't', 'e', 'r', 0}; - const unsigned char utf8Chars[] = {'g', 195, 188, 'n', 't', 'e', 'r', 0}; - std::string latin1Text((const char*) latin1Chars); - std::string utf8Text((const char*) utf8Chars); - - std::istringstream istr1(latin1Text); - std::ostringstream ostr1; - InputStreamConverter converter1(istr1, latin1Encoding, utf8Encoding); - StreamCopier::copyStream(converter1, ostr1); - assert (ostr1.str() == utf8Text); - assert (converter1.errors() == 0); -} - - -void StreamConverterTest::testLatin1toUTF8Out() -{ - UTF8Encoding utf8Encoding; - Latin1Encoding latin1Encoding; - - const unsigned char latin1Chars[] = {'g', 252, 'n', 't', 'e', 'r', 0}; - const unsigned char utf8Chars[] = {'g', 195, 188, 'n', 't', 'e', 'r', 0}; - std::string latin1Text((const char*) latin1Chars); - std::string utf8Text((const char*) utf8Chars); - - std::ostringstream ostr1; - OutputStreamConverter converter1(ostr1, latin1Encoding, utf8Encoding); - converter1 << latin1Text; - assert (ostr1.str() == utf8Text); - assert (converter1.errors() == 0); -} - - -void StreamConverterTest::testErrorsIn() -{ - UTF8Encoding utf8Encoding; - Latin1Encoding latin1Encoding; - - const unsigned char badChars[] = {'a', 'b', 255, 'c', 254, 0}; - std::string badText((const char*) badChars); - - std::istringstream istr1(badText); - std::ostringstream ostr1; - InputStreamConverter converter1(istr1, utf8Encoding, latin1Encoding); - StreamCopier::copyStream(converter1, ostr1); - assert (converter1.errors() == 2); -} - - -void StreamConverterTest::testErrorsOut() -{ - UTF8Encoding utf8Encoding; - Latin1Encoding latin1Encoding; - - const unsigned char badChars[] = {'a', 'b', 255, 'c', 254, 0}; - std::string badText((const char*) badChars); - - std::ostringstream ostr1; - OutputStreamConverter converter1(ostr1, utf8Encoding, latin1Encoding); - converter1 << badText; - assert (converter1.errors() == 1); -} - - -void StreamConverterTest::setUp() -{ -} - - -void StreamConverterTest::tearDown() -{ -} - - -CppUnit::Test* StreamConverterTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("StreamConverterTest"); - - CppUnit_addTest(pSuite, StreamConverterTest, testIdentityASCIIIn); - CppUnit_addTest(pSuite, StreamConverterTest, testIdentityASCIIOut); - CppUnit_addTest(pSuite, StreamConverterTest, testIdentityUTF8In); - CppUnit_addTest(pSuite, StreamConverterTest, testIdentityUTF8Out); - CppUnit_addTest(pSuite, StreamConverterTest, testUTF8toASCIIIn); - CppUnit_addTest(pSuite, StreamConverterTest, testUTF8toASCIIOut); - CppUnit_addTest(pSuite, StreamConverterTest, testLatin1toUTF8In); - CppUnit_addTest(pSuite, StreamConverterTest, testLatin1toUTF8Out); - CppUnit_addTest(pSuite, StreamConverterTest, testErrorsIn); - CppUnit_addTest(pSuite, StreamConverterTest, testErrorsOut); - - return pSuite; -} +// +// StreamConverterTest.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/StreamConverterTest.cpp#1 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "StreamConverterTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/StreamConverter.h" +#include "Poco/ASCIIEncoding.h" +#include "Poco/Latin1Encoding.h" +#include "Poco/UTF8Encoding.h" +#include "Poco/StreamCopier.h" +#include + + +using Poco::InputStreamConverter; +using Poco::OutputStreamConverter; +using Poco::Latin1Encoding; +using Poco::UTF8Encoding; +using Poco::ASCIIEncoding; +using Poco::StreamCopier; + + +StreamConverterTest::StreamConverterTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +StreamConverterTest::~StreamConverterTest() +{ +} + + +void StreamConverterTest::testIdentityASCIIIn() +{ + ASCIIEncoding encoding; + + std::istringstream istr1(""); + std::ostringstream ostr1; + InputStreamConverter converter1(istr1, encoding, encoding); + StreamCopier::copyStream(converter1, ostr1); + assert (ostr1.str() == ""); + assert (converter1.errors() == 0); + + std::istringstream istr2("foo bar"); + std::ostringstream ostr2; + InputStreamConverter converter2(istr2, encoding, encoding); + StreamCopier::copyStream(converter2, ostr2); + assert (ostr2.str() == "foo bar"); + assert (converter2.errors() == 0); + + std::istringstream istr3("x"); + std::ostringstream ostr3; + InputStreamConverter converter3(istr3, encoding, encoding); + StreamCopier::copyStream(converter3, ostr3); + assert (ostr3.str() == "x"); + assert (converter3.errors() == 0); +} + + +void StreamConverterTest::testIdentityASCIIOut() +{ + ASCIIEncoding encoding; + + std::ostringstream ostr1; + OutputStreamConverter converter1(ostr1, encoding, encoding); + converter1 << ""; + assert (ostr1.str() == ""); + assert (converter1.errors() == 0); + + std::ostringstream ostr2; + OutputStreamConverter converter2(ostr2, encoding, encoding); + converter2 << "foo bar"; + assert (ostr2.str() == "foo bar"); + assert (converter2.errors() == 0); + + std::ostringstream ostr3; + OutputStreamConverter converter3(ostr3, encoding, encoding); + converter3 << "x"; + assert (ostr3.str() == "x"); + assert (converter3.errors() == 0); +} + + +void StreamConverterTest::testIdentityUTF8In() +{ + UTF8Encoding encoding; + + std::istringstream istr1(""); + std::ostringstream ostr1; + InputStreamConverter converter1(istr1, encoding, encoding); + StreamCopier::copyStream(converter1, ostr1); + assert (ostr1.str() == ""); + assert (converter1.errors() == 0); + + std::istringstream istr2("foo bar"); + std::ostringstream ostr2; + InputStreamConverter converter2(istr2, encoding, encoding); + StreamCopier::copyStream(converter2, ostr2); + assert (ostr2.str() == "foo bar"); + assert (converter2.errors() == 0); + + std::istringstream istr3("x"); + std::ostringstream ostr3; + InputStreamConverter converter3(istr3, encoding, encoding); + StreamCopier::copyStream(converter3, ostr3); + assert (ostr3.str() == "x"); + assert (converter3.errors() == 0); + + const unsigned char greek[] = {0x20, 0xce, 0xba, 0xe1, 0xbd, 0xb9, 0xcf, 0x83, 0xce, 0xbc, 0xce, 0xb5, 0x20, 0x00}; + std::string text((const char*) greek); + + std::istringstream istr4(text); + std::ostringstream ostr4; + InputStreamConverter converter4(istr4, encoding, encoding); + StreamCopier::copyStream(converter4, ostr4); + assert (ostr4.str() == text); + assert (converter4.errors() == 0); +} + + +void StreamConverterTest::testIdentityUTF8Out() +{ + UTF8Encoding encoding; + + std::ostringstream ostr1; + OutputStreamConverter converter1(ostr1, encoding, encoding); + converter1 << ""; + assert (ostr1.str() == ""); + assert (converter1.errors() == 0); + + std::ostringstream ostr2; + OutputStreamConverter converter2(ostr2, encoding, encoding); + converter2 << "foo bar"; + assert (ostr2.str() == "foo bar"); + assert (converter2.errors() == 0); + + std::ostringstream ostr3; + OutputStreamConverter converter3(ostr3, encoding, encoding); + converter3 << "x"; + assert (ostr3.str() == "x"); + assert (converter3.errors() == 0); + + const unsigned char greek[] = {0x20, 0xce, 0xba, 0xe1, 0xbd, 0xb9, 0xcf, 0x83, 0xce, 0xbc, 0xce, 0xb5, 0x20, 0x00}; + std::string text((const char*) greek); + + std::ostringstream ostr4; + OutputStreamConverter converter4(ostr4, encoding, encoding); + converter4 << text; + assert (ostr4.str() == text); + assert (converter4.errors() == 0); +} + + +void StreamConverterTest::testUTF8toASCIIIn() +{ + UTF8Encoding utf8Encoding; + ASCIIEncoding asciiEncoding; + + const unsigned char greek[] = {0x20, 0xce, 0xba, 0xe1, 0xbd, 0xb9, 0xcf, 0x83, 0xce, 0xbc, 0xce, 0xb5, 0x20, 0x41, 0x42, 0x00}; + std::string text((const char*) greek); + + std::istringstream istr1(text); + std::ostringstream ostr1; + InputStreamConverter converter1(istr1, utf8Encoding, asciiEncoding); + StreamCopier::copyStream(converter1, ostr1); + assert (ostr1.str() == " ????? AB"); + assert (converter1.errors() == 0); + + std::istringstream istr2("abcde"); + std::ostringstream ostr2; + InputStreamConverter converter2(istr2, utf8Encoding, asciiEncoding); + StreamCopier::copyStream(converter2, ostr2); + assert (ostr2.str() == "abcde"); + assert (converter2.errors() == 0); +} + + +void StreamConverterTest::testUTF8toASCIIOut() +{ + UTF8Encoding utf8Encoding; + ASCIIEncoding asciiEncoding; + + const unsigned char greek[] = {0x20, 0xce, 0xba, 0xe1, 0xbd, 0xb9, 0xcf, 0x83, 0xce, 0xbc, 0xce, 0xb5, 0x20, 0x41, 0x42, 0x00}; + std::string text((const char*) greek); + + std::ostringstream ostr1; + OutputStreamConverter converter1(ostr1, utf8Encoding, asciiEncoding); + converter1 << text; + assert (ostr1.str() == " ????? AB"); + assert (converter1.errors() == 0); + + std::ostringstream ostr2; + OutputStreamConverter converter2(ostr2, utf8Encoding, asciiEncoding); + converter2 << "abcde"; + assert (ostr2.str() == "abcde"); + assert (converter2.errors() == 0); +} + + +void StreamConverterTest::testLatin1toUTF8In() +{ + UTF8Encoding utf8Encoding; + Latin1Encoding latin1Encoding; + + const unsigned char latin1Chars[] = {'g', 252, 'n', 't', 'e', 'r', 0}; + const unsigned char utf8Chars[] = {'g', 195, 188, 'n', 't', 'e', 'r', 0}; + std::string latin1Text((const char*) latin1Chars); + std::string utf8Text((const char*) utf8Chars); + + std::istringstream istr1(latin1Text); + std::ostringstream ostr1; + InputStreamConverter converter1(istr1, latin1Encoding, utf8Encoding); + StreamCopier::copyStream(converter1, ostr1); + assert (ostr1.str() == utf8Text); + assert (converter1.errors() == 0); +} + + +void StreamConverterTest::testLatin1toUTF8Out() +{ + UTF8Encoding utf8Encoding; + Latin1Encoding latin1Encoding; + + const unsigned char latin1Chars[] = {'g', 252, 'n', 't', 'e', 'r', 0}; + const unsigned char utf8Chars[] = {'g', 195, 188, 'n', 't', 'e', 'r', 0}; + std::string latin1Text((const char*) latin1Chars); + std::string utf8Text((const char*) utf8Chars); + + std::ostringstream ostr1; + OutputStreamConverter converter1(ostr1, latin1Encoding, utf8Encoding); + converter1 << latin1Text; + assert (ostr1.str() == utf8Text); + assert (converter1.errors() == 0); +} + + +void StreamConverterTest::testErrorsIn() +{ + UTF8Encoding utf8Encoding; + Latin1Encoding latin1Encoding; + + const unsigned char badChars[] = {'a', 'b', 255, 'c', 254, 0}; + std::string badText((const char*) badChars); + + std::istringstream istr1(badText); + std::ostringstream ostr1; + InputStreamConverter converter1(istr1, utf8Encoding, latin1Encoding); + StreamCopier::copyStream(converter1, ostr1); + assert (converter1.errors() == 2); +} + + +void StreamConverterTest::testErrorsOut() +{ + UTF8Encoding utf8Encoding; + Latin1Encoding latin1Encoding; + + const unsigned char badChars[] = {'a', 'b', 255, 'c', 254, 0}; + std::string badText((const char*) badChars); + + std::ostringstream ostr1; + OutputStreamConverter converter1(ostr1, utf8Encoding, latin1Encoding); + converter1 << badText; + assert (converter1.errors() == 1); +} + + +void StreamConverterTest::setUp() +{ +} + + +void StreamConverterTest::tearDown() +{ +} + + +CppUnit::Test* StreamConverterTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("StreamConverterTest"); + + CppUnit_addTest(pSuite, StreamConverterTest, testIdentityASCIIIn); + CppUnit_addTest(pSuite, StreamConverterTest, testIdentityASCIIOut); + CppUnit_addTest(pSuite, StreamConverterTest, testIdentityUTF8In); + CppUnit_addTest(pSuite, StreamConverterTest, testIdentityUTF8Out); + CppUnit_addTest(pSuite, StreamConverterTest, testUTF8toASCIIIn); + CppUnit_addTest(pSuite, StreamConverterTest, testUTF8toASCIIOut); + CppUnit_addTest(pSuite, StreamConverterTest, testLatin1toUTF8In); + CppUnit_addTest(pSuite, StreamConverterTest, testLatin1toUTF8Out); + CppUnit_addTest(pSuite, StreamConverterTest, testErrorsIn); + CppUnit_addTest(pSuite, StreamConverterTest, testErrorsOut); + + return pSuite; +} diff --git a/Foundation/testsuite/src/StreamConverterTest.h b/Foundation/testsuite/src/StreamConverterTest.h index 67a4a7f1b..38dacdf56 100644 --- a/Foundation/testsuite/src/StreamConverterTest.h +++ b/Foundation/testsuite/src/StreamConverterTest.h @@ -1,69 +1,69 @@ -// -// StreamConverterTest.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/StreamConverterTest.h#1 $ -// -// Definition of the StreamConverterTest class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 StreamConverterTest_INCLUDED -#define StreamConverterTest_INCLUDED - - -#include "Poco/Foundation.h" -#include "CppUnit/TestCase.h" - - -class StreamConverterTest: public CppUnit::TestCase -{ -public: - StreamConverterTest(const std::string& name); - ~StreamConverterTest(); - - void testIdentityASCIIIn(); - void testIdentityASCIIOut(); - void testIdentityUTF8In(); - void testIdentityUTF8Out(); - void testUTF8toASCIIIn(); - void testUTF8toASCIIOut(); - void testLatin1toUTF8In(); - void testLatin1toUTF8Out(); - void testErrorsIn(); - void testErrorsOut(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // StreamConverterTest_INCLUDED +// +// StreamConverterTest.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/StreamConverterTest.h#1 $ +// +// Definition of the StreamConverterTest class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 StreamConverterTest_INCLUDED +#define StreamConverterTest_INCLUDED + + +#include "Poco/Foundation.h" +#include "CppUnit/TestCase.h" + + +class StreamConverterTest: public CppUnit::TestCase +{ +public: + StreamConverterTest(const std::string& name); + ~StreamConverterTest(); + + void testIdentityASCIIIn(); + void testIdentityASCIIOut(); + void testIdentityUTF8In(); + void testIdentityUTF8Out(); + void testUTF8toASCIIIn(); + void testUTF8toASCIIOut(); + void testLatin1toUTF8In(); + void testLatin1toUTF8Out(); + void testErrorsIn(); + void testErrorsOut(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // StreamConverterTest_INCLUDED diff --git a/Foundation/testsuite/src/StreamCopierTest.cpp b/Foundation/testsuite/src/StreamCopierTest.cpp index 9cd546787..58588d759 100644 --- a/Foundation/testsuite/src/StreamCopierTest.cpp +++ b/Foundation/testsuite/src/StreamCopierTest.cpp @@ -1,130 +1,130 @@ -// -// StreamCopierTest.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/StreamCopierTest.cpp#1 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "StreamCopierTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/StreamCopier.h" -#include - - -using Poco::StreamCopier; - - -StreamCopierTest::StreamCopierTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -StreamCopierTest::~StreamCopierTest() -{ -} - - -void StreamCopierTest::testBufferedCopy() -{ - { - std::string src; - for (int i = 0; i < 255; ++i) src += char(i); - std::istringstream istr(src); - std::ostringstream ostr; - StreamCopier::copyStream(istr, ostr); - assert (ostr.str() == src); - } - { - std::string src; - for (int i = 0; i < 512; ++i) src += char(i % 256); - std::istringstream istr(src); - std::ostringstream ostr; - StreamCopier::copyStream(istr, ostr, 100); - assert (ostr.str() == src); - } - { - std::string src; - for (int i = 0; i < 512; ++i) src += char(i % 256); - std::istringstream istr(src); - std::ostringstream ostr; - StreamCopier::copyStream(istr, ostr, 128); - assert (ostr.str() == src); - } - { - std::string src; - for (int i = 0; i < 512; ++i) src += char(i % 256); - std::istringstream istr(src); - std::ostringstream ostr; - StreamCopier::copyStream(istr, ostr, 512); - assert (ostr.str() == src); - } -} - - -void StreamCopierTest::testUnbufferedCopy() -{ - std::string src; - for (int i = 0; i < 255; ++i) src += char(i); - std::istringstream istr(src); - std::ostringstream ostr; - StreamCopier::copyStreamUnbuffered(istr, ostr); - assert (ostr.str() == src); -} - - -void StreamCopierTest::testCopyToString() -{ - std::string src; - for (int i = 0; i < 512; ++i) src += char(i % 256); - std::istringstream istr(src); - std::string dest; - StreamCopier::copyToString(istr, dest, 100); - assert (src == dest); -} - - -void StreamCopierTest::setUp() -{ -} - - -void StreamCopierTest::tearDown() -{ -} - - -CppUnit::Test* StreamCopierTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("StreamCopierTest"); - - CppUnit_addTest(pSuite, StreamCopierTest, testBufferedCopy); - CppUnit_addTest(pSuite, StreamCopierTest, testUnbufferedCopy); - - return pSuite; -} +// +// StreamCopierTest.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/StreamCopierTest.cpp#1 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "StreamCopierTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/StreamCopier.h" +#include + + +using Poco::StreamCopier; + + +StreamCopierTest::StreamCopierTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +StreamCopierTest::~StreamCopierTest() +{ +} + + +void StreamCopierTest::testBufferedCopy() +{ + { + std::string src; + for (int i = 0; i < 255; ++i) src += char(i); + std::istringstream istr(src); + std::ostringstream ostr; + StreamCopier::copyStream(istr, ostr); + assert (ostr.str() == src); + } + { + std::string src; + for (int i = 0; i < 512; ++i) src += char(i % 256); + std::istringstream istr(src); + std::ostringstream ostr; + StreamCopier::copyStream(istr, ostr, 100); + assert (ostr.str() == src); + } + { + std::string src; + for (int i = 0; i < 512; ++i) src += char(i % 256); + std::istringstream istr(src); + std::ostringstream ostr; + StreamCopier::copyStream(istr, ostr, 128); + assert (ostr.str() == src); + } + { + std::string src; + for (int i = 0; i < 512; ++i) src += char(i % 256); + std::istringstream istr(src); + std::ostringstream ostr; + StreamCopier::copyStream(istr, ostr, 512); + assert (ostr.str() == src); + } +} + + +void StreamCopierTest::testUnbufferedCopy() +{ + std::string src; + for (int i = 0; i < 255; ++i) src += char(i); + std::istringstream istr(src); + std::ostringstream ostr; + StreamCopier::copyStreamUnbuffered(istr, ostr); + assert (ostr.str() == src); +} + + +void StreamCopierTest::testCopyToString() +{ + std::string src; + for (int i = 0; i < 512; ++i) src += char(i % 256); + std::istringstream istr(src); + std::string dest; + StreamCopier::copyToString(istr, dest, 100); + assert (src == dest); +} + + +void StreamCopierTest::setUp() +{ +} + + +void StreamCopierTest::tearDown() +{ +} + + +CppUnit::Test* StreamCopierTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("StreamCopierTest"); + + CppUnit_addTest(pSuite, StreamCopierTest, testBufferedCopy); + CppUnit_addTest(pSuite, StreamCopierTest, testUnbufferedCopy); + + return pSuite; +} diff --git a/Foundation/testsuite/src/StreamCopierTest.h b/Foundation/testsuite/src/StreamCopierTest.h index 69ac4ca07..f37a2afe1 100644 --- a/Foundation/testsuite/src/StreamCopierTest.h +++ b/Foundation/testsuite/src/StreamCopierTest.h @@ -1,62 +1,62 @@ -// -// StreamCopierTest.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/StreamCopierTest.h#1 $ -// -// Definition of the StreamCopierTest class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 StreamCopierTest_INCLUDED -#define StreamCopierTest_INCLUDED - - -#include "Poco/Foundation.h" -#include "CppUnit/TestCase.h" - - -class StreamCopierTest: public CppUnit::TestCase -{ -public: - StreamCopierTest(const std::string& name); - ~StreamCopierTest(); - - void testBufferedCopy(); - void testUnbufferedCopy(); - void testCopyToString(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // StreamCopierTest_INCLUDED +// +// StreamCopierTest.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/StreamCopierTest.h#1 $ +// +// Definition of the StreamCopierTest class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 StreamCopierTest_INCLUDED +#define StreamCopierTest_INCLUDED + + +#include "Poco/Foundation.h" +#include "CppUnit/TestCase.h" + + +class StreamCopierTest: public CppUnit::TestCase +{ +public: + StreamCopierTest(const std::string& name); + ~StreamCopierTest(); + + void testBufferedCopy(); + void testUnbufferedCopy(); + void testCopyToString(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // StreamCopierTest_INCLUDED diff --git a/Foundation/testsuite/src/StreamTokenizerTest.cpp b/Foundation/testsuite/src/StreamTokenizerTest.cpp index a79b5cdd2..9f9829b73 100644 --- a/Foundation/testsuite/src/StreamTokenizerTest.cpp +++ b/Foundation/testsuite/src/StreamTokenizerTest.cpp @@ -1,310 +1,310 @@ -// -// StreamTokenizerTest.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/StreamTokenizerTest.cpp#1 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "StreamTokenizerTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/StreamTokenizer.h" -#include "Poco/Token.h" -#include -#include - - -using Poco::StreamTokenizer; -using Poco::Token; -using Poco::InvalidToken; -using Poco::EOFToken; -using Poco::WhitespaceToken; - - -class IdentifierToken: public Token -{ -public: - IdentifierToken() - { - } - - ~IdentifierToken() - { - } - - Class tokenClass() const - { - return Token::IDENTIFIER_TOKEN; - } - - bool start(char c, std::istream& istr) - { - if (isalpha(c)) - { - _value = c; - return true; - } - else return false; - } - - void finish(std::istream& istr) - { - int c = istr.peek(); - while (isalnum(c)) - { - istr.get(); - _value += c; - c = istr.peek(); - } - } -}; - - -class IntLiteralToken: public Token -{ -public: - IntLiteralToken() - { - } - - ~IntLiteralToken() - { - } - - Class tokenClass() const - { - return Token::INTEGER_LITERAL_TOKEN; - } - - bool start(char c, std::istream& istr) - { - if (isdigit(c)) - { - _value = c; - return true; - } - else return false; - } - - void finish(std::istream& istr) - { - int c = istr.peek(); - while (isdigit(c)) - { - istr.get(); - _value += c; - c = istr.peek(); - } - } -}; - - -StreamTokenizerTest::StreamTokenizerTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -StreamTokenizerTest::~StreamTokenizerTest() -{ -} - - -void StreamTokenizerTest::testTokenizer1() -{ - std::string data = ""; - std::istringstream istr(data); - StreamTokenizer tokenizer(istr); - tokenizer.addToken(new WhitespaceToken()); - tokenizer.addToken(new IdentifierToken()); - tokenizer.addToken(new IntLiteralToken()); - - const Token* next = tokenizer.next(); - assert (next->tokenClass() == Token::EOF_TOKEN); -} - - -void StreamTokenizerTest::testTokenizer2() -{ - std::string data = "foo"; - std::istringstream istr(data); - StreamTokenizer tokenizer(istr); - tokenizer.addToken(new WhitespaceToken()); - tokenizer.addToken(new IdentifierToken()); - tokenizer.addToken(new IntLiteralToken()); - - const Token* next = tokenizer.next(); - assert (next->tokenClass() == Token::IDENTIFIER_TOKEN); - assert (next->tokenString() == "foo"); - - next = tokenizer.next(); - assert (next->tokenClass() == Token::EOF_TOKEN); -} - - -void StreamTokenizerTest::testTokenizer3() -{ - std::string data = "foo bar"; - std::istringstream istr(data); - StreamTokenizer tokenizer(istr); - tokenizer.addToken(new WhitespaceToken()); - tokenizer.addToken(new IdentifierToken()); - tokenizer.addToken(new IntLiteralToken()); - - const Token* next = tokenizer.next(); - assert (next->tokenClass() == Token::IDENTIFIER_TOKEN); - assert (next->tokenString() == "foo"); - - next = tokenizer.next(); - assert (next->tokenClass() == Token::IDENTIFIER_TOKEN); - assert (next->tokenString() == "bar"); - - next = tokenizer.next(); - assert (next->tokenClass() == Token::EOF_TOKEN); -} - - -void StreamTokenizerTest::testTokenizer4() -{ - std::string data = "foo 123"; - std::istringstream istr(data); - StreamTokenizer tokenizer(istr); - tokenizer.addToken(new WhitespaceToken()); - tokenizer.addToken(new IdentifierToken()); - tokenizer.addToken(new IntLiteralToken()); - - const Token* next = tokenizer.next(); - assert (next->tokenClass() == Token::IDENTIFIER_TOKEN); - assert (next->tokenString() == "foo"); - - next = tokenizer.next(); - assert (next->tokenClass() == Token::INTEGER_LITERAL_TOKEN); - assert (next->asInteger() == 123); - - next = tokenizer.next(); - assert (next->tokenClass() == Token::EOF_TOKEN); -} - - -void StreamTokenizerTest::testTokenizer5() -{ - std::string data = "foo # 123"; - std::istringstream istr(data); - StreamTokenizer tokenizer(istr); - tokenizer.addToken(new WhitespaceToken()); - tokenizer.addToken(new IdentifierToken()); - tokenizer.addToken(new IntLiteralToken()); - - const Token* next = tokenizer.next(); - assert (next->tokenClass() == Token::IDENTIFIER_TOKEN); - assert (next->tokenString() == "foo"); - - next = tokenizer.next(); - assert (next->tokenClass() == Token::INVALID_TOKEN); - assert (next->tokenString() == "#"); - - next = tokenizer.next(); - assert (next->tokenClass() == Token::INTEGER_LITERAL_TOKEN); - assert (next->asInteger() == 123); - - next = tokenizer.next(); - assert (next->tokenClass() == Token::EOF_TOKEN); -} - - -void StreamTokenizerTest::testTokenizer6() -{ - std::string data = "foo 123 #"; - std::istringstream istr(data); - StreamTokenizer tokenizer(istr); - tokenizer.addToken(new WhitespaceToken()); - tokenizer.addToken(new IdentifierToken()); - tokenizer.addToken(new IntLiteralToken()); - - const Token* next = tokenizer.next(); - assert (next->tokenClass() == Token::IDENTIFIER_TOKEN); - assert (next->tokenString() == "foo"); - - next = tokenizer.next(); - assert (next->tokenClass() == Token::INTEGER_LITERAL_TOKEN); - assert (next->asInteger() == 123); - - next = tokenizer.next(); - assert (next->tokenClass() == Token::INVALID_TOKEN); - assert (next->tokenString() == "#"); - - next = tokenizer.next(); - assert (next->tokenClass() == Token::EOF_TOKEN); -} - - -void StreamTokenizerTest::testTokenizer7() -{ - std::string data = " foo 123 "; - std::istringstream istr(data); - StreamTokenizer tokenizer(istr); - tokenizer.addToken(new WhitespaceToken()); - tokenizer.addToken(new IdentifierToken()); - tokenizer.addToken(new IntLiteralToken()); - - const Token* next = tokenizer.next(); - assert (next->tokenClass() == Token::IDENTIFIER_TOKEN); - assert (next->tokenString() == "foo"); - - next = tokenizer.next(); - assert (next->tokenClass() == Token::INTEGER_LITERAL_TOKEN); - assert (next->asInteger() == 123); - - next = tokenizer.next(); - assert (next->tokenClass() == Token::EOF_TOKEN); -} - - -void StreamTokenizerTest::setUp() -{ -} - - -void StreamTokenizerTest::tearDown() -{ -} - - -CppUnit::Test* StreamTokenizerTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("StreamTokenizerTest"); - - CppUnit_addTest(pSuite, StreamTokenizerTest, testTokenizer1); - CppUnit_addTest(pSuite, StreamTokenizerTest, testTokenizer2); - CppUnit_addTest(pSuite, StreamTokenizerTest, testTokenizer3); - CppUnit_addTest(pSuite, StreamTokenizerTest, testTokenizer4); - CppUnit_addTest(pSuite, StreamTokenizerTest, testTokenizer5); - CppUnit_addTest(pSuite, StreamTokenizerTest, testTokenizer6); - CppUnit_addTest(pSuite, StreamTokenizerTest, testTokenizer7); - - return pSuite; -} +// +// StreamTokenizerTest.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/StreamTokenizerTest.cpp#1 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "StreamTokenizerTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/StreamTokenizer.h" +#include "Poco/Token.h" +#include +#include + + +using Poco::StreamTokenizer; +using Poco::Token; +using Poco::InvalidToken; +using Poco::EOFToken; +using Poco::WhitespaceToken; + + +class IdentifierToken: public Token +{ +public: + IdentifierToken() + { + } + + ~IdentifierToken() + { + } + + Class tokenClass() const + { + return Token::IDENTIFIER_TOKEN; + } + + bool start(char c, std::istream& istr) + { + if (isalpha(c)) + { + _value = c; + return true; + } + else return false; + } + + void finish(std::istream& istr) + { + int c = istr.peek(); + while (isalnum(c)) + { + istr.get(); + _value += c; + c = istr.peek(); + } + } +}; + + +class IntLiteralToken: public Token +{ +public: + IntLiteralToken() + { + } + + ~IntLiteralToken() + { + } + + Class tokenClass() const + { + return Token::INTEGER_LITERAL_TOKEN; + } + + bool start(char c, std::istream& istr) + { + if (isdigit(c)) + { + _value = c; + return true; + } + else return false; + } + + void finish(std::istream& istr) + { + int c = istr.peek(); + while (isdigit(c)) + { + istr.get(); + _value += c; + c = istr.peek(); + } + } +}; + + +StreamTokenizerTest::StreamTokenizerTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +StreamTokenizerTest::~StreamTokenizerTest() +{ +} + + +void StreamTokenizerTest::testTokenizer1() +{ + std::string data = ""; + std::istringstream istr(data); + StreamTokenizer tokenizer(istr); + tokenizer.addToken(new WhitespaceToken()); + tokenizer.addToken(new IdentifierToken()); + tokenizer.addToken(new IntLiteralToken()); + + const Token* next = tokenizer.next(); + assert (next->tokenClass() == Token::EOF_TOKEN); +} + + +void StreamTokenizerTest::testTokenizer2() +{ + std::string data = "foo"; + std::istringstream istr(data); + StreamTokenizer tokenizer(istr); + tokenizer.addToken(new WhitespaceToken()); + tokenizer.addToken(new IdentifierToken()); + tokenizer.addToken(new IntLiteralToken()); + + const Token* next = tokenizer.next(); + assert (next->tokenClass() == Token::IDENTIFIER_TOKEN); + assert (next->tokenString() == "foo"); + + next = tokenizer.next(); + assert (next->tokenClass() == Token::EOF_TOKEN); +} + + +void StreamTokenizerTest::testTokenizer3() +{ + std::string data = "foo bar"; + std::istringstream istr(data); + StreamTokenizer tokenizer(istr); + tokenizer.addToken(new WhitespaceToken()); + tokenizer.addToken(new IdentifierToken()); + tokenizer.addToken(new IntLiteralToken()); + + const Token* next = tokenizer.next(); + assert (next->tokenClass() == Token::IDENTIFIER_TOKEN); + assert (next->tokenString() == "foo"); + + next = tokenizer.next(); + assert (next->tokenClass() == Token::IDENTIFIER_TOKEN); + assert (next->tokenString() == "bar"); + + next = tokenizer.next(); + assert (next->tokenClass() == Token::EOF_TOKEN); +} + + +void StreamTokenizerTest::testTokenizer4() +{ + std::string data = "foo 123"; + std::istringstream istr(data); + StreamTokenizer tokenizer(istr); + tokenizer.addToken(new WhitespaceToken()); + tokenizer.addToken(new IdentifierToken()); + tokenizer.addToken(new IntLiteralToken()); + + const Token* next = tokenizer.next(); + assert (next->tokenClass() == Token::IDENTIFIER_TOKEN); + assert (next->tokenString() == "foo"); + + next = tokenizer.next(); + assert (next->tokenClass() == Token::INTEGER_LITERAL_TOKEN); + assert (next->asInteger() == 123); + + next = tokenizer.next(); + assert (next->tokenClass() == Token::EOF_TOKEN); +} + + +void StreamTokenizerTest::testTokenizer5() +{ + std::string data = "foo # 123"; + std::istringstream istr(data); + StreamTokenizer tokenizer(istr); + tokenizer.addToken(new WhitespaceToken()); + tokenizer.addToken(new IdentifierToken()); + tokenizer.addToken(new IntLiteralToken()); + + const Token* next = tokenizer.next(); + assert (next->tokenClass() == Token::IDENTIFIER_TOKEN); + assert (next->tokenString() == "foo"); + + next = tokenizer.next(); + assert (next->tokenClass() == Token::INVALID_TOKEN); + assert (next->tokenString() == "#"); + + next = tokenizer.next(); + assert (next->tokenClass() == Token::INTEGER_LITERAL_TOKEN); + assert (next->asInteger() == 123); + + next = tokenizer.next(); + assert (next->tokenClass() == Token::EOF_TOKEN); +} + + +void StreamTokenizerTest::testTokenizer6() +{ + std::string data = "foo 123 #"; + std::istringstream istr(data); + StreamTokenizer tokenizer(istr); + tokenizer.addToken(new WhitespaceToken()); + tokenizer.addToken(new IdentifierToken()); + tokenizer.addToken(new IntLiteralToken()); + + const Token* next = tokenizer.next(); + assert (next->tokenClass() == Token::IDENTIFIER_TOKEN); + assert (next->tokenString() == "foo"); + + next = tokenizer.next(); + assert (next->tokenClass() == Token::INTEGER_LITERAL_TOKEN); + assert (next->asInteger() == 123); + + next = tokenizer.next(); + assert (next->tokenClass() == Token::INVALID_TOKEN); + assert (next->tokenString() == "#"); + + next = tokenizer.next(); + assert (next->tokenClass() == Token::EOF_TOKEN); +} + + +void StreamTokenizerTest::testTokenizer7() +{ + std::string data = " foo 123 "; + std::istringstream istr(data); + StreamTokenizer tokenizer(istr); + tokenizer.addToken(new WhitespaceToken()); + tokenizer.addToken(new IdentifierToken()); + tokenizer.addToken(new IntLiteralToken()); + + const Token* next = tokenizer.next(); + assert (next->tokenClass() == Token::IDENTIFIER_TOKEN); + assert (next->tokenString() == "foo"); + + next = tokenizer.next(); + assert (next->tokenClass() == Token::INTEGER_LITERAL_TOKEN); + assert (next->asInteger() == 123); + + next = tokenizer.next(); + assert (next->tokenClass() == Token::EOF_TOKEN); +} + + +void StreamTokenizerTest::setUp() +{ +} + + +void StreamTokenizerTest::tearDown() +{ +} + + +CppUnit::Test* StreamTokenizerTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("StreamTokenizerTest"); + + CppUnit_addTest(pSuite, StreamTokenizerTest, testTokenizer1); + CppUnit_addTest(pSuite, StreamTokenizerTest, testTokenizer2); + CppUnit_addTest(pSuite, StreamTokenizerTest, testTokenizer3); + CppUnit_addTest(pSuite, StreamTokenizerTest, testTokenizer4); + CppUnit_addTest(pSuite, StreamTokenizerTest, testTokenizer5); + CppUnit_addTest(pSuite, StreamTokenizerTest, testTokenizer6); + CppUnit_addTest(pSuite, StreamTokenizerTest, testTokenizer7); + + return pSuite; +} diff --git a/Foundation/testsuite/src/StreamTokenizerTest.h b/Foundation/testsuite/src/StreamTokenizerTest.h index 37aafe9a4..6e1d99fc1 100644 --- a/Foundation/testsuite/src/StreamTokenizerTest.h +++ b/Foundation/testsuite/src/StreamTokenizerTest.h @@ -1,66 +1,66 @@ -// -// StreamTokenizerTest.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/StreamTokenizerTest.h#1 $ -// -// Definition of the StreamTokenizerTest class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 StreamTokenizerTest_INCLUDED -#define StreamTokenizerTest_INCLUDED - - -#include "Poco/Foundation.h" -#include "CppUnit/TestCase.h" - - -class StreamTokenizerTest: public CppUnit::TestCase -{ -public: - StreamTokenizerTest(const std::string& name); - ~StreamTokenizerTest(); - - void testTokenizer1(); - void testTokenizer2(); - void testTokenizer3(); - void testTokenizer4(); - void testTokenizer5(); - void testTokenizer6(); - void testTokenizer7(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // StreamTokenizerTest_INCLUDED +// +// StreamTokenizerTest.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/StreamTokenizerTest.h#1 $ +// +// Definition of the StreamTokenizerTest class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 StreamTokenizerTest_INCLUDED +#define StreamTokenizerTest_INCLUDED + + +#include "Poco/Foundation.h" +#include "CppUnit/TestCase.h" + + +class StreamTokenizerTest: public CppUnit::TestCase +{ +public: + StreamTokenizerTest(const std::string& name); + ~StreamTokenizerTest(); + + void testTokenizer1(); + void testTokenizer2(); + void testTokenizer3(); + void testTokenizer4(); + void testTokenizer5(); + void testTokenizer6(); + void testTokenizer7(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // StreamTokenizerTest_INCLUDED diff --git a/Foundation/testsuite/src/StreamsTestSuite.cpp b/Foundation/testsuite/src/StreamsTestSuite.cpp index 4e321f245..5e4fba911 100644 --- a/Foundation/testsuite/src/StreamsTestSuite.cpp +++ b/Foundation/testsuite/src/StreamsTestSuite.cpp @@ -1,62 +1,62 @@ -// -// StreamsTestSuite.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/StreamsTestSuite.cpp#1 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "StreamsTestSuite.h" -#include "Base64Test.h" -#include "HexBinaryTest.h" -#include "StreamCopierTest.h" -#include "CountingStreamTest.h" -#include "NullStreamTest.h" -#include "ZLibTest.h" -#include "StreamTokenizerTest.h" -#include "BinaryReaderWriterTest.h" -#include "LineEndingConverterTest.h" -#include "TeeStreamTest.h" - - -CppUnit::Test* StreamsTestSuite::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("StreamsTestSuite"); - - pSuite->addTest(Base64Test::suite()); - pSuite->addTest(HexBinaryTest::suite()); - pSuite->addTest(StreamCopierTest::suite()); - pSuite->addTest(CountingStreamTest::suite()); - pSuite->addTest(NullStreamTest::suite()); - pSuite->addTest(ZLibTest::suite()); - pSuite->addTest(StreamTokenizerTest::suite()); - pSuite->addTest(BinaryReaderWriterTest::suite()); - pSuite->addTest(LineEndingConverterTest::suite()); - pSuite->addTest(TeeStreamTest::suite()); - - return pSuite; -} +// +// StreamsTestSuite.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/StreamsTestSuite.cpp#1 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "StreamsTestSuite.h" +#include "Base64Test.h" +#include "HexBinaryTest.h" +#include "StreamCopierTest.h" +#include "CountingStreamTest.h" +#include "NullStreamTest.h" +#include "ZLibTest.h" +#include "StreamTokenizerTest.h" +#include "BinaryReaderWriterTest.h" +#include "LineEndingConverterTest.h" +#include "TeeStreamTest.h" + + +CppUnit::Test* StreamsTestSuite::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("StreamsTestSuite"); + + pSuite->addTest(Base64Test::suite()); + pSuite->addTest(HexBinaryTest::suite()); + pSuite->addTest(StreamCopierTest::suite()); + pSuite->addTest(CountingStreamTest::suite()); + pSuite->addTest(NullStreamTest::suite()); + pSuite->addTest(ZLibTest::suite()); + pSuite->addTest(StreamTokenizerTest::suite()); + pSuite->addTest(BinaryReaderWriterTest::suite()); + pSuite->addTest(LineEndingConverterTest::suite()); + pSuite->addTest(TeeStreamTest::suite()); + + return pSuite; +} diff --git a/Foundation/testsuite/src/StreamsTestSuite.h b/Foundation/testsuite/src/StreamsTestSuite.h index 48ed1809f..4801135e6 100644 --- a/Foundation/testsuite/src/StreamsTestSuite.h +++ b/Foundation/testsuite/src/StreamsTestSuite.h @@ -1,49 +1,49 @@ -// -// StreamsTestSuite.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/StreamsTestSuite.h#1 $ -// -// Definition of the StreamsTestSuite class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 StreamsTestSuite_INCLUDED -#define StreamsTestSuite_INCLUDED - - -#include "CppUnit/TestSuite.h" - - -class StreamsTestSuite -{ -public: - static CppUnit::Test* suite(); -}; - - -#endif // StreamsTestSuite_INCLUDED +// +// StreamsTestSuite.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/StreamsTestSuite.h#1 $ +// +// Definition of the StreamsTestSuite class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 StreamsTestSuite_INCLUDED +#define StreamsTestSuite_INCLUDED + + +#include "CppUnit/TestSuite.h" + + +class StreamsTestSuite +{ +public: + static CppUnit::Test* suite(); +}; + + +#endif // StreamsTestSuite_INCLUDED diff --git a/Foundation/testsuite/src/StringTest.cpp b/Foundation/testsuite/src/StringTest.cpp index d67140412..4c61597c7 100644 --- a/Foundation/testsuite/src/StringTest.cpp +++ b/Foundation/testsuite/src/StringTest.cpp @@ -1,326 +1,326 @@ -// -// StringTest.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/StringTest.cpp#1 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "StringTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/String.h" - - -using Poco::trimLeft; -using Poco::trimLeftInPlace; -using Poco::trimRight; -using Poco::trimRightInPlace; -using Poco::trim; -using Poco::trimInPlace; -using Poco::toUpper; -using Poco::toUpperInPlace; -using Poco::toLower; -using Poco::toLowerInPlace; -using Poco::icompare; -using Poco::translate; -using Poco::translateInPlace; -using Poco::cat; - - -StringTest::StringTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -StringTest::~StringTest() -{ -} - - -void StringTest::testTrimLeft() -{ - { - std::string s = "abc"; - assert (trimLeft(s) == "abc"); - } - std::string s = " abc "; - assert (trimLeft(s) == "abc "); - { - std::string s = " ab c "; - assert (trimLeft(s) == "ab c "); - } -} - - -void StringTest::testTrimLeftInPlace() -{ - { - std::string s = "abc"; - assert (trimLeftInPlace(s) == "abc"); - } - { - std::string s = " abc "; - assert (trimLeftInPlace(s) == "abc "); - } - { - std::string s = " ab c "; - assert (trimLeftInPlace(s) == "ab c "); - } -} - - -void StringTest::testTrimRight() -{ - { - std::string s = "abc"; - assert (trimRight(s) == "abc"); - } - { - std::string s = " abc "; - assert (trimRight(s) == " abc"); - } - { - std::string s = " ab c "; - assert (trimRight(s) == " ab c"); - } -} - - -void StringTest::testTrimRightInPlace() -{ - { - std::string s = "abc"; - assert (trimRightInPlace(s) == "abc"); - } - { - std::string s = " abc "; - assert (trimRightInPlace(s) == " abc"); - } - { - std::string s = " ab c "; - assert (trimRightInPlace(s) == " ab c"); - } -} - - -void StringTest::testTrim() -{ - { - std::string s = "abc"; - assert (trim(s) == "abc"); - } - { - std::string s = "abc "; - assert (trim(s) == "abc"); - } - { - std::string s = " ab c "; - assert (trim(s) == "ab c"); - } -} - - -void StringTest::testTrimInPlace() -{ - { - std::string s = "abc"; - assert (trimInPlace(s) == "abc"); - } - { - std::string s = " abc "; - assert (trimInPlace(s) == "abc"); - } - { - std::string s = " ab c "; - assert (trimInPlace(s) == "ab c"); - } -} - - -void StringTest::testToUpper() -{ - { - std::string s = "abc"; - assert (toUpper(s) == "ABC"); - } - { - std::string s = "Abc"; - assert (toUpper(s) == "ABC"); - } - { - std::string s = "abc"; - assert (toUpperInPlace(s) == "ABC"); - } - { - std::string s = "Abc"; - assert (toUpperInPlace(s) == "ABC"); - } -} - - -void StringTest::testToLower() -{ - { - std::string s = "ABC"; - assert (toLower(s) == "abc"); - } - { - std::string s = "aBC"; - assert (toLower(s) == "abc"); - } - { - std::string s = "ABC"; - assert (toLowerInPlace(s) == "abc"); - } - { - std::string s = "aBC"; - assert (toLowerInPlace(s) == "abc"); - } -} - - -void StringTest::testIcompare() -{ - std::string s1 = "AAA"; - std::string s2 = "aaa"; - std::string s3 = "bbb"; - std::string s4 = "cCcCc"; - std::string s5; - assert (icompare(s1, s2) == 0); - assert (icompare(s1, s3) < 0); - assert (icompare(s1, s4) < 0); - assert (icompare(s3, s1) > 0); - assert (icompare(s4, s2) > 0); - assert (icompare(s2, s4) < 0); - assert (icompare(s1, s5) > 0); - assert (icompare(s5, s4) < 0); - - std::string ss1 = "xxAAAzz"; - std::string ss2 = "YaaaX"; - std::string ss3 = "YbbbX"; - assert (icompare(ss1, 2, 3, ss2, 1, 3) == 0); - assert (icompare(ss1, 2, 3, ss3, 1, 3) < 0); - assert (icompare(ss1, 2, 3, ss2, 1) == 0); - assert (icompare(ss1, 2, 3, ss3, 1) < 0); - assert (icompare(ss1, 2, 2, ss2, 1, 3) < 0); - assert (icompare(ss1, 2, 2, ss2, 1, 2) == 0); - assert (icompare(ss3, 1, 3, ss1, 2, 3) > 0); - - assert (icompare(s1, s2.c_str()) == 0); - assert (icompare(s1, s3.c_str()) < 0); - assert (icompare(s1, s4.c_str()) < 0); - assert (icompare(s3, s1.c_str()) > 0); - assert (icompare(s4, s2.c_str()) > 0); - assert (icompare(s2, s4.c_str()) < 0); - assert (icompare(s1, s5.c_str()) > 0); - assert (icompare(s5, s4.c_str()) < 0); - - assert (icompare(ss1, 2, 3, "aaa") == 0); - assert (icompare(ss1, 2, 2, "aaa") < 0); - assert (icompare(ss1, 2, 3, "AAA") == 0); - assert (icompare(ss1, 2, 2, "bb") < 0); - - assert (icompare(ss1, 2, "aaa") > 0); -} - - -void StringTest::testTranslate() -{ - std::string s = "aabbccdd"; - assert (translate(s, "abc", "ABC") == "AABBCCdd"); - assert (translate(s, "abc", "AB") == "AABBdd"); - assert (translate(s, "abc", "") == "dd"); - assert (translate(s, "cba", "CB") == "BBCCdd"); - assert (translate(s, "", "CB") == "aabbccdd"); -} - - -void StringTest::testTranslateInPlace() -{ - std::string s = "aabbccdd"; - translateInPlace(s, "abc", "ABC"); - assert (s == "AABBCCdd"); -} - - -void StringTest::testCat() -{ - std::string s1("one"); - std::string s2("two"); - std::string s3("three"); - std::string s4("four"); - std::string s5("five"); - std::string s6("six"); - - assert (cat(s1, s2) == "onetwo"); - assert (cat(s1, s2, s3) == "onetwothree"); - assert (cat(s1, s2, s3, s4) == "onetwothreefour"); - assert (cat(s1, s2, s3, s4, s5) == "onetwothreefourfive"); - assert (cat(s1, s2, s3, s4, s5, s6) == "onetwothreefourfivesix"); - - std::vector vec; - assert (cat(std::string(), vec.begin(), vec.end()) == ""); - assert (cat(std::string(","), vec.begin(), vec.end()) == ""); - vec.push_back(s1); - assert (cat(std::string(","), vec.begin(), vec.end()) == "one"); - vec.push_back(s2); - assert (cat(std::string(","), vec.begin(), vec.end()) == "one,two"); - vec.push_back(s3); - assert (cat(std::string(","), vec.begin(), vec.end()) == "one,two,three"); -} - - -void StringTest::setUp() -{ -} - - -void StringTest::tearDown() -{ -} - - -CppUnit::Test* StringTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("StringTest"); - - CppUnit_addTest(pSuite, StringTest, testTrimLeft); - CppUnit_addTest(pSuite, StringTest, testTrimLeftInPlace); - CppUnit_addTest(pSuite, StringTest, testTrimRight); - CppUnit_addTest(pSuite, StringTest, testTrimInPlace); - CppUnit_addTest(pSuite, StringTest, testTrim); - CppUnit_addTest(pSuite, StringTest, testTrimRightInPlace); - CppUnit_addTest(pSuite, StringTest, testToUpper); - CppUnit_addTest(pSuite, StringTest, testToLower); - CppUnit_addTest(pSuite, StringTest, testIcompare); - CppUnit_addTest(pSuite, StringTest, testTranslate); - CppUnit_addTest(pSuite, StringTest, testTranslateInPlace); - CppUnit_addTest(pSuite, StringTest, testCat); - - return pSuite; -} +// +// StringTest.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/StringTest.cpp#1 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "StringTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/String.h" + + +using Poco::trimLeft; +using Poco::trimLeftInPlace; +using Poco::trimRight; +using Poco::trimRightInPlace; +using Poco::trim; +using Poco::trimInPlace; +using Poco::toUpper; +using Poco::toUpperInPlace; +using Poco::toLower; +using Poco::toLowerInPlace; +using Poco::icompare; +using Poco::translate; +using Poco::translateInPlace; +using Poco::cat; + + +StringTest::StringTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +StringTest::~StringTest() +{ +} + + +void StringTest::testTrimLeft() +{ + { + std::string s = "abc"; + assert (trimLeft(s) == "abc"); + } + std::string s = " abc "; + assert (trimLeft(s) == "abc "); + { + std::string s = " ab c "; + assert (trimLeft(s) == "ab c "); + } +} + + +void StringTest::testTrimLeftInPlace() +{ + { + std::string s = "abc"; + assert (trimLeftInPlace(s) == "abc"); + } + { + std::string s = " abc "; + assert (trimLeftInPlace(s) == "abc "); + } + { + std::string s = " ab c "; + assert (trimLeftInPlace(s) == "ab c "); + } +} + + +void StringTest::testTrimRight() +{ + { + std::string s = "abc"; + assert (trimRight(s) == "abc"); + } + { + std::string s = " abc "; + assert (trimRight(s) == " abc"); + } + { + std::string s = " ab c "; + assert (trimRight(s) == " ab c"); + } +} + + +void StringTest::testTrimRightInPlace() +{ + { + std::string s = "abc"; + assert (trimRightInPlace(s) == "abc"); + } + { + std::string s = " abc "; + assert (trimRightInPlace(s) == " abc"); + } + { + std::string s = " ab c "; + assert (trimRightInPlace(s) == " ab c"); + } +} + + +void StringTest::testTrim() +{ + { + std::string s = "abc"; + assert (trim(s) == "abc"); + } + { + std::string s = "abc "; + assert (trim(s) == "abc"); + } + { + std::string s = " ab c "; + assert (trim(s) == "ab c"); + } +} + + +void StringTest::testTrimInPlace() +{ + { + std::string s = "abc"; + assert (trimInPlace(s) == "abc"); + } + { + std::string s = " abc "; + assert (trimInPlace(s) == "abc"); + } + { + std::string s = " ab c "; + assert (trimInPlace(s) == "ab c"); + } +} + + +void StringTest::testToUpper() +{ + { + std::string s = "abc"; + assert (toUpper(s) == "ABC"); + } + { + std::string s = "Abc"; + assert (toUpper(s) == "ABC"); + } + { + std::string s = "abc"; + assert (toUpperInPlace(s) == "ABC"); + } + { + std::string s = "Abc"; + assert (toUpperInPlace(s) == "ABC"); + } +} + + +void StringTest::testToLower() +{ + { + std::string s = "ABC"; + assert (toLower(s) == "abc"); + } + { + std::string s = "aBC"; + assert (toLower(s) == "abc"); + } + { + std::string s = "ABC"; + assert (toLowerInPlace(s) == "abc"); + } + { + std::string s = "aBC"; + assert (toLowerInPlace(s) == "abc"); + } +} + + +void StringTest::testIcompare() +{ + std::string s1 = "AAA"; + std::string s2 = "aaa"; + std::string s3 = "bbb"; + std::string s4 = "cCcCc"; + std::string s5; + assert (icompare(s1, s2) == 0); + assert (icompare(s1, s3) < 0); + assert (icompare(s1, s4) < 0); + assert (icompare(s3, s1) > 0); + assert (icompare(s4, s2) > 0); + assert (icompare(s2, s4) < 0); + assert (icompare(s1, s5) > 0); + assert (icompare(s5, s4) < 0); + + std::string ss1 = "xxAAAzz"; + std::string ss2 = "YaaaX"; + std::string ss3 = "YbbbX"; + assert (icompare(ss1, 2, 3, ss2, 1, 3) == 0); + assert (icompare(ss1, 2, 3, ss3, 1, 3) < 0); + assert (icompare(ss1, 2, 3, ss2, 1) == 0); + assert (icompare(ss1, 2, 3, ss3, 1) < 0); + assert (icompare(ss1, 2, 2, ss2, 1, 3) < 0); + assert (icompare(ss1, 2, 2, ss2, 1, 2) == 0); + assert (icompare(ss3, 1, 3, ss1, 2, 3) > 0); + + assert (icompare(s1, s2.c_str()) == 0); + assert (icompare(s1, s3.c_str()) < 0); + assert (icompare(s1, s4.c_str()) < 0); + assert (icompare(s3, s1.c_str()) > 0); + assert (icompare(s4, s2.c_str()) > 0); + assert (icompare(s2, s4.c_str()) < 0); + assert (icompare(s1, s5.c_str()) > 0); + assert (icompare(s5, s4.c_str()) < 0); + + assert (icompare(ss1, 2, 3, "aaa") == 0); + assert (icompare(ss1, 2, 2, "aaa") < 0); + assert (icompare(ss1, 2, 3, "AAA") == 0); + assert (icompare(ss1, 2, 2, "bb") < 0); + + assert (icompare(ss1, 2, "aaa") > 0); +} + + +void StringTest::testTranslate() +{ + std::string s = "aabbccdd"; + assert (translate(s, "abc", "ABC") == "AABBCCdd"); + assert (translate(s, "abc", "AB") == "AABBdd"); + assert (translate(s, "abc", "") == "dd"); + assert (translate(s, "cba", "CB") == "BBCCdd"); + assert (translate(s, "", "CB") == "aabbccdd"); +} + + +void StringTest::testTranslateInPlace() +{ + std::string s = "aabbccdd"; + translateInPlace(s, "abc", "ABC"); + assert (s == "AABBCCdd"); +} + + +void StringTest::testCat() +{ + std::string s1("one"); + std::string s2("two"); + std::string s3("three"); + std::string s4("four"); + std::string s5("five"); + std::string s6("six"); + + assert (cat(s1, s2) == "onetwo"); + assert (cat(s1, s2, s3) == "onetwothree"); + assert (cat(s1, s2, s3, s4) == "onetwothreefour"); + assert (cat(s1, s2, s3, s4, s5) == "onetwothreefourfive"); + assert (cat(s1, s2, s3, s4, s5, s6) == "onetwothreefourfivesix"); + + std::vector vec; + assert (cat(std::string(), vec.begin(), vec.end()) == ""); + assert (cat(std::string(","), vec.begin(), vec.end()) == ""); + vec.push_back(s1); + assert (cat(std::string(","), vec.begin(), vec.end()) == "one"); + vec.push_back(s2); + assert (cat(std::string(","), vec.begin(), vec.end()) == "one,two"); + vec.push_back(s3); + assert (cat(std::string(","), vec.begin(), vec.end()) == "one,two,three"); +} + + +void StringTest::setUp() +{ +} + + +void StringTest::tearDown() +{ +} + + +CppUnit::Test* StringTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("StringTest"); + + CppUnit_addTest(pSuite, StringTest, testTrimLeft); + CppUnit_addTest(pSuite, StringTest, testTrimLeftInPlace); + CppUnit_addTest(pSuite, StringTest, testTrimRight); + CppUnit_addTest(pSuite, StringTest, testTrimInPlace); + CppUnit_addTest(pSuite, StringTest, testTrim); + CppUnit_addTest(pSuite, StringTest, testTrimRightInPlace); + CppUnit_addTest(pSuite, StringTest, testToUpper); + CppUnit_addTest(pSuite, StringTest, testToLower); + CppUnit_addTest(pSuite, StringTest, testIcompare); + CppUnit_addTest(pSuite, StringTest, testTranslate); + CppUnit_addTest(pSuite, StringTest, testTranslateInPlace); + CppUnit_addTest(pSuite, StringTest, testCat); + + return pSuite; +} diff --git a/Foundation/testsuite/src/StringTest.h b/Foundation/testsuite/src/StringTest.h index 8c732b831..29d075b41 100644 --- a/Foundation/testsuite/src/StringTest.h +++ b/Foundation/testsuite/src/StringTest.h @@ -1,71 +1,71 @@ -// -// StringTest.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/StringTest.h#1 $ -// -// Definition of the StringTest class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 StringTest_INCLUDED -#define StringTest_INCLUDED - - -#include "Poco/Foundation.h" -#include "CppUnit/TestCase.h" - - -class StringTest: public CppUnit::TestCase -{ -public: - StringTest(const std::string& name); - ~StringTest(); - - void testTrimLeft(); - void testTrimLeftInPlace(); - void testTrimRight(); - void testTrimRightInPlace(); - void testTrim(); - void testTrimInPlace(); - void testToUpper(); - void testToLower(); - void testIcompare(); - void testTranslate(); - void testTranslateInPlace(); - void testCat(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // StringTest_INCLUDED +// +// StringTest.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/StringTest.h#1 $ +// +// Definition of the StringTest class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 StringTest_INCLUDED +#define StringTest_INCLUDED + + +#include "Poco/Foundation.h" +#include "CppUnit/TestCase.h" + + +class StringTest: public CppUnit::TestCase +{ +public: + StringTest(const std::string& name); + ~StringTest(); + + void testTrimLeft(); + void testTrimLeftInPlace(); + void testTrimRight(); + void testTrimRightInPlace(); + void testTrim(); + void testTrimInPlace(); + void testToUpper(); + void testToLower(); + void testIcompare(); + void testTranslate(); + void testTranslateInPlace(); + void testCat(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // StringTest_INCLUDED diff --git a/Foundation/testsuite/src/StringTokenizerTest.cpp b/Foundation/testsuite/src/StringTokenizerTest.cpp index f40e1a2ee..f9e63be41 100644 --- a/Foundation/testsuite/src/StringTokenizerTest.cpp +++ b/Foundation/testsuite/src/StringTokenizerTest.cpp @@ -1,307 +1,307 @@ -// -// StringTokenizerTest.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/StringTokenizerTest.cpp#1 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "StringTokenizerTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/StringTokenizer.h" - - -using Poco::StringTokenizer; - - -StringTokenizerTest::StringTokenizerTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -StringTokenizerTest::~StringTokenizerTest() -{ -} - - -void StringTokenizerTest::testStringTokenizer() -{ - { - StringTokenizer st("", ""); - assert (st.begin() == st.end()); - } - { - StringTokenizer st("", "", StringTokenizer::TOK_IGNORE_EMPTY); - assert (st.begin() == st.end()); - } - { - StringTokenizer st("", "", StringTokenizer::TOK_TRIM); - assert (st.begin() == st.end()); - } - { - StringTokenizer st("", "", StringTokenizer::TOK_TRIM | StringTokenizer::TOK_IGNORE_EMPTY); - assert (st.begin() == st.end()); - } - { - StringTokenizer st("abc", ""); - StringTokenizer::Iterator it = st.begin(); - assert (it != st.end()); - assert (*it++ == "abc"); - assert (it == st.end()); - } - { - StringTokenizer st("abc ", "", StringTokenizer::TOK_TRIM); - StringTokenizer::Iterator it = st.begin(); - assert (it != st.end()); - assert (*it++ == "abc"); - assert (it == st.end()); - } - { - StringTokenizer st(" abc ", "", StringTokenizer::TOK_TRIM); - StringTokenizer::Iterator it = st.begin(); - assert (it != st.end()); - assert (*it++ == "abc"); - assert (it == st.end()); - } - { - StringTokenizer st(" abc", "", StringTokenizer::TOK_TRIM); - StringTokenizer::Iterator it = st.begin(); - assert (it != st.end()); - assert (*it++ == "abc"); - assert (it == st.end()); - } - { - StringTokenizer st("abc", "b"); - StringTokenizer::Iterator it = st.begin(); - assert (it != st.end()); - assert (*it++ == "a"); - assert (it != st.end()); - assert (*it++ == "c"); - assert (it == st.end()); - } - { - StringTokenizer st("abc", "b", StringTokenizer::TOK_TRIM | StringTokenizer::TOK_IGNORE_EMPTY); - StringTokenizer::Iterator it = st.begin(); - assert (it != st.end()); - assert (*it++ == "a"); - assert (it != st.end()); - assert (*it++ == "c"); - assert (it == st.end()); - } - { - StringTokenizer st("abc", "bc"); - StringTokenizer::Iterator it = st.begin(); - assert (it != st.end()); - assert (*it++ == "a"); - assert (it != st.end()); - assert (*it++ == ""); - assert (it == st.end()); - } - { - StringTokenizer st("abc", "bc", StringTokenizer::TOK_TRIM); - StringTokenizer::Iterator it = st.begin(); - assert (it != st.end()); - assert (*it++ == "a"); - assert (it != st.end()); - assert (*it++ == ""); - assert (it == st.end()); - } - { - StringTokenizer st("abc", "bc", StringTokenizer::TOK_IGNORE_EMPTY); - StringTokenizer::Iterator it = st.begin(); - assert (it != st.end()); - assert (*it++ == "a"); - assert (it == st.end()); - } - { - StringTokenizer st("abc", "bc", StringTokenizer::TOK_TRIM | StringTokenizer::TOK_IGNORE_EMPTY); - StringTokenizer::Iterator it = st.begin(); - assert (it != st.end()); - assert (*it++ == "a"); - assert (it == st.end()); - } - { - StringTokenizer st("abc", "bc", StringTokenizer::TOK_TRIM | StringTokenizer::TOK_IGNORE_EMPTY); - StringTokenizer::Iterator it = st.begin(); - assert (it != st.end()); - assert (*it++ == "a"); - assert (it == st.end()); - } - { - StringTokenizer st("a a,c c", ","); - StringTokenizer::Iterator it = st.begin(); - assert (it != st.end()); - assert (*it++ == "a a"); - assert (it != st.end()); - assert (*it++ == "c c"); - assert (it == st.end()); - } - { - StringTokenizer st("a a,c c", ",", StringTokenizer::TOK_TRIM | StringTokenizer::TOK_IGNORE_EMPTY); - StringTokenizer::Iterator it = st.begin(); - assert (it != st.end()); - assert (*it++ == "a a"); - assert (it != st.end()); - assert (*it++ == "c c"); - assert (it == st.end()); - } - { - StringTokenizer st(" a a , , c c ", ","); - StringTokenizer::Iterator it = st.begin(); - assert (it != st.end()); - assert (*it++ == " a a "); - assert (it != st.end()); - assert (*it++ == " "); - assert (it != st.end()); - assert (*it++ == " c c "); - assert (it == st.end()); - } - { - StringTokenizer st(" a a , , c c ", ",", StringTokenizer::TOK_TRIM); - StringTokenizer::Iterator it = st.begin(); - assert (it != st.end()); - assert (*it++ == "a a"); - assert (it != st.end()); - assert (*it++ == ""); - assert (it != st.end()); - assert (*it++ == "c c"); - assert (it == st.end()); - } - { - StringTokenizer st(" a a , , c c ", ",", StringTokenizer::TOK_TRIM | StringTokenizer::TOK_IGNORE_EMPTY); - StringTokenizer::Iterator it = st.begin(); - assert (it != st.end()); - assert (*it++ == "a a"); - assert (it != st.end()); - assert (*it++ == "c c"); - assert (it == st.end()); - } - { - StringTokenizer st("abc,def,,ghi , jk, l ", ",", StringTokenizer::TOK_TRIM | StringTokenizer::TOK_IGNORE_EMPTY); - StringTokenizer::Iterator it = st.begin(); - assert (it != st.end()); - assert (*it++ == "abc"); - assert (it != st.end()); - assert (*it++ == "def"); - assert (it != st.end()); - assert (*it++ == "ghi"); - assert (it != st.end()); - assert (*it++ == "jk"); - assert (it != st.end()); - assert (*it++ == "l"); - assert (it == st.end()); - } - { - StringTokenizer st("abc,def,,ghi // jk, l ", ",/", StringTokenizer::TOK_TRIM | StringTokenizer::TOK_IGNORE_EMPTY); - StringTokenizer::Iterator it = st.begin(); - assert (it != st.end()); - assert (*it++ == "abc"); - assert (it != st.end()); - assert (*it++ == "def"); - assert (it != st.end()); - assert (*it++ == "ghi"); - assert (it != st.end()); - assert (*it++ == "jk"); - assert (it != st.end()); - assert (*it++ == "l"); - assert (it == st.end()); - } - { - StringTokenizer st("a/bc,def,,ghi // jk, l ", ",/", StringTokenizer::TOK_TRIM | StringTokenizer::TOK_IGNORE_EMPTY); - StringTokenizer::Iterator it = st.begin(); - assert (it != st.end()); - assert (*it++ == "a"); - assert (it != st.end()); - assert (*it++ == "bc"); - assert (it != st.end()); - assert (*it++ == "def"); - assert (it != st.end()); - assert (*it++ == "ghi"); - assert (it != st.end()); - assert (*it++ == "jk"); - assert (it != st.end()); - assert (*it++ == "l"); - assert (it == st.end()); - } - { - StringTokenizer st(",ab,cd,", ","); - StringTokenizer::Iterator it = st.begin(); - assert (it != st.end()); - assert (*it++ == ""); - assert (it != st.end()); - assert (*it++ == "ab"); - assert (it != st.end()); - assert (*it++ == "cd"); - assert (it == st.end()); - } - { - StringTokenizer st(",ab,cd,", ",", StringTokenizer::TOK_IGNORE_EMPTY); - StringTokenizer::Iterator it = st.begin(); - assert (it != st.end()); - assert (*it++ == "ab"); - assert (it != st.end()); - assert (*it++ == "cd"); - assert (it == st.end()); - } - { - StringTokenizer st(" , ab , cd , ", ",", StringTokenizer::TOK_TRIM | StringTokenizer::TOK_IGNORE_EMPTY); - StringTokenizer::Iterator it = st.begin(); - assert (it != st.end()); - assert (*it++ == "ab"); - assert (it != st.end()); - assert (*it++ == "cd"); - assert (it == st.end()); - } - { - StringTokenizer st("1 : 2 , : 3 ", ":,", StringTokenizer::TOK_TRIM | StringTokenizer::TOK_IGNORE_EMPTY); - assert (st.count() == 3); - assert (st[0] == "1"); - assert (st[1] == "2"); - assert (st[2] == "3"); - } -} - - -void StringTokenizerTest::setUp() -{ -} - - -void StringTokenizerTest::tearDown() -{ -} - - -CppUnit::Test* StringTokenizerTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("StringTokenizerTest"); - - CppUnit_addTest(pSuite, StringTokenizerTest, testStringTokenizer); - - return pSuite; -} +// +// StringTokenizerTest.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/StringTokenizerTest.cpp#1 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "StringTokenizerTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/StringTokenizer.h" + + +using Poco::StringTokenizer; + + +StringTokenizerTest::StringTokenizerTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +StringTokenizerTest::~StringTokenizerTest() +{ +} + + +void StringTokenizerTest::testStringTokenizer() +{ + { + StringTokenizer st("", ""); + assert (st.begin() == st.end()); + } + { + StringTokenizer st("", "", StringTokenizer::TOK_IGNORE_EMPTY); + assert (st.begin() == st.end()); + } + { + StringTokenizer st("", "", StringTokenizer::TOK_TRIM); + assert (st.begin() == st.end()); + } + { + StringTokenizer st("", "", StringTokenizer::TOK_TRIM | StringTokenizer::TOK_IGNORE_EMPTY); + assert (st.begin() == st.end()); + } + { + StringTokenizer st("abc", ""); + StringTokenizer::Iterator it = st.begin(); + assert (it != st.end()); + assert (*it++ == "abc"); + assert (it == st.end()); + } + { + StringTokenizer st("abc ", "", StringTokenizer::TOK_TRIM); + StringTokenizer::Iterator it = st.begin(); + assert (it != st.end()); + assert (*it++ == "abc"); + assert (it == st.end()); + } + { + StringTokenizer st(" abc ", "", StringTokenizer::TOK_TRIM); + StringTokenizer::Iterator it = st.begin(); + assert (it != st.end()); + assert (*it++ == "abc"); + assert (it == st.end()); + } + { + StringTokenizer st(" abc", "", StringTokenizer::TOK_TRIM); + StringTokenizer::Iterator it = st.begin(); + assert (it != st.end()); + assert (*it++ == "abc"); + assert (it == st.end()); + } + { + StringTokenizer st("abc", "b"); + StringTokenizer::Iterator it = st.begin(); + assert (it != st.end()); + assert (*it++ == "a"); + assert (it != st.end()); + assert (*it++ == "c"); + assert (it == st.end()); + } + { + StringTokenizer st("abc", "b", StringTokenizer::TOK_TRIM | StringTokenizer::TOK_IGNORE_EMPTY); + StringTokenizer::Iterator it = st.begin(); + assert (it != st.end()); + assert (*it++ == "a"); + assert (it != st.end()); + assert (*it++ == "c"); + assert (it == st.end()); + } + { + StringTokenizer st("abc", "bc"); + StringTokenizer::Iterator it = st.begin(); + assert (it != st.end()); + assert (*it++ == "a"); + assert (it != st.end()); + assert (*it++ == ""); + assert (it == st.end()); + } + { + StringTokenizer st("abc", "bc", StringTokenizer::TOK_TRIM); + StringTokenizer::Iterator it = st.begin(); + assert (it != st.end()); + assert (*it++ == "a"); + assert (it != st.end()); + assert (*it++ == ""); + assert (it == st.end()); + } + { + StringTokenizer st("abc", "bc", StringTokenizer::TOK_IGNORE_EMPTY); + StringTokenizer::Iterator it = st.begin(); + assert (it != st.end()); + assert (*it++ == "a"); + assert (it == st.end()); + } + { + StringTokenizer st("abc", "bc", StringTokenizer::TOK_TRIM | StringTokenizer::TOK_IGNORE_EMPTY); + StringTokenizer::Iterator it = st.begin(); + assert (it != st.end()); + assert (*it++ == "a"); + assert (it == st.end()); + } + { + StringTokenizer st("abc", "bc", StringTokenizer::TOK_TRIM | StringTokenizer::TOK_IGNORE_EMPTY); + StringTokenizer::Iterator it = st.begin(); + assert (it != st.end()); + assert (*it++ == "a"); + assert (it == st.end()); + } + { + StringTokenizer st("a a,c c", ","); + StringTokenizer::Iterator it = st.begin(); + assert (it != st.end()); + assert (*it++ == "a a"); + assert (it != st.end()); + assert (*it++ == "c c"); + assert (it == st.end()); + } + { + StringTokenizer st("a a,c c", ",", StringTokenizer::TOK_TRIM | StringTokenizer::TOK_IGNORE_EMPTY); + StringTokenizer::Iterator it = st.begin(); + assert (it != st.end()); + assert (*it++ == "a a"); + assert (it != st.end()); + assert (*it++ == "c c"); + assert (it == st.end()); + } + { + StringTokenizer st(" a a , , c c ", ","); + StringTokenizer::Iterator it = st.begin(); + assert (it != st.end()); + assert (*it++ == " a a "); + assert (it != st.end()); + assert (*it++ == " "); + assert (it != st.end()); + assert (*it++ == " c c "); + assert (it == st.end()); + } + { + StringTokenizer st(" a a , , c c ", ",", StringTokenizer::TOK_TRIM); + StringTokenizer::Iterator it = st.begin(); + assert (it != st.end()); + assert (*it++ == "a a"); + assert (it != st.end()); + assert (*it++ == ""); + assert (it != st.end()); + assert (*it++ == "c c"); + assert (it == st.end()); + } + { + StringTokenizer st(" a a , , c c ", ",", StringTokenizer::TOK_TRIM | StringTokenizer::TOK_IGNORE_EMPTY); + StringTokenizer::Iterator it = st.begin(); + assert (it != st.end()); + assert (*it++ == "a a"); + assert (it != st.end()); + assert (*it++ == "c c"); + assert (it == st.end()); + } + { + StringTokenizer st("abc,def,,ghi , jk, l ", ",", StringTokenizer::TOK_TRIM | StringTokenizer::TOK_IGNORE_EMPTY); + StringTokenizer::Iterator it = st.begin(); + assert (it != st.end()); + assert (*it++ == "abc"); + assert (it != st.end()); + assert (*it++ == "def"); + assert (it != st.end()); + assert (*it++ == "ghi"); + assert (it != st.end()); + assert (*it++ == "jk"); + assert (it != st.end()); + assert (*it++ == "l"); + assert (it == st.end()); + } + { + StringTokenizer st("abc,def,,ghi // jk, l ", ",/", StringTokenizer::TOK_TRIM | StringTokenizer::TOK_IGNORE_EMPTY); + StringTokenizer::Iterator it = st.begin(); + assert (it != st.end()); + assert (*it++ == "abc"); + assert (it != st.end()); + assert (*it++ == "def"); + assert (it != st.end()); + assert (*it++ == "ghi"); + assert (it != st.end()); + assert (*it++ == "jk"); + assert (it != st.end()); + assert (*it++ == "l"); + assert (it == st.end()); + } + { + StringTokenizer st("a/bc,def,,ghi // jk, l ", ",/", StringTokenizer::TOK_TRIM | StringTokenizer::TOK_IGNORE_EMPTY); + StringTokenizer::Iterator it = st.begin(); + assert (it != st.end()); + assert (*it++ == "a"); + assert (it != st.end()); + assert (*it++ == "bc"); + assert (it != st.end()); + assert (*it++ == "def"); + assert (it != st.end()); + assert (*it++ == "ghi"); + assert (it != st.end()); + assert (*it++ == "jk"); + assert (it != st.end()); + assert (*it++ == "l"); + assert (it == st.end()); + } + { + StringTokenizer st(",ab,cd,", ","); + StringTokenizer::Iterator it = st.begin(); + assert (it != st.end()); + assert (*it++ == ""); + assert (it != st.end()); + assert (*it++ == "ab"); + assert (it != st.end()); + assert (*it++ == "cd"); + assert (it == st.end()); + } + { + StringTokenizer st(",ab,cd,", ",", StringTokenizer::TOK_IGNORE_EMPTY); + StringTokenizer::Iterator it = st.begin(); + assert (it != st.end()); + assert (*it++ == "ab"); + assert (it != st.end()); + assert (*it++ == "cd"); + assert (it == st.end()); + } + { + StringTokenizer st(" , ab , cd , ", ",", StringTokenizer::TOK_TRIM | StringTokenizer::TOK_IGNORE_EMPTY); + StringTokenizer::Iterator it = st.begin(); + assert (it != st.end()); + assert (*it++ == "ab"); + assert (it != st.end()); + assert (*it++ == "cd"); + assert (it == st.end()); + } + { + StringTokenizer st("1 : 2 , : 3 ", ":,", StringTokenizer::TOK_TRIM | StringTokenizer::TOK_IGNORE_EMPTY); + assert (st.count() == 3); + assert (st[0] == "1"); + assert (st[1] == "2"); + assert (st[2] == "3"); + } +} + + +void StringTokenizerTest::setUp() +{ +} + + +void StringTokenizerTest::tearDown() +{ +} + + +CppUnit::Test* StringTokenizerTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("StringTokenizerTest"); + + CppUnit_addTest(pSuite, StringTokenizerTest, testStringTokenizer); + + return pSuite; +} diff --git a/Foundation/testsuite/src/StringTokenizerTest.h b/Foundation/testsuite/src/StringTokenizerTest.h index e27a62173..1e25c7d61 100644 --- a/Foundation/testsuite/src/StringTokenizerTest.h +++ b/Foundation/testsuite/src/StringTokenizerTest.h @@ -1,60 +1,60 @@ -// -// StringTokenizerTest.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/StringTokenizerTest.h#1 $ -// -// Definition of the StringTokenizerTest class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 StringTokenizerTest_INCLUDED -#define StringTokenizerTest_INCLUDED - - -#include "Poco/Foundation.h" -#include "CppUnit/TestCase.h" - - -class StringTokenizerTest: public CppUnit::TestCase -{ -public: - StringTokenizerTest(const std::string& name); - ~StringTokenizerTest(); - - void testStringTokenizer(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // StringTokenizerTest_INCLUDED +// +// StringTokenizerTest.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/StringTokenizerTest.h#1 $ +// +// Definition of the StringTokenizerTest class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 StringTokenizerTest_INCLUDED +#define StringTokenizerTest_INCLUDED + + +#include "Poco/Foundation.h" +#include "CppUnit/TestCase.h" + + +class StringTokenizerTest: public CppUnit::TestCase +{ +public: + StringTokenizerTest(const std::string& name); + ~StringTokenizerTest(); + + void testStringTokenizer(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // StringTokenizerTest_INCLUDED diff --git a/Foundation/testsuite/src/TaskManagerTest.cpp b/Foundation/testsuite/src/TaskManagerTest.cpp index 6dda2da32..c7d33b77a 100644 --- a/Foundation/testsuite/src/TaskManagerTest.cpp +++ b/Foundation/testsuite/src/TaskManagerTest.cpp @@ -1,484 +1,484 @@ -// -// TaskManagerTest.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/TaskManagerTest.cpp#1 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "TaskManagerTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/TaskManager.h" -#include "Poco/Task.h" -#include "Poco/TaskNotification.h" -#include "Poco/NotificationCenter.h" -#include "Poco/Thread.h" -#include "Poco/Event.h" -#include "Poco/Observer.h" -#include "Poco/Exception.h" -#include "Poco/AutoPtr.h" - - -using Poco::TaskManager; -using Poco::Task; -using Poco::NotificationCenter; -using Poco::TaskStartedNotification; -using Poco::TaskCancelledNotification; -using Poco::TaskFinishedNotification; -using Poco::TaskFailedNotification; -using Poco::TaskProgressNotification; -using Poco::TaskCustomNotification; -using Poco::Thread; -using Poco::Event; -using Poco::Observer; -using Poco::Exception; -using Poco::SystemException; -using Poco::NullPointerException; -using Poco::AutoPtr; - - -namespace -{ - class TestTask: public Task - { - public: - TestTask(): - Task("TestTask"), - _fail(false) - { - } - - void runTask() - { - _event.wait(); - setProgress(0.5); - _event.wait(); - if (isCancelled()) - return; - if (_fail) - throw SystemException("warp core breach detected"); - setProgress(1.0); - _event.wait(); - } - - void fail() - { - _fail = true; - } - - void cont() - { - _event.set(); - } - - private: - Event _event; - bool _fail; - }; - - class SimpleTask: public Task - { - public: - SimpleTask(): Task("SimpleTask") - { - } - - void runTask() - { - sleep(10000); - } - }; - - class TaskObserver - { - public: - TaskObserver(): - _started(false), - _cancelled(false), - _finished(false), - _pException(0), - _progress(0.0) - { - } - - ~TaskObserver() - { - delete _pException; - } - - void taskStarted(TaskStartedNotification* pNf) - { - _started = true; - pNf->release(); - } - - void taskCancelled(TaskCancelledNotification* pNf) - { - _cancelled = true; - pNf->release(); - } - - void taskFinished(TaskFinishedNotification* pNf) - { - _finished = true; - pNf->release(); - } - - void taskFailed(TaskFailedNotification* pNf) - { - _pException = pNf->reason().clone(); - pNf->release(); - } - - void taskProgress(TaskProgressNotification* pNf) - { - _progress = pNf->progress(); - pNf->release(); - } - - bool started() const - { - return _started; - } - - bool cancelled() const - { - return _cancelled; - } - - bool finished() const - { - return _finished; - } - - float progress() const - { - return _progress; - } - - Exception* error() const - { - return _pException; - } - - private: - bool _started; - bool _cancelled; - bool _finished; - Exception* _pException; - float _progress; - }; - - - template - class CustomNotificationTask: public Task - { - public: - CustomNotificationTask(const T& t): - Task("CustomNotificationTask"), - _custom(t) - { - } - - void runTask() - { - sleep(10000); - } - - void setCustom(const T& custom) - { - _custom = custom; - postNotification(new TaskCustomNotification(this, _custom)); - } - - private: - T _custom; - }; - - - template - class CustomTaskObserver - { - public: - CustomTaskObserver(const C& custom): _custom(custom) - { - } - - ~CustomTaskObserver() - { - } - - void taskCustom(TaskCustomNotification* pNf) - { - _custom = pNf->custom(); - pNf->release(); - } - - const C& custom() const - { - return _custom; - } - - private: - C _custom; - }; -} - - -TaskManagerTest::TaskManagerTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -TaskManagerTest::~TaskManagerTest() -{ -} - - -void TaskManagerTest::testFinish() -{ - TaskManager tm; - TaskObserver to; - tm.addObserver(Observer(to, &TaskObserver::taskStarted)); - tm.addObserver(Observer(to, &TaskObserver::taskCancelled)); - tm.addObserver(Observer(to, &TaskObserver::taskFailed)); - tm.addObserver(Observer(to, &TaskObserver::taskFinished)); - tm.addObserver(Observer(to, &TaskObserver::taskProgress)); - AutoPtr pTT = new TestTask; - tm.start(pTT.duplicate()); - assert (pTT->progress() == 0); - Thread::sleep(200); - pTT->cont(); - while (pTT->progress() != 0.5) Thread::sleep(50); - assert (to.progress() == 0.5); - assert (to.started()); - assert (pTT->state() == Task::TASK_RUNNING); - TaskManager::TaskList list = tm.taskList(); - assert (list.size() == 1); - assert (tm.count() == 1); - pTT->cont(); - while (pTT->progress() != 1.0) Thread::sleep(50); - pTT->cont(); - while (pTT->state() != Task::TASK_FINISHED) Thread::sleep(50); - assert (pTT->state() == Task::TASK_FINISHED); - assert (to.finished()); - while (tm.count() == 1) Thread::sleep(50); - list = tm.taskList(); - assert (list.empty()); - assert (!to.error()); -} - - -void TaskManagerTest::testCancel() -{ - TaskManager tm; - TaskObserver to; - tm.addObserver(Observer(to, &TaskObserver::taskStarted)); - tm.addObserver(Observer(to, &TaskObserver::taskCancelled)); - tm.addObserver(Observer(to, &TaskObserver::taskFailed)); - tm.addObserver(Observer(to, &TaskObserver::taskFinished)); - tm.addObserver(Observer(to, &TaskObserver::taskProgress)); - AutoPtr pTT = new TestTask; - tm.start(pTT.duplicate()); - assert (pTT->progress() == 0); - Thread::sleep(200); - pTT->cont(); - while (pTT->progress() != 0.5) Thread::sleep(50); - assert (to.progress() == 0.5); - assert (to.started()); - assert (pTT->state() == Task::TASK_RUNNING); - TaskManager::TaskList list = tm.taskList(); - assert (list.size() == 1); - assert (tm.count() == 1); - tm.cancelAll(); - assert (to.cancelled()); - pTT->cont(); - while (pTT->state() != Task::TASK_FINISHED) Thread::sleep(50); - assert (pTT->state() == Task::TASK_FINISHED); - assert (to.finished()); - while (tm.count() == 1) Thread::sleep(50); - list = tm.taskList(); - assert (list.empty()); - assert (!to.error()); -} - - -void TaskManagerTest::testError() -{ - TaskManager tm; - TaskObserver to; - tm.addObserver(Observer(to, &TaskObserver::taskStarted)); - tm.addObserver(Observer(to, &TaskObserver::taskCancelled)); - tm.addObserver(Observer(to, &TaskObserver::taskFailed)); - tm.addObserver(Observer(to, &TaskObserver::taskFinished)); - tm.addObserver(Observer(to, &TaskObserver::taskProgress)); - AutoPtr pTT = new TestTask; - tm.start(pTT.duplicate()); - assert (pTT->progress() == 0); - Thread::sleep(200); - pTT->cont(); - while (pTT->progress() != 0.5) Thread::sleep(50); - assert (to.progress() == 0.5); - assert (to.started()); - assert (pTT->state() == Task::TASK_RUNNING); - TaskManager::TaskList list = tm.taskList(); - assert (list.size() == 1); - assert (tm.count() == 1); - pTT->fail(); - pTT->cont(); - while (pTT->state() != Task::TASK_FINISHED) Thread::sleep(50); - assert (pTT->state() == Task::TASK_FINISHED); - assert (to.finished()); - assert (to.error() != 0); - while (tm.count() == 1) Thread::sleep(50); - list = tm.taskList(); - assert (list.empty()); -} - - -void TaskManagerTest::testCustom() -{ - TaskManager tm; - - CustomTaskObserver ti(0); - tm.addObserver( - Observer, TaskCustomNotification > - (ti, &CustomTaskObserver::taskCustom)); - - AutoPtr > pCNT1 = new CustomNotificationTask(0); - tm.start(pCNT1.duplicate()); - assert (ti.custom() == 0); - - for (int i = 1; i < 10; ++i) - { - pCNT1->setCustom(i); - assert (ti.custom() == i); - } - - CustomTaskObserver ts(""); - tm.addObserver( - Observer, TaskCustomNotification > - (ts, &CustomTaskObserver::taskCustom)); - - AutoPtr > pCNT2 = new CustomNotificationTask(""); - tm.start(pCNT2.duplicate()); - assert (tm.taskList().size() == 2); - assert (ts.custom() == ""); - std::string str("notify me"); - pCNT2->setCustom(str); - assert (ts.custom() == str); - - S s; - s.i = 0; - s.str = ""; - - CustomTaskObserver ptst(&s); - - tm.addObserver( - Observer, TaskCustomNotification > - (ptst, &CustomTaskObserver::taskCustom)); - - AutoPtr > pCNT3 = new CustomNotificationTask(&s); - tm.start(pCNT3.duplicate()); - assert (tm.taskList().size() == 3); - assert (ptst.custom()->i == 0); - assert (ptst.custom()->str == ""); - s.i = 123; - s.str = "123"; - pCNT3->setCustom(&s); - assert (ptst.custom()->i == 123); - assert (ptst.custom()->str == "123"); - - s.i = 0; - s.str = ""; - - CustomTaskObserver tst(s); - - tm.addObserver( - Observer, TaskCustomNotification > - (tst, &CustomTaskObserver::taskCustom)); - - AutoPtr > pCNT4 = new CustomNotificationTask(s); - tm.start(pCNT4.duplicate()); - assert (tm.taskList().size() == 4); - assert (tst.custom().i == 0); - assert (tst.custom().str == ""); - s.i = 123; - s.str = "123"; - pCNT4->setCustom(s); - assert (tst.custom().i == 123); - assert (tst.custom().str == "123"); - - AutoPtr pST = new SimpleTask; - tm.start(pST.duplicate()); - assert (tm.taskList().size() == 5); - - tm.cancelAll(); - while (tm.count() > 0) Thread::sleep(50); - assert (tm.count() == 0); -} - - -void TaskManagerTest::testMultiTasks() -{ - TaskManager tm; - tm.start(new SimpleTask); - tm.start(new SimpleTask); - tm.start(new SimpleTask); - - TaskManager::TaskList list = tm.taskList(); - assert (list.size() == 3); - - tm.cancelAll(); - while (tm.count() > 0) Thread::sleep(100); - assert (tm.count() == 0); -} - - -void TaskManagerTest::setUp() -{ -} - - -void TaskManagerTest::tearDown() -{ -} - - -CppUnit::Test* TaskManagerTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("TaskManagerTest"); - - CppUnit_addTest(pSuite, TaskManagerTest, testFinish); - CppUnit_addTest(pSuite, TaskManagerTest, testCancel); - CppUnit_addTest(pSuite, TaskManagerTest, testError); - CppUnit_addTest(pSuite, TaskManagerTest, testMultiTasks); - CppUnit_addTest(pSuite, TaskManagerTest, testCustom); - - return pSuite; -} +// +// TaskManagerTest.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/TaskManagerTest.cpp#1 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "TaskManagerTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/TaskManager.h" +#include "Poco/Task.h" +#include "Poco/TaskNotification.h" +#include "Poco/NotificationCenter.h" +#include "Poco/Thread.h" +#include "Poco/Event.h" +#include "Poco/Observer.h" +#include "Poco/Exception.h" +#include "Poco/AutoPtr.h" + + +using Poco::TaskManager; +using Poco::Task; +using Poco::NotificationCenter; +using Poco::TaskStartedNotification; +using Poco::TaskCancelledNotification; +using Poco::TaskFinishedNotification; +using Poco::TaskFailedNotification; +using Poco::TaskProgressNotification; +using Poco::TaskCustomNotification; +using Poco::Thread; +using Poco::Event; +using Poco::Observer; +using Poco::Exception; +using Poco::SystemException; +using Poco::NullPointerException; +using Poco::AutoPtr; + + +namespace +{ + class TestTask: public Task + { + public: + TestTask(): + Task("TestTask"), + _fail(false) + { + } + + void runTask() + { + _event.wait(); + setProgress(0.5); + _event.wait(); + if (isCancelled()) + return; + if (_fail) + throw SystemException("warp core breach detected"); + setProgress(1.0); + _event.wait(); + } + + void fail() + { + _fail = true; + } + + void cont() + { + _event.set(); + } + + private: + Event _event; + bool _fail; + }; + + class SimpleTask: public Task + { + public: + SimpleTask(): Task("SimpleTask") + { + } + + void runTask() + { + sleep(10000); + } + }; + + class TaskObserver + { + public: + TaskObserver(): + _started(false), + _cancelled(false), + _finished(false), + _pException(0), + _progress(0.0) + { + } + + ~TaskObserver() + { + delete _pException; + } + + void taskStarted(TaskStartedNotification* pNf) + { + _started = true; + pNf->release(); + } + + void taskCancelled(TaskCancelledNotification* pNf) + { + _cancelled = true; + pNf->release(); + } + + void taskFinished(TaskFinishedNotification* pNf) + { + _finished = true; + pNf->release(); + } + + void taskFailed(TaskFailedNotification* pNf) + { + _pException = pNf->reason().clone(); + pNf->release(); + } + + void taskProgress(TaskProgressNotification* pNf) + { + _progress = pNf->progress(); + pNf->release(); + } + + bool started() const + { + return _started; + } + + bool cancelled() const + { + return _cancelled; + } + + bool finished() const + { + return _finished; + } + + float progress() const + { + return _progress; + } + + Exception* error() const + { + return _pException; + } + + private: + bool _started; + bool _cancelled; + bool _finished; + Exception* _pException; + float _progress; + }; + + + template + class CustomNotificationTask: public Task + { + public: + CustomNotificationTask(const T& t): + Task("CustomNotificationTask"), + _custom(t) + { + } + + void runTask() + { + sleep(10000); + } + + void setCustom(const T& custom) + { + _custom = custom; + postNotification(new TaskCustomNotification(this, _custom)); + } + + private: + T _custom; + }; + + + template + class CustomTaskObserver + { + public: + CustomTaskObserver(const C& custom): _custom(custom) + { + } + + ~CustomTaskObserver() + { + } + + void taskCustom(TaskCustomNotification* pNf) + { + _custom = pNf->custom(); + pNf->release(); + } + + const C& custom() const + { + return _custom; + } + + private: + C _custom; + }; +} + + +TaskManagerTest::TaskManagerTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +TaskManagerTest::~TaskManagerTest() +{ +} + + +void TaskManagerTest::testFinish() +{ + TaskManager tm; + TaskObserver to; + tm.addObserver(Observer(to, &TaskObserver::taskStarted)); + tm.addObserver(Observer(to, &TaskObserver::taskCancelled)); + tm.addObserver(Observer(to, &TaskObserver::taskFailed)); + tm.addObserver(Observer(to, &TaskObserver::taskFinished)); + tm.addObserver(Observer(to, &TaskObserver::taskProgress)); + AutoPtr pTT = new TestTask; + tm.start(pTT.duplicate()); + assert (pTT->progress() == 0); + Thread::sleep(200); + pTT->cont(); + while (pTT->progress() != 0.5) Thread::sleep(50); + assert (to.progress() == 0.5); + assert (to.started()); + assert (pTT->state() == Task::TASK_RUNNING); + TaskManager::TaskList list = tm.taskList(); + assert (list.size() == 1); + assert (tm.count() == 1); + pTT->cont(); + while (pTT->progress() != 1.0) Thread::sleep(50); + pTT->cont(); + while (pTT->state() != Task::TASK_FINISHED) Thread::sleep(50); + assert (pTT->state() == Task::TASK_FINISHED); + assert (to.finished()); + while (tm.count() == 1) Thread::sleep(50); + list = tm.taskList(); + assert (list.empty()); + assert (!to.error()); +} + + +void TaskManagerTest::testCancel() +{ + TaskManager tm; + TaskObserver to; + tm.addObserver(Observer(to, &TaskObserver::taskStarted)); + tm.addObserver(Observer(to, &TaskObserver::taskCancelled)); + tm.addObserver(Observer(to, &TaskObserver::taskFailed)); + tm.addObserver(Observer(to, &TaskObserver::taskFinished)); + tm.addObserver(Observer(to, &TaskObserver::taskProgress)); + AutoPtr pTT = new TestTask; + tm.start(pTT.duplicate()); + assert (pTT->progress() == 0); + Thread::sleep(200); + pTT->cont(); + while (pTT->progress() != 0.5) Thread::sleep(50); + assert (to.progress() == 0.5); + assert (to.started()); + assert (pTT->state() == Task::TASK_RUNNING); + TaskManager::TaskList list = tm.taskList(); + assert (list.size() == 1); + assert (tm.count() == 1); + tm.cancelAll(); + assert (to.cancelled()); + pTT->cont(); + while (pTT->state() != Task::TASK_FINISHED) Thread::sleep(50); + assert (pTT->state() == Task::TASK_FINISHED); + assert (to.finished()); + while (tm.count() == 1) Thread::sleep(50); + list = tm.taskList(); + assert (list.empty()); + assert (!to.error()); +} + + +void TaskManagerTest::testError() +{ + TaskManager tm; + TaskObserver to; + tm.addObserver(Observer(to, &TaskObserver::taskStarted)); + tm.addObserver(Observer(to, &TaskObserver::taskCancelled)); + tm.addObserver(Observer(to, &TaskObserver::taskFailed)); + tm.addObserver(Observer(to, &TaskObserver::taskFinished)); + tm.addObserver(Observer(to, &TaskObserver::taskProgress)); + AutoPtr pTT = new TestTask; + tm.start(pTT.duplicate()); + assert (pTT->progress() == 0); + Thread::sleep(200); + pTT->cont(); + while (pTT->progress() != 0.5) Thread::sleep(50); + assert (to.progress() == 0.5); + assert (to.started()); + assert (pTT->state() == Task::TASK_RUNNING); + TaskManager::TaskList list = tm.taskList(); + assert (list.size() == 1); + assert (tm.count() == 1); + pTT->fail(); + pTT->cont(); + while (pTT->state() != Task::TASK_FINISHED) Thread::sleep(50); + assert (pTT->state() == Task::TASK_FINISHED); + assert (to.finished()); + assert (to.error() != 0); + while (tm.count() == 1) Thread::sleep(50); + list = tm.taskList(); + assert (list.empty()); +} + + +void TaskManagerTest::testCustom() +{ + TaskManager tm; + + CustomTaskObserver ti(0); + tm.addObserver( + Observer, TaskCustomNotification > + (ti, &CustomTaskObserver::taskCustom)); + + AutoPtr > pCNT1 = new CustomNotificationTask(0); + tm.start(pCNT1.duplicate()); + assert (ti.custom() == 0); + + for (int i = 1; i < 10; ++i) + { + pCNT1->setCustom(i); + assert (ti.custom() == i); + } + + CustomTaskObserver ts(""); + tm.addObserver( + Observer, TaskCustomNotification > + (ts, &CustomTaskObserver::taskCustom)); + + AutoPtr > pCNT2 = new CustomNotificationTask(""); + tm.start(pCNT2.duplicate()); + assert (tm.taskList().size() == 2); + assert (ts.custom() == ""); + std::string str("notify me"); + pCNT2->setCustom(str); + assert (ts.custom() == str); + + S s; + s.i = 0; + s.str = ""; + + CustomTaskObserver ptst(&s); + + tm.addObserver( + Observer, TaskCustomNotification > + (ptst, &CustomTaskObserver::taskCustom)); + + AutoPtr > pCNT3 = new CustomNotificationTask(&s); + tm.start(pCNT3.duplicate()); + assert (tm.taskList().size() == 3); + assert (ptst.custom()->i == 0); + assert (ptst.custom()->str == ""); + s.i = 123; + s.str = "123"; + pCNT3->setCustom(&s); + assert (ptst.custom()->i == 123); + assert (ptst.custom()->str == "123"); + + s.i = 0; + s.str = ""; + + CustomTaskObserver tst(s); + + tm.addObserver( + Observer, TaskCustomNotification > + (tst, &CustomTaskObserver::taskCustom)); + + AutoPtr > pCNT4 = new CustomNotificationTask(s); + tm.start(pCNT4.duplicate()); + assert (tm.taskList().size() == 4); + assert (tst.custom().i == 0); + assert (tst.custom().str == ""); + s.i = 123; + s.str = "123"; + pCNT4->setCustom(s); + assert (tst.custom().i == 123); + assert (tst.custom().str == "123"); + + AutoPtr pST = new SimpleTask; + tm.start(pST.duplicate()); + assert (tm.taskList().size() == 5); + + tm.cancelAll(); + while (tm.count() > 0) Thread::sleep(50); + assert (tm.count() == 0); +} + + +void TaskManagerTest::testMultiTasks() +{ + TaskManager tm; + tm.start(new SimpleTask); + tm.start(new SimpleTask); + tm.start(new SimpleTask); + + TaskManager::TaskList list = tm.taskList(); + assert (list.size() == 3); + + tm.cancelAll(); + while (tm.count() > 0) Thread::sleep(100); + assert (tm.count() == 0); +} + + +void TaskManagerTest::setUp() +{ +} + + +void TaskManagerTest::tearDown() +{ +} + + +CppUnit::Test* TaskManagerTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("TaskManagerTest"); + + CppUnit_addTest(pSuite, TaskManagerTest, testFinish); + CppUnit_addTest(pSuite, TaskManagerTest, testCancel); + CppUnit_addTest(pSuite, TaskManagerTest, testError); + CppUnit_addTest(pSuite, TaskManagerTest, testMultiTasks); + CppUnit_addTest(pSuite, TaskManagerTest, testCustom); + + return pSuite; +} diff --git a/Foundation/testsuite/src/TaskManagerTest.h b/Foundation/testsuite/src/TaskManagerTest.h index 66740287e..1cc9a5639 100644 --- a/Foundation/testsuite/src/TaskManagerTest.h +++ b/Foundation/testsuite/src/TaskManagerTest.h @@ -1,70 +1,70 @@ -// -// TaskManagerTest.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/TaskManagerTest.h#1 $ -// -// Definition of the TaskManagerTest class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 TaskManagerTest_INCLUDED -#define TaskManagerTest_INCLUDED - - -#include "Poco/Foundation.h" -#include "CppUnit/TestCase.h" - - -class TaskManagerTest: public CppUnit::TestCase -{ -public: - struct S - { - int i; - std::string str; - }; - - TaskManagerTest(const std::string& name); - ~TaskManagerTest(); - - void testFinish(); - void testCancel(); - void testError(); - void testCustom(); - void testMultiTasks(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // TaskManagerTest_INCLUDED +// +// TaskManagerTest.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/TaskManagerTest.h#1 $ +// +// Definition of the TaskManagerTest class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 TaskManagerTest_INCLUDED +#define TaskManagerTest_INCLUDED + + +#include "Poco/Foundation.h" +#include "CppUnit/TestCase.h" + + +class TaskManagerTest: public CppUnit::TestCase +{ +public: + struct S + { + int i; + std::string str; + }; + + TaskManagerTest(const std::string& name); + ~TaskManagerTest(); + + void testFinish(); + void testCancel(); + void testError(); + void testCustom(); + void testMultiTasks(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // TaskManagerTest_INCLUDED diff --git a/Foundation/testsuite/src/TaskTest.cpp b/Foundation/testsuite/src/TaskTest.cpp index e1537ce4c..07263c703 100644 --- a/Foundation/testsuite/src/TaskTest.cpp +++ b/Foundation/testsuite/src/TaskTest.cpp @@ -1,161 +1,161 @@ -// -// TaskTest.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/TaskTest.cpp#1 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "TaskTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/Task.h" -#include "Poco/Thread.h" -#include "Poco/Event.h" -#include "Poco/AutoPtr.h" - - -using Poco::Task; -using Poco::Thread; -using Poco::Event; -using Poco::AutoPtr; - - -namespace -{ - class TestTask: public Task - { - public: - TestTask(): Task("TestTask") - { - } - - void runTask() - { - _event.wait(); - if (sleep(10)) - return; - setProgress(0.5); - _event.wait(); - if (isCancelled()) - return; - setProgress(1.0); - _event.wait(); - } - - void cont() - { - _event.set(); - } - - private: - Event _event; - }; -} - - -TaskTest::TaskTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -TaskTest::~TaskTest() -{ -} - - -void TaskTest::testFinish() -{ - AutoPtr pTT = new TestTask; - assert (pTT->state() == Task::TASK_IDLE); - Thread thr; - thr.start(*pTT); - assert (pTT->progress() == 0); - pTT->cont(); - while (pTT->progress() != 0.5) Thread::sleep(50); - assert (pTT->state() == Task::TASK_RUNNING); - pTT->cont(); - while (pTT->progress() != 1.0) Thread::sleep(50); - pTT->cont(); - thr.join(); - assert (pTT->state() == Task::TASK_FINISHED); -} - - -void TaskTest::testCancel1() -{ - AutoPtr pTT = new TestTask; - assert (pTT->state() == Task::TASK_IDLE); - Thread thr; - thr.start(*pTT); - assert (pTT->progress() == 0); - pTT->cont(); - while (pTT->progress() != 0.5) Thread::sleep(50); - assert (pTT->state() == Task::TASK_RUNNING); - pTT->cancel(); - assert (pTT->state() == Task::TASK_CANCELLING); - pTT->cont(); - thr.join(); - assert (pTT->state() == Task::TASK_FINISHED); -} - - -void TaskTest::testCancel2() -{ - AutoPtr pTT = new TestTask; - assert (pTT->state() == Task::TASK_IDLE); - Thread thr; - thr.start(*pTT); - assert (pTT->progress() == 0); - pTT->cancel(); - assert (pTT->state() == Task::TASK_CANCELLING); - pTT->cont(); - thr.join(); - assert (pTT->state() == Task::TASK_FINISHED); -} - - -void TaskTest::setUp() -{ -} - - -void TaskTest::tearDown() -{ -} - - -CppUnit::Test* TaskTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("TaskTest"); - - CppUnit_addTest(pSuite, TaskTest, testFinish); - CppUnit_addTest(pSuite, TaskTest, testCancel1); - CppUnit_addTest(pSuite, TaskTest, testCancel2); - - return pSuite; -} +// +// TaskTest.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/TaskTest.cpp#1 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "TaskTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/Task.h" +#include "Poco/Thread.h" +#include "Poco/Event.h" +#include "Poco/AutoPtr.h" + + +using Poco::Task; +using Poco::Thread; +using Poco::Event; +using Poco::AutoPtr; + + +namespace +{ + class TestTask: public Task + { + public: + TestTask(): Task("TestTask") + { + } + + void runTask() + { + _event.wait(); + if (sleep(10)) + return; + setProgress(0.5); + _event.wait(); + if (isCancelled()) + return; + setProgress(1.0); + _event.wait(); + } + + void cont() + { + _event.set(); + } + + private: + Event _event; + }; +} + + +TaskTest::TaskTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +TaskTest::~TaskTest() +{ +} + + +void TaskTest::testFinish() +{ + AutoPtr pTT = new TestTask; + assert (pTT->state() == Task::TASK_IDLE); + Thread thr; + thr.start(*pTT); + assert (pTT->progress() == 0); + pTT->cont(); + while (pTT->progress() != 0.5) Thread::sleep(50); + assert (pTT->state() == Task::TASK_RUNNING); + pTT->cont(); + while (pTT->progress() != 1.0) Thread::sleep(50); + pTT->cont(); + thr.join(); + assert (pTT->state() == Task::TASK_FINISHED); +} + + +void TaskTest::testCancel1() +{ + AutoPtr pTT = new TestTask; + assert (pTT->state() == Task::TASK_IDLE); + Thread thr; + thr.start(*pTT); + assert (pTT->progress() == 0); + pTT->cont(); + while (pTT->progress() != 0.5) Thread::sleep(50); + assert (pTT->state() == Task::TASK_RUNNING); + pTT->cancel(); + assert (pTT->state() == Task::TASK_CANCELLING); + pTT->cont(); + thr.join(); + assert (pTT->state() == Task::TASK_FINISHED); +} + + +void TaskTest::testCancel2() +{ + AutoPtr pTT = new TestTask; + assert (pTT->state() == Task::TASK_IDLE); + Thread thr; + thr.start(*pTT); + assert (pTT->progress() == 0); + pTT->cancel(); + assert (pTT->state() == Task::TASK_CANCELLING); + pTT->cont(); + thr.join(); + assert (pTT->state() == Task::TASK_FINISHED); +} + + +void TaskTest::setUp() +{ +} + + +void TaskTest::tearDown() +{ +} + + +CppUnit::Test* TaskTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("TaskTest"); + + CppUnit_addTest(pSuite, TaskTest, testFinish); + CppUnit_addTest(pSuite, TaskTest, testCancel1); + CppUnit_addTest(pSuite, TaskTest, testCancel2); + + return pSuite; +} diff --git a/Foundation/testsuite/src/TaskTest.h b/Foundation/testsuite/src/TaskTest.h index a0179e894..038c28e33 100644 --- a/Foundation/testsuite/src/TaskTest.h +++ b/Foundation/testsuite/src/TaskTest.h @@ -1,62 +1,62 @@ -// -// TaskTest.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/TaskTest.h#1 $ -// -// Definition of the TaskTest class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 TaskTest_INCLUDED -#define TaskTest_INCLUDED - - -#include "Poco/Foundation.h" -#include "CppUnit/TestCase.h" - - -class TaskTest: public CppUnit::TestCase -{ -public: - TaskTest(const std::string& name); - ~TaskTest(); - - void testFinish(); - void testCancel1(); - void testCancel2(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // TaskTest_INCLUDED +// +// TaskTest.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/TaskTest.h#1 $ +// +// Definition of the TaskTest class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 TaskTest_INCLUDED +#define TaskTest_INCLUDED + + +#include "Poco/Foundation.h" +#include "CppUnit/TestCase.h" + + +class TaskTest: public CppUnit::TestCase +{ +public: + TaskTest(const std::string& name); + ~TaskTest(); + + void testFinish(); + void testCancel1(); + void testCancel2(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // TaskTest_INCLUDED diff --git a/Foundation/testsuite/src/TaskTestSuite.cpp b/Foundation/testsuite/src/TaskTestSuite.cpp index adaacb58b..d2fa842fe 100644 --- a/Foundation/testsuite/src/TaskTestSuite.cpp +++ b/Foundation/testsuite/src/TaskTestSuite.cpp @@ -1,46 +1,46 @@ -// -// TaskTestSuite.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/TaskTestSuite.cpp#1 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "TaskTestSuite.h" -#include "TaskTest.h" -#include "TaskManagerTest.h" - - -CppUnit::Test* TaskTestSuite::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("TaskTestSuite"); - - pSuite->addTest(TaskTest::suite()); - pSuite->addTest(TaskManagerTest::suite()); - - return pSuite; -} +// +// TaskTestSuite.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/TaskTestSuite.cpp#1 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "TaskTestSuite.h" +#include "TaskTest.h" +#include "TaskManagerTest.h" + + +CppUnit::Test* TaskTestSuite::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("TaskTestSuite"); + + pSuite->addTest(TaskTest::suite()); + pSuite->addTest(TaskManagerTest::suite()); + + return pSuite; +} diff --git a/Foundation/testsuite/src/TaskTestSuite.h b/Foundation/testsuite/src/TaskTestSuite.h index 46b29f590..fdd4c6117 100644 --- a/Foundation/testsuite/src/TaskTestSuite.h +++ b/Foundation/testsuite/src/TaskTestSuite.h @@ -1,49 +1,49 @@ -// -// TaskTestSuite.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/TaskTestSuite.h#1 $ -// -// Definition of the TaskTestSuite class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 TaskTestSuite_INCLUDED -#define TaskTestSuite_INCLUDED - - -#include "CppUnit/TestSuite.h" - - -class TaskTestSuite -{ -public: - static CppUnit::Test* suite(); -}; - - -#endif // TaskTestSuite_INCLUDED +// +// TaskTestSuite.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/TaskTestSuite.h#1 $ +// +// Definition of the TaskTestSuite class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 TaskTestSuite_INCLUDED +#define TaskTestSuite_INCLUDED + + +#include "CppUnit/TestSuite.h" + + +class TaskTestSuite +{ +public: + static CppUnit::Test* suite(); +}; + + +#endif // TaskTestSuite_INCLUDED diff --git a/Foundation/testsuite/src/TeeStreamTest.cpp b/Foundation/testsuite/src/TeeStreamTest.cpp index 997998b6f..71bee4935 100644 --- a/Foundation/testsuite/src/TeeStreamTest.cpp +++ b/Foundation/testsuite/src/TeeStreamTest.cpp @@ -1,96 +1,96 @@ -// -// TeeStreamTest.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/TeeStreamTest.cpp#1 $ -// -// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "TeeStreamTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/TeeStream.h" -#include - - -using Poco::TeeInputStream; -using Poco::TeeOutputStream; - - -TeeStreamTest::TeeStreamTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -TeeStreamTest::~TeeStreamTest() -{ -} - - -void TeeStreamTest::testTeeInputStream() -{ - std::istringstream istr("foo"); - std::ostringstream ostr; - TeeInputStream tis(istr); - tis.addStream(ostr); - std::string s; - tis >> s; - assert (ostr.str() == "foo"); -} - - -void TeeStreamTest::testTeeOutputStream() -{ - std::ostringstream ostr1; - std::ostringstream ostr2; - TeeOutputStream tos(ostr1); - tos.addStream(ostr2); - tos << "bar" << std::flush; - assert (ostr1.str() == "bar"); - assert (ostr2.str() == "bar"); -} - - -void TeeStreamTest::setUp() -{ -} - - -void TeeStreamTest::tearDown() -{ -} - - -CppUnit::Test* TeeStreamTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("TeeStreamTest"); - - CppUnit_addTest(pSuite, TeeStreamTest, testTeeInputStream); - CppUnit_addTest(pSuite, TeeStreamTest, testTeeOutputStream); - - return pSuite; -} +// +// TeeStreamTest.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/TeeStreamTest.cpp#1 $ +// +// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "TeeStreamTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/TeeStream.h" +#include + + +using Poco::TeeInputStream; +using Poco::TeeOutputStream; + + +TeeStreamTest::TeeStreamTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +TeeStreamTest::~TeeStreamTest() +{ +} + + +void TeeStreamTest::testTeeInputStream() +{ + std::istringstream istr("foo"); + std::ostringstream ostr; + TeeInputStream tis(istr); + tis.addStream(ostr); + std::string s; + tis >> s; + assert (ostr.str() == "foo"); +} + + +void TeeStreamTest::testTeeOutputStream() +{ + std::ostringstream ostr1; + std::ostringstream ostr2; + TeeOutputStream tos(ostr1); + tos.addStream(ostr2); + tos << "bar" << std::flush; + assert (ostr1.str() == "bar"); + assert (ostr2.str() == "bar"); +} + + +void TeeStreamTest::setUp() +{ +} + + +void TeeStreamTest::tearDown() +{ +} + + +CppUnit::Test* TeeStreamTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("TeeStreamTest"); + + CppUnit_addTest(pSuite, TeeStreamTest, testTeeInputStream); + CppUnit_addTest(pSuite, TeeStreamTest, testTeeOutputStream); + + return pSuite; +} diff --git a/Foundation/testsuite/src/TeeStreamTest.h b/Foundation/testsuite/src/TeeStreamTest.h index ac7031a70..427088b2b 100644 --- a/Foundation/testsuite/src/TeeStreamTest.h +++ b/Foundation/testsuite/src/TeeStreamTest.h @@ -1,61 +1,61 @@ -// -// TeeStreamTest.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/TeeStreamTest.h#1 $ -// -// Definition of the TeeStreamTest class. -// -// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 TeeStreamTest_INCLUDED -#define TeeStreamTest_INCLUDED - - -#include "Poco/Foundation.h" -#include "CppUnit/TestCase.h" - - -class TeeStreamTest: public CppUnit::TestCase -{ -public: - TeeStreamTest(const std::string& name); - ~TeeStreamTest(); - - void testTeeInputStream(); - void testTeeOutputStream(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // TeeStreamTest_INCLUDED +// +// TeeStreamTest.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/TeeStreamTest.h#1 $ +// +// Definition of the TeeStreamTest class. +// +// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 TeeStreamTest_INCLUDED +#define TeeStreamTest_INCLUDED + + +#include "Poco/Foundation.h" +#include "CppUnit/TestCase.h" + + +class TeeStreamTest: public CppUnit::TestCase +{ +public: + TeeStreamTest(const std::string& name); + ~TeeStreamTest(); + + void testTeeInputStream(); + void testTeeOutputStream(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // TeeStreamTest_INCLUDED diff --git a/Foundation/testsuite/src/TestApp.cpp b/Foundation/testsuite/src/TestApp.cpp index 24ea1a259..67e3e32cd 100644 --- a/Foundation/testsuite/src/TestApp.cpp +++ b/Foundation/testsuite/src/TestApp.cpp @@ -1,55 +1,55 @@ -// -// TestApp.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/TestApp.cpp#1 $ -// -// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include -#include - - -int main(int argc, char** argv) -{ - if (argc > 1) - { - std::string arg(argv[1]); - if (arg == "-hello") - { - std::cout << "Hello, world!"; - } - else if (arg == "-count") - { - int n = 0; - int c = std::cin.get(); - while (c != -1) { ++n; c = std::cin.get(); } - return n; - } - } - return argc - 1; -} +// +// TestApp.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/TestApp.cpp#1 $ +// +// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include +#include + + +int main(int argc, char** argv) +{ + if (argc > 1) + { + std::string arg(argv[1]); + if (arg == "-hello") + { + std::cout << "Hello, world!"; + } + else if (arg == "-count") + { + int n = 0; + int c = std::cin.get(); + while (c != -1) { ++n; c = std::cin.get(); } + return n; + } + } + return argc - 1; +} diff --git a/Foundation/testsuite/src/TestChannel.cpp b/Foundation/testsuite/src/TestChannel.cpp index d56aca207..4e072bada 100644 --- a/Foundation/testsuite/src/TestChannel.cpp +++ b/Foundation/testsuite/src/TestChannel.cpp @@ -1,61 +1,61 @@ -// -// TestChannel.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/TestChannel.cpp#1 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "TestChannel.h" - - -TestChannel::TestChannel() -{ -} - - -TestChannel::~TestChannel() -{ -} - - -void TestChannel::log(const Poco::Message& msg) -{ - _msgList.push_back(msg); -} - - -TestChannel::MsgList& TestChannel::list() -{ - return _msgList; -} - - -void TestChannel::clear() -{ - _msgList.clear(); -} +// +// TestChannel.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/TestChannel.cpp#1 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "TestChannel.h" + + +TestChannel::TestChannel() +{ +} + + +TestChannel::~TestChannel() +{ +} + + +void TestChannel::log(const Poco::Message& msg) +{ + _msgList.push_back(msg); +} + + +TestChannel::MsgList& TestChannel::list() +{ + return _msgList; +} + + +void TestChannel::clear() +{ + _msgList.clear(); +} diff --git a/Foundation/testsuite/src/TestChannel.h b/Foundation/testsuite/src/TestChannel.h index 13a5d23ef..c95ececf9 100644 --- a/Foundation/testsuite/src/TestChannel.h +++ b/Foundation/testsuite/src/TestChannel.h @@ -1,61 +1,61 @@ -// -// TestChannel.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/TestChannel.h#1 $ -// -// Definition of the TestChannel class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 TestChannel_INCLUDED -#define TestChannel_INCLUDED - - -#include "Poco/Channel.h" -#include "Poco/Message.h" -#include - - -class TestChannel: public Poco::Channel -{ -public: - typedef std::list MsgList; - - TestChannel(); - ~TestChannel(); - - void log(const Poco::Message& msg); - MsgList& list(); - void clear(); - -private: - MsgList _msgList; -}; - - -#endif // TestChannel_INCLUDED +// +// TestChannel.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/TestChannel.h#1 $ +// +// Definition of the TestChannel class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 TestChannel_INCLUDED +#define TestChannel_INCLUDED + + +#include "Poco/Channel.h" +#include "Poco/Message.h" +#include + + +class TestChannel: public Poco::Channel +{ +public: + typedef std::list MsgList; + + TestChannel(); + ~TestChannel(); + + void log(const Poco::Message& msg); + MsgList& list(); + void clear(); + +private: + MsgList _msgList; +}; + + +#endif // TestChannel_INCLUDED diff --git a/Foundation/testsuite/src/TestLibrary.cpp b/Foundation/testsuite/src/TestLibrary.cpp index 395194fad..072838740 100644 --- a/Foundation/testsuite/src/TestLibrary.cpp +++ b/Foundation/testsuite/src/TestLibrary.cpp @@ -1,117 +1,117 @@ -// -// TestLibrary.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/TestLibrary.cpp#1 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "TestPlugin.h" -#include "Poco/ClassLibrary.h" -#include - - -extern "C" int POCO_LIBRARY_API gimmeFive(); - - -class PluginA: public TestPlugin -{ -public: - PluginA() - { - } - - ~PluginA() - { - } - - std::string name() const - { - return "PluginA"; - } -}; - - -class PluginB: public TestPlugin -{ -public: - PluginB() - { - } - - ~PluginB() - { - } - - std::string name() const - { - return "PluginB"; - } -}; - - -class PluginC: public TestPlugin -{ -public: - PluginC() - { - } - - ~PluginC() - { - } - - std::string name() const - { - return "PluginC"; - } -}; - - -POCO_BEGIN_MANIFEST(TestPlugin) - POCO_EXPORT_CLASS(PluginA) - POCO_EXPORT_CLASS(PluginB) - POCO_EXPORT_SINGLETON(PluginC) -POCO_END_MANIFEST - - -void pocoInitializeLibrary() -{ - std::cout << "TestLibrary initializing" << std::endl; -} - - -void pocoUninitializeLibrary() -{ - std::cout << "TestLibrary uninitialzing" << std::endl; -} - - -int gimmeFive() -{ - return 5; -} +// +// TestLibrary.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/TestLibrary.cpp#1 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "TestPlugin.h" +#include "Poco/ClassLibrary.h" +#include + + +extern "C" int POCO_LIBRARY_API gimmeFive(); + + +class PluginA: public TestPlugin +{ +public: + PluginA() + { + } + + ~PluginA() + { + } + + std::string name() const + { + return "PluginA"; + } +}; + + +class PluginB: public TestPlugin +{ +public: + PluginB() + { + } + + ~PluginB() + { + } + + std::string name() const + { + return "PluginB"; + } +}; + + +class PluginC: public TestPlugin +{ +public: + PluginC() + { + } + + ~PluginC() + { + } + + std::string name() const + { + return "PluginC"; + } +}; + + +POCO_BEGIN_MANIFEST(TestPlugin) + POCO_EXPORT_CLASS(PluginA) + POCO_EXPORT_CLASS(PluginB) + POCO_EXPORT_SINGLETON(PluginC) +POCO_END_MANIFEST + + +void pocoInitializeLibrary() +{ + std::cout << "TestLibrary initializing" << std::endl; +} + + +void pocoUninitializeLibrary() +{ + std::cout << "TestLibrary uninitialzing" << std::endl; +} + + +int gimmeFive() +{ + return 5; +} diff --git a/Foundation/testsuite/src/TestPlugin.cpp b/Foundation/testsuite/src/TestPlugin.cpp index 052c3c703..728e8d5a0 100644 --- a/Foundation/testsuite/src/TestPlugin.cpp +++ b/Foundation/testsuite/src/TestPlugin.cpp @@ -1,43 +1,43 @@ -// -// TestPlugin.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/TestPlugin.cpp#1 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "TestPlugin.h" - - -TestPlugin::TestPlugin() -{ -} - - -TestPlugin::~TestPlugin() -{ -} +// +// TestPlugin.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/TestPlugin.cpp#1 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "TestPlugin.h" + + +TestPlugin::TestPlugin() +{ +} + + +TestPlugin::~TestPlugin() +{ +} diff --git a/Foundation/testsuite/src/TestPlugin.h b/Foundation/testsuite/src/TestPlugin.h index abc8b4307..43d8ed662 100644 --- a/Foundation/testsuite/src/TestPlugin.h +++ b/Foundation/testsuite/src/TestPlugin.h @@ -1,51 +1,51 @@ -// -// TestPlugin.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/TestPlugin.h#1 $ -// -// Definition of the TestPlugin class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 TestPlugin_INCLUDED -#define TestPlugin_INCLUDED - - -#include "Poco/Foundation.h" - - -class TestPlugin -{ -public: - TestPlugin(); - virtual ~TestPlugin(); - virtual std::string name() const = 0; -}; - - -#endif // TestPlugin_INCLUDED +// +// TestPlugin.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/TestPlugin.h#1 $ +// +// Definition of the TestPlugin class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 TestPlugin_INCLUDED +#define TestPlugin_INCLUDED + + +#include "Poco/Foundation.h" + + +class TestPlugin +{ +public: + TestPlugin(); + virtual ~TestPlugin(); + virtual std::string name() const = 0; +}; + + +#endif // TestPlugin_INCLUDED diff --git a/Foundation/testsuite/src/TextConverterTest.cpp b/Foundation/testsuite/src/TextConverterTest.cpp index ffb8b8e65..c91cfa71f 100644 --- a/Foundation/testsuite/src/TextConverterTest.cpp +++ b/Foundation/testsuite/src/TextConverterTest.cpp @@ -1,240 +1,240 @@ -// -// TextConverterTest.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/TextConverterTest.cpp#1 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "TextConverterTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/TextConverter.h" -#include "Poco/ASCIIEncoding.h" -#include "Poco/Latin1Encoding.h" -#include "Poco/UTF8Encoding.h" - - -using Poco::TextConverter; -using Poco::Latin1Encoding; -using Poco::UTF8Encoding; -using Poco::ASCIIEncoding; - - -TextConverterTest::TextConverterTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -TextConverterTest::~TextConverterTest() -{ -} - - -void TextConverterTest::testIdentityASCII() -{ - ASCIIEncoding encoding; - TextConverter converter(encoding, encoding); - - std::string empty; - std::string result0; - int errors = converter.convert(empty, result0); - assert (result0 == empty); - assert (errors == 0); - - std::string fooBar = "foo bar"; - std::string result1; - errors = converter.convert(fooBar, result1); - assert (result1 == fooBar); - assert (errors == 0); - - std::string result2; - errors = converter.convert(fooBar.data(), (int) fooBar.length(), result2); - assert (result2 == fooBar); - assert (errors == 0); - - std::string result3; - errors = converter.convert("", 0, result3); - assert (result3.empty()); - assert (errors == 0); - - std::string x = "x"; - std::string result4; - errors = converter.convert(x, result4); - assert (result4 == x); - assert (errors == 0); - - std::string result5; - errors = converter.convert("x", 1, result5); - assert (result5 == x); - assert (errors == 0); -} - - -void TextConverterTest::testIdentityUTF8() -{ - UTF8Encoding encoding; - TextConverter converter(encoding, encoding); - - std::string empty; - std::string result0; - int errors = converter.convert(empty, result0); - assert (result0 == empty); - assert (errors == 0); - - std::string fooBar = "foo bar"; - std::string result1; - errors = converter.convert(fooBar, result1); - assert (result1 == fooBar); - assert (errors == 0); - - std::string result2; - errors = converter.convert(fooBar.data(), (int) fooBar.length(), result2); - assert (result2 == fooBar); - assert (errors == 0); - - std::string result3; - errors = converter.convert("", 0, result3); - assert (result3.empty()); - assert (errors == 0); - - const unsigned char greek[] = {0x20, 0xce, 0xba, 0xe1, 0xbd, 0xb9, 0xcf, 0x83, 0xce, 0xbc, 0xce, 0xb5, 0x20, 0x00}; - std::string text((const char*) greek); - - std::string result4; - errors = converter.convert(text, result4); - assert (result4 == text); - assert (errors == 0); - - std::string result5; - errors = converter.convert((char*) greek, 13, result5); - assert (result5 == text); - assert (errors == 0); - - std::string x = "x"; - std::string result6; - errors = converter.convert(x, result6); - assert (result6 == x); - assert (errors == 0); - - std::string result7; - errors = converter.convert("x", 1, result7); - assert (result7 == x); - assert (errors == 0); - - std::string utfChar((char*) greek + 1, 2); - std::string result8; - errors = converter.convert(utfChar, result8); - assert (result8 == utfChar); - assert (errors == 0); - - std::string result9; - errors = converter.convert((char*) greek + 1, 2, result9); - assert (result9 == utfChar); - assert (errors == 0); -} - - -void TextConverterTest::testUTF8toASCII() -{ - UTF8Encoding utf8Encoding; - ASCIIEncoding asciiEncoding; - TextConverter converter(utf8Encoding, asciiEncoding); - - const unsigned char greek[] = {0x20, 0xce, 0xba, 0xe1, 0xbd, 0xb9, 0xcf, 0x83, 0xce, 0xbc, 0xce, 0xb5, 0x20, 0x41, 0x42, 0x00}; - std::string text((const char*) greek); - std::string result0; - int errors = converter.convert(text, result0); - assert (result0 == " ????? AB"); - assert (errors == 0); - - std::string result1; - errors = converter.convert("abcde", 5, result1); - assert (result1 == "abcde"); -} - - -void TextConverterTest::testLatin1toUTF8() -{ - Latin1Encoding latin1Encoding; - UTF8Encoding utf8Encoding; - TextConverter converter(latin1Encoding, utf8Encoding); - - const unsigned char latin1Chars[] = {'g', 252, 'n', 't', 'e', 'r', 0}; - const unsigned char utf8Chars[] = {'g', 195, 188, 'n', 't', 'e', 'r', 0}; - std::string latin1Text((const char*) latin1Chars); - std::string utf8Text((const char*) utf8Chars); - - std::string result0; - int errors = converter.convert(latin1Text, result0); - assert (result0 == utf8Text); - assert (errors == 0); - - std::string result1; - errors = converter.convert(latin1Chars, 6, result1); - assert (result0 == utf8Text); - assert (errors == 0); -} - - -void TextConverterTest::testErrors() -{ - UTF8Encoding utf8Encoding; - Latin1Encoding latin1Encoding; - TextConverter converter(utf8Encoding, latin1Encoding); - - const unsigned char badChars[] = {'a', 'b', 255, 'c', 254, 0}; - std::string badText((const char*) badChars); - - std::string result; - int errors = converter.convert(badText, result); - assert (errors == 2); -} - - -void TextConverterTest::setUp() -{ -} - - -void TextConverterTest::tearDown() -{ -} - - -CppUnit::Test* TextConverterTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("TextConverterTest"); - - CppUnit_addTest(pSuite, TextConverterTest, testIdentityASCII); - CppUnit_addTest(pSuite, TextConverterTest, testIdentityUTF8); - CppUnit_addTest(pSuite, TextConverterTest, testUTF8toASCII); - CppUnit_addTest(pSuite, TextConverterTest, testLatin1toUTF8); - CppUnit_addTest(pSuite, TextConverterTest, testErrors); - - return pSuite; -} +// +// TextConverterTest.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/TextConverterTest.cpp#1 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "TextConverterTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/TextConverter.h" +#include "Poco/ASCIIEncoding.h" +#include "Poco/Latin1Encoding.h" +#include "Poco/UTF8Encoding.h" + + +using Poco::TextConverter; +using Poco::Latin1Encoding; +using Poco::UTF8Encoding; +using Poco::ASCIIEncoding; + + +TextConverterTest::TextConverterTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +TextConverterTest::~TextConverterTest() +{ +} + + +void TextConverterTest::testIdentityASCII() +{ + ASCIIEncoding encoding; + TextConverter converter(encoding, encoding); + + std::string empty; + std::string result0; + int errors = converter.convert(empty, result0); + assert (result0 == empty); + assert (errors == 0); + + std::string fooBar = "foo bar"; + std::string result1; + errors = converter.convert(fooBar, result1); + assert (result1 == fooBar); + assert (errors == 0); + + std::string result2; + errors = converter.convert(fooBar.data(), (int) fooBar.length(), result2); + assert (result2 == fooBar); + assert (errors == 0); + + std::string result3; + errors = converter.convert("", 0, result3); + assert (result3.empty()); + assert (errors == 0); + + std::string x = "x"; + std::string result4; + errors = converter.convert(x, result4); + assert (result4 == x); + assert (errors == 0); + + std::string result5; + errors = converter.convert("x", 1, result5); + assert (result5 == x); + assert (errors == 0); +} + + +void TextConverterTest::testIdentityUTF8() +{ + UTF8Encoding encoding; + TextConverter converter(encoding, encoding); + + std::string empty; + std::string result0; + int errors = converter.convert(empty, result0); + assert (result0 == empty); + assert (errors == 0); + + std::string fooBar = "foo bar"; + std::string result1; + errors = converter.convert(fooBar, result1); + assert (result1 == fooBar); + assert (errors == 0); + + std::string result2; + errors = converter.convert(fooBar.data(), (int) fooBar.length(), result2); + assert (result2 == fooBar); + assert (errors == 0); + + std::string result3; + errors = converter.convert("", 0, result3); + assert (result3.empty()); + assert (errors == 0); + + const unsigned char greek[] = {0x20, 0xce, 0xba, 0xe1, 0xbd, 0xb9, 0xcf, 0x83, 0xce, 0xbc, 0xce, 0xb5, 0x20, 0x00}; + std::string text((const char*) greek); + + std::string result4; + errors = converter.convert(text, result4); + assert (result4 == text); + assert (errors == 0); + + std::string result5; + errors = converter.convert((char*) greek, 13, result5); + assert (result5 == text); + assert (errors == 0); + + std::string x = "x"; + std::string result6; + errors = converter.convert(x, result6); + assert (result6 == x); + assert (errors == 0); + + std::string result7; + errors = converter.convert("x", 1, result7); + assert (result7 == x); + assert (errors == 0); + + std::string utfChar((char*) greek + 1, 2); + std::string result8; + errors = converter.convert(utfChar, result8); + assert (result8 == utfChar); + assert (errors == 0); + + std::string result9; + errors = converter.convert((char*) greek + 1, 2, result9); + assert (result9 == utfChar); + assert (errors == 0); +} + + +void TextConverterTest::testUTF8toASCII() +{ + UTF8Encoding utf8Encoding; + ASCIIEncoding asciiEncoding; + TextConverter converter(utf8Encoding, asciiEncoding); + + const unsigned char greek[] = {0x20, 0xce, 0xba, 0xe1, 0xbd, 0xb9, 0xcf, 0x83, 0xce, 0xbc, 0xce, 0xb5, 0x20, 0x41, 0x42, 0x00}; + std::string text((const char*) greek); + std::string result0; + int errors = converter.convert(text, result0); + assert (result0 == " ????? AB"); + assert (errors == 0); + + std::string result1; + errors = converter.convert("abcde", 5, result1); + assert (result1 == "abcde"); +} + + +void TextConverterTest::testLatin1toUTF8() +{ + Latin1Encoding latin1Encoding; + UTF8Encoding utf8Encoding; + TextConverter converter(latin1Encoding, utf8Encoding); + + const unsigned char latin1Chars[] = {'g', 252, 'n', 't', 'e', 'r', 0}; + const unsigned char utf8Chars[] = {'g', 195, 188, 'n', 't', 'e', 'r', 0}; + std::string latin1Text((const char*) latin1Chars); + std::string utf8Text((const char*) utf8Chars); + + std::string result0; + int errors = converter.convert(latin1Text, result0); + assert (result0 == utf8Text); + assert (errors == 0); + + std::string result1; + errors = converter.convert(latin1Chars, 6, result1); + assert (result0 == utf8Text); + assert (errors == 0); +} + + +void TextConverterTest::testErrors() +{ + UTF8Encoding utf8Encoding; + Latin1Encoding latin1Encoding; + TextConverter converter(utf8Encoding, latin1Encoding); + + const unsigned char badChars[] = {'a', 'b', 255, 'c', 254, 0}; + std::string badText((const char*) badChars); + + std::string result; + int errors = converter.convert(badText, result); + assert (errors == 2); +} + + +void TextConverterTest::setUp() +{ +} + + +void TextConverterTest::tearDown() +{ +} + + +CppUnit::Test* TextConverterTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("TextConverterTest"); + + CppUnit_addTest(pSuite, TextConverterTest, testIdentityASCII); + CppUnit_addTest(pSuite, TextConverterTest, testIdentityUTF8); + CppUnit_addTest(pSuite, TextConverterTest, testUTF8toASCII); + CppUnit_addTest(pSuite, TextConverterTest, testLatin1toUTF8); + CppUnit_addTest(pSuite, TextConverterTest, testErrors); + + return pSuite; +} diff --git a/Foundation/testsuite/src/TextConverterTest.h b/Foundation/testsuite/src/TextConverterTest.h index 22ffb0691..4714cdec8 100644 --- a/Foundation/testsuite/src/TextConverterTest.h +++ b/Foundation/testsuite/src/TextConverterTest.h @@ -1,64 +1,64 @@ -// -// TextConverterTest.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/TextConverterTest.h#1 $ -// -// Definition of the TextConverterTest class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 TextConverterTest_INCLUDED -#define TextConverterTest_INCLUDED - - -#include "Poco/Foundation.h" -#include "CppUnit/TestCase.h" - - -class TextConverterTest: public CppUnit::TestCase -{ -public: - TextConverterTest(const std::string& name); - ~TextConverterTest(); - - void testIdentityASCII(); - void testIdentityUTF8(); - void testUTF8toASCII(); - void testLatin1toUTF8(); - void testErrors(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // TextConverterTest_INCLUDED +// +// TextConverterTest.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/TextConverterTest.h#1 $ +// +// Definition of the TextConverterTest class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 TextConverterTest_INCLUDED +#define TextConverterTest_INCLUDED + + +#include "Poco/Foundation.h" +#include "CppUnit/TestCase.h" + + +class TextConverterTest: public CppUnit::TestCase +{ +public: + TextConverterTest(const std::string& name); + ~TextConverterTest(); + + void testIdentityASCII(); + void testIdentityUTF8(); + void testUTF8toASCII(); + void testLatin1toUTF8(); + void testErrors(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // TextConverterTest_INCLUDED diff --git a/Foundation/testsuite/src/TextIteratorTest.cpp b/Foundation/testsuite/src/TextIteratorTest.cpp index 599aa1ff6..58e16c61e 100644 --- a/Foundation/testsuite/src/TextIteratorTest.cpp +++ b/Foundation/testsuite/src/TextIteratorTest.cpp @@ -1,258 +1,258 @@ -// -// TextIteratorTest.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/TextIteratorTest.cpp#1 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "TextIteratorTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/TextIterator.h" -#include "Poco/Latin1Encoding.h" -#include "Poco/UTF8Encoding.h" - - -using Poco::TextIterator; -using Poco::Latin1Encoding; -using Poco::UTF8Encoding; - - -TextIteratorTest::TextIteratorTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -TextIteratorTest::~TextIteratorTest() -{ -} - - -void TextIteratorTest::testEmptyLatin1() -{ - Latin1Encoding encoding; - std::string text; - TextIterator it(text, encoding); - TextIterator end(text); - - assert (it == end); -} - - -void TextIteratorTest::testOneLatin1() -{ - Latin1Encoding encoding; - std::string text("x"); - TextIterator it(text, encoding); - TextIterator end(text); - - assert (it != end); - assert (*it == 'x'); - ++it; - assert (it == end); -} - - -void TextIteratorTest::testLatin1() -{ - Latin1Encoding encoding; - std::string text("Latin1"); - TextIterator it(text, encoding); - TextIterator end(text); - - assert (it != end); - assert (*it++ == 'L'); - assert (it != end); - assert (*it++ == 'a'); - assert (it != end); - assert (*it++ == 't'); - assert (it != end); - assert (*it++ == 'i'); - assert (it != end); - assert (*it++ == 'n'); - assert (it != end); - assert (*it++ == '1'); - assert (it == end); - - std::string empty; - it = TextIterator(empty, encoding); - end = TextIterator(empty); - assert (it == end); -} - - -void TextIteratorTest::testEmptyUTF8() -{ - UTF8Encoding encoding; - std::string text; - TextIterator it(text, encoding); - TextIterator end(text); - - assert (it == end); -} - - -void TextIteratorTest::testOneUTF8() -{ - UTF8Encoding encoding; - - // 1 byte sequence - std::string text("x"); - TextIterator it(text, encoding); - TextIterator end(text); - - assert (it != end); - assert (*it == 'x'); - ++it; - assert (it == end); - - unsigned char data[Poco::TextEncoding::MAX_SEQUENCE_LENGTH]; - - // 2 byte sequence - int n = encoding.convert(0xab, data, sizeof(data)); - assert (n == 2); - text.assign((char*) data, n); - it = TextIterator(text, encoding); - end = TextIterator(text); - - assert (it != end); - assert (*it++ == 0xab); - assert (it == end); - - // 3 byte sequence - n = encoding.convert(0xabcd, data, sizeof(data)); - assert (n == 3); - text.assign((char*) data, n); - it = TextIterator(text, encoding); - end = TextIterator(text); - - assert (it != end); - assert (*it++ == 0xabcd); - assert (it == end); - - // 4 byte sequence - n = encoding.convert(0xabcde, data, sizeof(data)); - assert (n == 4); - text.assign((char*) data, n); - it = TextIterator(text, encoding); - end = TextIterator(text); - - assert (it != end); - assert (*it++ == 0xabcde); - assert (it == end); - - // 5 byte sequence - n = encoding.convert(0xabcdef, data, sizeof(data)); - assert (n == 5); - text.assign((char*) data, n); - it = TextIterator(text, encoding); - end = TextIterator(text); - - assert (it != end); - assert (*it++ == 0xabcdef); - assert (it == end); - - // 6 byte sequence - n = encoding.convert(0xfabcdef, data, sizeof(data)); - assert (n == 6); - text.assign((char*) data, n); - it = TextIterator(text, encoding); - end = TextIterator(text); - - assert (it != end); - assert (*it++ == 0xfabcdef); - assert (it == end); -} - - -void TextIteratorTest::testUTF8() -{ - UTF8Encoding encoding; - const unsigned char greek[] = {0x20, 0xce, 0xba, 0xe1, 0xbd, 0xb9, 0xcf, 0x83, 0xce, 0xbc, 0xce, 0xb5, 0x20, 0x00}; - std::string text((const char*) greek); - TextIterator it(text, encoding); - TextIterator end(text); - - assert (it != end); - assert (*it++ == 0x0020); - assert (it != end); - assert (*it++ == 0x03ba); - assert (it != end); - assert (*it++ == 0x1f79); - assert (it != end); - assert (*it++ == 0x03c3); - assert (it != end); - assert (*it++ == 0x03bc); - assert (it != end); - assert (*it++ == 0x03b5); - assert (it != end); - assert (*it++ == 0x0020); - assert (it == end); -} - - -void TextIteratorTest::testSwap() -{ - Latin1Encoding encoding; - std::string text("x"); - TextIterator it1(text, encoding); - TextIterator it2(text, encoding); - TextIterator end(text); - - assert (it1 == it2); - it2.swap(end); - assert (it1 != it2); - it2.swap(end); - assert (it1 == it2); -} - - -void TextIteratorTest::setUp() -{ -} - - -void TextIteratorTest::tearDown() -{ -} - - -CppUnit::Test* TextIteratorTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("TextIteratorTest"); - - CppUnit_addTest(pSuite, TextIteratorTest, testEmptyLatin1); - CppUnit_addTest(pSuite, TextIteratorTest, testOneLatin1); - CppUnit_addTest(pSuite, TextIteratorTest, testLatin1); - CppUnit_addTest(pSuite, TextIteratorTest, testEmptyUTF8); - CppUnit_addTest(pSuite, TextIteratorTest, testOneUTF8); - CppUnit_addTest(pSuite, TextIteratorTest, testUTF8); - CppUnit_addTest(pSuite, TextIteratorTest, testSwap); - - return pSuite; -} +// +// TextIteratorTest.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/TextIteratorTest.cpp#1 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "TextIteratorTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/TextIterator.h" +#include "Poco/Latin1Encoding.h" +#include "Poco/UTF8Encoding.h" + + +using Poco::TextIterator; +using Poco::Latin1Encoding; +using Poco::UTF8Encoding; + + +TextIteratorTest::TextIteratorTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +TextIteratorTest::~TextIteratorTest() +{ +} + + +void TextIteratorTest::testEmptyLatin1() +{ + Latin1Encoding encoding; + std::string text; + TextIterator it(text, encoding); + TextIterator end(text); + + assert (it == end); +} + + +void TextIteratorTest::testOneLatin1() +{ + Latin1Encoding encoding; + std::string text("x"); + TextIterator it(text, encoding); + TextIterator end(text); + + assert (it != end); + assert (*it == 'x'); + ++it; + assert (it == end); +} + + +void TextIteratorTest::testLatin1() +{ + Latin1Encoding encoding; + std::string text("Latin1"); + TextIterator it(text, encoding); + TextIterator end(text); + + assert (it != end); + assert (*it++ == 'L'); + assert (it != end); + assert (*it++ == 'a'); + assert (it != end); + assert (*it++ == 't'); + assert (it != end); + assert (*it++ == 'i'); + assert (it != end); + assert (*it++ == 'n'); + assert (it != end); + assert (*it++ == '1'); + assert (it == end); + + std::string empty; + it = TextIterator(empty, encoding); + end = TextIterator(empty); + assert (it == end); +} + + +void TextIteratorTest::testEmptyUTF8() +{ + UTF8Encoding encoding; + std::string text; + TextIterator it(text, encoding); + TextIterator end(text); + + assert (it == end); +} + + +void TextIteratorTest::testOneUTF8() +{ + UTF8Encoding encoding; + + // 1 byte sequence + std::string text("x"); + TextIterator it(text, encoding); + TextIterator end(text); + + assert (it != end); + assert (*it == 'x'); + ++it; + assert (it == end); + + unsigned char data[Poco::TextEncoding::MAX_SEQUENCE_LENGTH]; + + // 2 byte sequence + int n = encoding.convert(0xab, data, sizeof(data)); + assert (n == 2); + text.assign((char*) data, n); + it = TextIterator(text, encoding); + end = TextIterator(text); + + assert (it != end); + assert (*it++ == 0xab); + assert (it == end); + + // 3 byte sequence + n = encoding.convert(0xabcd, data, sizeof(data)); + assert (n == 3); + text.assign((char*) data, n); + it = TextIterator(text, encoding); + end = TextIterator(text); + + assert (it != end); + assert (*it++ == 0xabcd); + assert (it == end); + + // 4 byte sequence + n = encoding.convert(0xabcde, data, sizeof(data)); + assert (n == 4); + text.assign((char*) data, n); + it = TextIterator(text, encoding); + end = TextIterator(text); + + assert (it != end); + assert (*it++ == 0xabcde); + assert (it == end); + + // 5 byte sequence + n = encoding.convert(0xabcdef, data, sizeof(data)); + assert (n == 5); + text.assign((char*) data, n); + it = TextIterator(text, encoding); + end = TextIterator(text); + + assert (it != end); + assert (*it++ == 0xabcdef); + assert (it == end); + + // 6 byte sequence + n = encoding.convert(0xfabcdef, data, sizeof(data)); + assert (n == 6); + text.assign((char*) data, n); + it = TextIterator(text, encoding); + end = TextIterator(text); + + assert (it != end); + assert (*it++ == 0xfabcdef); + assert (it == end); +} + + +void TextIteratorTest::testUTF8() +{ + UTF8Encoding encoding; + const unsigned char greek[] = {0x20, 0xce, 0xba, 0xe1, 0xbd, 0xb9, 0xcf, 0x83, 0xce, 0xbc, 0xce, 0xb5, 0x20, 0x00}; + std::string text((const char*) greek); + TextIterator it(text, encoding); + TextIterator end(text); + + assert (it != end); + assert (*it++ == 0x0020); + assert (it != end); + assert (*it++ == 0x03ba); + assert (it != end); + assert (*it++ == 0x1f79); + assert (it != end); + assert (*it++ == 0x03c3); + assert (it != end); + assert (*it++ == 0x03bc); + assert (it != end); + assert (*it++ == 0x03b5); + assert (it != end); + assert (*it++ == 0x0020); + assert (it == end); +} + + +void TextIteratorTest::testSwap() +{ + Latin1Encoding encoding; + std::string text("x"); + TextIterator it1(text, encoding); + TextIterator it2(text, encoding); + TextIterator end(text); + + assert (it1 == it2); + it2.swap(end); + assert (it1 != it2); + it2.swap(end); + assert (it1 == it2); +} + + +void TextIteratorTest::setUp() +{ +} + + +void TextIteratorTest::tearDown() +{ +} + + +CppUnit::Test* TextIteratorTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("TextIteratorTest"); + + CppUnit_addTest(pSuite, TextIteratorTest, testEmptyLatin1); + CppUnit_addTest(pSuite, TextIteratorTest, testOneLatin1); + CppUnit_addTest(pSuite, TextIteratorTest, testLatin1); + CppUnit_addTest(pSuite, TextIteratorTest, testEmptyUTF8); + CppUnit_addTest(pSuite, TextIteratorTest, testOneUTF8); + CppUnit_addTest(pSuite, TextIteratorTest, testUTF8); + CppUnit_addTest(pSuite, TextIteratorTest, testSwap); + + return pSuite; +} diff --git a/Foundation/testsuite/src/TextIteratorTest.h b/Foundation/testsuite/src/TextIteratorTest.h index 066c1f2b7..fe0e0d470 100644 --- a/Foundation/testsuite/src/TextIteratorTest.h +++ b/Foundation/testsuite/src/TextIteratorTest.h @@ -1,66 +1,66 @@ -// -// TextIteratorTest.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/TextIteratorTest.h#1 $ -// -// Definition of the TextIteratorTest class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 TextIteratorTest_INCLUDED -#define TextIteratorTest_INCLUDED - - -#include "Poco/Foundation.h" -#include "CppUnit/TestCase.h" - - -class TextIteratorTest: public CppUnit::TestCase -{ -public: - TextIteratorTest(const std::string& name); - ~TextIteratorTest(); - - void testEmptyLatin1(); - void testOneLatin1(); - void testLatin1(); - void testEmptyUTF8(); - void testOneUTF8(); - void testUTF8(); - void testSwap(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // TextIteratorTest_INCLUDED +// +// TextIteratorTest.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/TextIteratorTest.h#1 $ +// +// Definition of the TextIteratorTest class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 TextIteratorTest_INCLUDED +#define TextIteratorTest_INCLUDED + + +#include "Poco/Foundation.h" +#include "CppUnit/TestCase.h" + + +class TextIteratorTest: public CppUnit::TestCase +{ +public: + TextIteratorTest(const std::string& name); + ~TextIteratorTest(); + + void testEmptyLatin1(); + void testOneLatin1(); + void testLatin1(); + void testEmptyUTF8(); + void testOneUTF8(); + void testUTF8(); + void testSwap(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // TextIteratorTest_INCLUDED diff --git a/Foundation/testsuite/src/TextTestSuite.cpp b/Foundation/testsuite/src/TextTestSuite.cpp index 4dd516547..02b348e12 100644 --- a/Foundation/testsuite/src/TextTestSuite.cpp +++ b/Foundation/testsuite/src/TextTestSuite.cpp @@ -1,48 +1,48 @@ -// -// TextTestSuite.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/TextTestSuite.cpp#1 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "TextTestSuite.h" -#include "TextIteratorTest.h" -#include "TextConverterTest.h" -#include "StreamConverterTest.h" - - -CppUnit::Test* TextTestSuite::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("TextTestSuite"); - - pSuite->addTest(TextIteratorTest::suite()); - pSuite->addTest(TextConverterTest::suite()); - pSuite->addTest(StreamConverterTest::suite()); - - return pSuite; -} +// +// TextTestSuite.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/TextTestSuite.cpp#1 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "TextTestSuite.h" +#include "TextIteratorTest.h" +#include "TextConverterTest.h" +#include "StreamConverterTest.h" + + +CppUnit::Test* TextTestSuite::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("TextTestSuite"); + + pSuite->addTest(TextIteratorTest::suite()); + pSuite->addTest(TextConverterTest::suite()); + pSuite->addTest(StreamConverterTest::suite()); + + return pSuite; +} diff --git a/Foundation/testsuite/src/TextTestSuite.h b/Foundation/testsuite/src/TextTestSuite.h index ee267df39..56ea3e24a 100644 --- a/Foundation/testsuite/src/TextTestSuite.h +++ b/Foundation/testsuite/src/TextTestSuite.h @@ -1,49 +1,49 @@ -// -// TextTestSuite.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/TextTestSuite.h#1 $ -// -// Definition of the TextTestSuite class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 TextTestSuite_INCLUDED -#define TextTestSuite_INCLUDED - - -#include "CppUnit/TestSuite.h" - - -class TextTestSuite -{ -public: - static CppUnit::Test* suite(); -}; - - -#endif // TextTestSuite_INCLUDED +// +// TextTestSuite.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/TextTestSuite.h#1 $ +// +// Definition of the TextTestSuite class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 TextTestSuite_INCLUDED +#define TextTestSuite_INCLUDED + + +#include "CppUnit/TestSuite.h" + + +class TextTestSuite +{ +public: + static CppUnit::Test* suite(); +}; + + +#endif // TextTestSuite_INCLUDED diff --git a/Foundation/testsuite/src/ThreadLocalTest.cpp b/Foundation/testsuite/src/ThreadLocalTest.cpp index 77501a0f1..d0314caef 100644 --- a/Foundation/testsuite/src/ThreadLocalTest.cpp +++ b/Foundation/testsuite/src/ThreadLocalTest.cpp @@ -1,144 +1,144 @@ -// -// ThreadLocalTest.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/ThreadLocalTest.cpp#1 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "ThreadLocalTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/ThreadLocal.h" -#include "Poco/Thread.h" -#include "Poco/Runnable.h" - - -using Poco::ThreadLocal; -using Poco::Thread; -using Poco::Runnable; - - -class TLTestRunnable: public Runnable -{ -public: - TLTestRunnable(int n): _n(n) - { - } - - void run() - { - *_count = 0; - for (int i = 0; i < _n; ++i) - ++(*_count); - _result = *_count; - } - - int result() - { - return _result; - } - -private: - int _n; - int _result; - static ThreadLocal _count; -}; - - -struct TLTestStruct -{ - int i; - std::string s; -}; - - -ThreadLocal TLTestRunnable::_count; - - -ThreadLocalTest::ThreadLocalTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -ThreadLocalTest::~ThreadLocalTest() -{ -} - - -void ThreadLocalTest::testLocality() -{ - TLTestRunnable r1(5000); - TLTestRunnable r2(7500); - TLTestRunnable r3(6000); - Thread t1; - Thread t2; - Thread t3; - t1.start(r1); - t2.start(r2); - t3.start(r3); - t1.join(); - t2.join(); - t3.join(); - - assert (r1.result() == 5000); - assert (r2.result() == 7500); - assert (r3.result() == 6000); -} - - -void ThreadLocalTest::testAccessors() -{ - ThreadLocal ts; - ts->i = 100; - ts->s = "foo"; - assert ((*ts).i == 100); - assert ((*ts).s == "foo"); - assert (ts.get().i == 100); - assert (ts.get().s == "foo"); -} - - -void ThreadLocalTest::setUp() -{ -} - - -void ThreadLocalTest::tearDown() -{ -} - - -CppUnit::Test* ThreadLocalTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("ThreadLocalTest"); - - CppUnit_addTest(pSuite, ThreadLocalTest, testLocality); - CppUnit_addTest(pSuite, ThreadLocalTest, testAccessors); - - return pSuite; -} +// +// ThreadLocalTest.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/ThreadLocalTest.cpp#1 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "ThreadLocalTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/ThreadLocal.h" +#include "Poco/Thread.h" +#include "Poco/Runnable.h" + + +using Poco::ThreadLocal; +using Poco::Thread; +using Poco::Runnable; + + +class TLTestRunnable: public Runnable +{ +public: + TLTestRunnable(int n): _n(n) + { + } + + void run() + { + *_count = 0; + for (int i = 0; i < _n; ++i) + ++(*_count); + _result = *_count; + } + + int result() + { + return _result; + } + +private: + int _n; + int _result; + static ThreadLocal _count; +}; + + +struct TLTestStruct +{ + int i; + std::string s; +}; + + +ThreadLocal TLTestRunnable::_count; + + +ThreadLocalTest::ThreadLocalTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +ThreadLocalTest::~ThreadLocalTest() +{ +} + + +void ThreadLocalTest::testLocality() +{ + TLTestRunnable r1(5000); + TLTestRunnable r2(7500); + TLTestRunnable r3(6000); + Thread t1; + Thread t2; + Thread t3; + t1.start(r1); + t2.start(r2); + t3.start(r3); + t1.join(); + t2.join(); + t3.join(); + + assert (r1.result() == 5000); + assert (r2.result() == 7500); + assert (r3.result() == 6000); +} + + +void ThreadLocalTest::testAccessors() +{ + ThreadLocal ts; + ts->i = 100; + ts->s = "foo"; + assert ((*ts).i == 100); + assert ((*ts).s == "foo"); + assert (ts.get().i == 100); + assert (ts.get().s == "foo"); +} + + +void ThreadLocalTest::setUp() +{ +} + + +void ThreadLocalTest::tearDown() +{ +} + + +CppUnit::Test* ThreadLocalTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("ThreadLocalTest"); + + CppUnit_addTest(pSuite, ThreadLocalTest, testLocality); + CppUnit_addTest(pSuite, ThreadLocalTest, testAccessors); + + return pSuite; +} diff --git a/Foundation/testsuite/src/ThreadLocalTest.h b/Foundation/testsuite/src/ThreadLocalTest.h index b6c45803f..7ec0e274a 100644 --- a/Foundation/testsuite/src/ThreadLocalTest.h +++ b/Foundation/testsuite/src/ThreadLocalTest.h @@ -1,61 +1,61 @@ -// -// ThreadLocalTest.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/ThreadLocalTest.h#1 $ -// -// Definition of the ThreadLocalTest class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 ThreadLocalTest_INCLUDED -#define ThreadLocalTest_INCLUDED - - -#include "Poco/Foundation.h" -#include "CppUnit/TestCase.h" - - -class ThreadLocalTest: public CppUnit::TestCase -{ -public: - ThreadLocalTest(const std::string& name); - ~ThreadLocalTest(); - - void testLocality(); - void testAccessors(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // ThreadLocalTest_INCLUDED +// +// ThreadLocalTest.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/ThreadLocalTest.h#1 $ +// +// Definition of the ThreadLocalTest class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 ThreadLocalTest_INCLUDED +#define ThreadLocalTest_INCLUDED + + +#include "Poco/Foundation.h" +#include "CppUnit/TestCase.h" + + +class ThreadLocalTest: public CppUnit::TestCase +{ +public: + ThreadLocalTest(const std::string& name); + ~ThreadLocalTest(); + + void testLocality(); + void testAccessors(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // ThreadLocalTest_INCLUDED diff --git a/Foundation/testsuite/src/ThreadPoolTest.cpp b/Foundation/testsuite/src/ThreadPoolTest.cpp index 78fdc3683..aa3b3d9fe 100644 --- a/Foundation/testsuite/src/ThreadPoolTest.cpp +++ b/Foundation/testsuite/src/ThreadPoolTest.cpp @@ -1,183 +1,183 @@ -// -// ThreadPoolTest.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/ThreadPoolTest.cpp#2 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "ThreadPoolTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/ThreadPool.h" -#include "Poco/RunnableAdapter.h" -#include "Poco/Exception.h" -#include "Poco/Thread.h" - - -using Poco::ThreadPool; -using Poco::RunnableAdapter; -using Poco::Thread; - - -ThreadPoolTest::ThreadPoolTest(const std::string& name): CppUnit::TestCase(name), _event(false) -{ -} - - -ThreadPoolTest::~ThreadPoolTest() -{ -} - - -void ThreadPoolTest::testThreadPool() -{ - ThreadPool pool(2, 3, 3); - - assert (pool.allocated() == 2); - assert (pool.used() == 0); - assert (pool.capacity() == 3); - assert (pool.available() == 3); - pool.addCapacity(1); - assert (pool.allocated() == 2); - assert (pool.used() == 0); - assert (pool.capacity() == 4); - assert (pool.available() == 4); - - RunnableAdapter ra(*this, &ThreadPoolTest::count); - pool.start(ra); - assert (pool.allocated() == 2); - assert (pool.used() == 1); - assert (pool.capacity() == 4); - assert (pool.available() == 3); - - pool.start(ra); - assert (pool.allocated() == 2); - assert (pool.used() == 2); - assert (pool.capacity() == 4); - assert (pool.available() == 2); - - pool.start(ra); - assert (pool.allocated() == 3); - assert (pool.used() == 3); - assert (pool.capacity() == 4); - assert (pool.available() == 1); - - pool.start(ra); - assert (pool.allocated() == 4); - assert (pool.used() == 4); - assert (pool.capacity() == 4); - assert (pool.available() == 0); - - try - { - pool.start(ra); - failmsg("thread pool exhausted - must throw exception"); - } - catch (Poco::NoThreadAvailableException&) - { - } - catch (...) - { - failmsg("wrong exception thrown"); - } - - _event.set(); // go!!! - pool.joinAll(); - - assert (_count == 40000); - - assert (pool.allocated() == 4); - assert (pool.used() == 0); - assert (pool.capacity() == 4); - assert (pool.available() == 4); - - Thread::sleep(4000); - - pool.collect(); - assert (pool.allocated() == 2); - assert (pool.used() == 0); - assert (pool.capacity() == 4); - assert (pool.available() == 4); - - _count = 0; - _event.reset(); - pool.start(ra); - assert (pool.allocated() == 2); - assert (pool.used() == 1); - assert (pool.capacity() == 4); - assert (pool.available() == 3); - - pool.start(ra); - assert (pool.allocated() == 2); - assert (pool.used() == 2); - assert (pool.capacity() == 4); - assert (pool.available() == 2); - _event.set(); // go!!! - pool.joinAll(); - - assert (_count == 20000); - - assert (pool.allocated() == 2); - assert (pool.used() == 0); - assert (pool.capacity() == 4); - assert (pool.available() == 4); -} - - -void ThreadPoolTest::setUp() -{ - _event.reset(); - _count = 0; -} - - -void ThreadPoolTest::tearDown() -{ -} - - -void ThreadPoolTest::count() -{ - _event.wait(); - for (int i = 0; i < 10000; ++i) - { - _mutex.lock(); - ++_count; - _mutex.unlock(); - } -} - - -CppUnit::Test* ThreadPoolTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("ThreadPoolTest"); - - CppUnit_addTest(pSuite, ThreadPoolTest, testThreadPool); - - return pSuite; -} +// +// ThreadPoolTest.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/ThreadPoolTest.cpp#2 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "ThreadPoolTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/ThreadPool.h" +#include "Poco/RunnableAdapter.h" +#include "Poco/Exception.h" +#include "Poco/Thread.h" + + +using Poco::ThreadPool; +using Poco::RunnableAdapter; +using Poco::Thread; + + +ThreadPoolTest::ThreadPoolTest(const std::string& name): CppUnit::TestCase(name), _event(false) +{ +} + + +ThreadPoolTest::~ThreadPoolTest() +{ +} + + +void ThreadPoolTest::testThreadPool() +{ + ThreadPool pool(2, 3, 3); + + assert (pool.allocated() == 2); + assert (pool.used() == 0); + assert (pool.capacity() == 3); + assert (pool.available() == 3); + pool.addCapacity(1); + assert (pool.allocated() == 2); + assert (pool.used() == 0); + assert (pool.capacity() == 4); + assert (pool.available() == 4); + + RunnableAdapter ra(*this, &ThreadPoolTest::count); + pool.start(ra); + assert (pool.allocated() == 2); + assert (pool.used() == 1); + assert (pool.capacity() == 4); + assert (pool.available() == 3); + + pool.start(ra); + assert (pool.allocated() == 2); + assert (pool.used() == 2); + assert (pool.capacity() == 4); + assert (pool.available() == 2); + + pool.start(ra); + assert (pool.allocated() == 3); + assert (pool.used() == 3); + assert (pool.capacity() == 4); + assert (pool.available() == 1); + + pool.start(ra); + assert (pool.allocated() == 4); + assert (pool.used() == 4); + assert (pool.capacity() == 4); + assert (pool.available() == 0); + + try + { + pool.start(ra); + failmsg("thread pool exhausted - must throw exception"); + } + catch (Poco::NoThreadAvailableException&) + { + } + catch (...) + { + failmsg("wrong exception thrown"); + } + + _event.set(); // go!!! + pool.joinAll(); + + assert (_count == 40000); + + assert (pool.allocated() == 4); + assert (pool.used() == 0); + assert (pool.capacity() == 4); + assert (pool.available() == 4); + + Thread::sleep(4000); + + pool.collect(); + assert (pool.allocated() == 2); + assert (pool.used() == 0); + assert (pool.capacity() == 4); + assert (pool.available() == 4); + + _count = 0; + _event.reset(); + pool.start(ra); + assert (pool.allocated() == 2); + assert (pool.used() == 1); + assert (pool.capacity() == 4); + assert (pool.available() == 3); + + pool.start(ra); + assert (pool.allocated() == 2); + assert (pool.used() == 2); + assert (pool.capacity() == 4); + assert (pool.available() == 2); + _event.set(); // go!!! + pool.joinAll(); + + assert (_count == 20000); + + assert (pool.allocated() == 2); + assert (pool.used() == 0); + assert (pool.capacity() == 4); + assert (pool.available() == 4); +} + + +void ThreadPoolTest::setUp() +{ + _event.reset(); + _count = 0; +} + + +void ThreadPoolTest::tearDown() +{ +} + + +void ThreadPoolTest::count() +{ + _event.wait(); + for (int i = 0; i < 10000; ++i) + { + _mutex.lock(); + ++_count; + _mutex.unlock(); + } +} + + +CppUnit::Test* ThreadPoolTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("ThreadPoolTest"); + + CppUnit_addTest(pSuite, ThreadPoolTest, testThreadPool); + + return pSuite; +} diff --git a/Foundation/testsuite/src/ThreadPoolTest.h b/Foundation/testsuite/src/ThreadPoolTest.h index 421a633c9..94a8b20d0 100644 --- a/Foundation/testsuite/src/ThreadPoolTest.h +++ b/Foundation/testsuite/src/ThreadPoolTest.h @@ -1,68 +1,68 @@ -// -// ThreadPoolTest.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/ThreadPoolTest.h#1 $ -// -// Definition of the ThreadPoolTest class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 ThreadPoolTest_INCLUDED -#define ThreadPoolTest_INCLUDED - - -#include "Poco/Foundation.h" -#include "CppUnit/TestCase.h" -#include "Poco/Event.h" -#include "Poco/Mutex.h" - - -class ThreadPoolTest: public CppUnit::TestCase -{ -public: - ThreadPoolTest(const std::string& name); - ~ThreadPoolTest(); - - void testThreadPool(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -protected: - void count(); - -private: - Poco::FastMutex _mutex; - Poco::Event _event; - int _count; -}; - - -#endif // ThreadPoolTest_INCLUDED +// +// ThreadPoolTest.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/ThreadPoolTest.h#1 $ +// +// Definition of the ThreadPoolTest class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 ThreadPoolTest_INCLUDED +#define ThreadPoolTest_INCLUDED + + +#include "Poco/Foundation.h" +#include "CppUnit/TestCase.h" +#include "Poco/Event.h" +#include "Poco/Mutex.h" + + +class ThreadPoolTest: public CppUnit::TestCase +{ +public: + ThreadPoolTest(const std::string& name); + ~ThreadPoolTest(); + + void testThreadPool(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +protected: + void count(); + +private: + Poco::FastMutex _mutex; + Poco::Event _event; + int _count; +}; + + +#endif // ThreadPoolTest_INCLUDED diff --git a/Foundation/testsuite/src/ThreadTest.cpp b/Foundation/testsuite/src/ThreadTest.cpp index 54cdd5dfb..1e6d434f5 100644 --- a/Foundation/testsuite/src/ThreadTest.cpp +++ b/Foundation/testsuite/src/ThreadTest.cpp @@ -1,203 +1,203 @@ -// -// ThreadTest.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/ThreadTest.cpp#1 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "ThreadTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/Thread.h" -#include "Poco/Runnable.h" -#include "Poco/Event.h" - - -using Poco::Thread; -using Poco::Runnable; -using Poco::Event; - - -class MyRunnable: public Runnable -{ -public: - MyRunnable(): _ran(false) - { - } - - void run() - { - Thread* pThread = Thread::current(); - if (pThread) - _threadName = pThread->name(); - _ran = true; - _event.wait(); - } - - bool ran() const - { - return _ran; - } - - const std::string& threadName() const - { - return _threadName; - } - - void notify() - { - _event.set(); - } - -private: - bool _ran; - std::string _threadName; - Event _event; -}; - - -ThreadTest::ThreadTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -ThreadTest::~ThreadTest() -{ -} - - -void ThreadTest::testThread() -{ - Thread thread; - MyRunnable r; - assert (!thread.isRunning()); - thread.start(r); - Thread::sleep(200); - assert (thread.isRunning()); - r.notify(); - thread.join(); - assert (!thread.isRunning()); - assert (r.ran()); - assert (!r.threadName().empty()); -} - - -void ThreadTest::testNamedThread() -{ - Thread thread("MyThread"); - MyRunnable r; - thread.start(r); - r.notify(); - thread.join(); - assert (r.ran()); - assert (r.threadName() == "MyThread"); -} - - -void ThreadTest::testCurrent() -{ - assertNullPtr (Thread::current()); -} - - -void ThreadTest::testThreads() -{ - Thread thread1("Thread1"); - Thread thread2("Thread2"); - Thread thread3("Thread3"); - Thread thread4("Thread4"); - - MyRunnable r1; - MyRunnable r2; - MyRunnable r3; - MyRunnable r4; - assert (!thread1.isRunning()); - assert (!thread2.isRunning()); - assert (!thread3.isRunning()); - assert (!thread4.isRunning()); - thread1.start(r1); - Thread::sleep(200); - assert (thread1.isRunning()); - assert (!thread2.isRunning()); - assert (!thread3.isRunning()); - assert (!thread4.isRunning()); - thread2.start(r2); - thread3.start(r3); - thread4.start(r4); - Thread::sleep(200); - assert (thread1.isRunning()); - assert (thread2.isRunning()); - assert (thread3.isRunning()); - assert (thread4.isRunning()); - r4.notify(); - thread4.join(); - assert (!thread4.isRunning()); - assert (thread1.isRunning()); - assert (thread2.isRunning()); - assert (thread3.isRunning()); - r3.notify(); - thread3.join(); - assert (!thread3.isRunning()); - r2.notify(); - thread2.join(); - assert (!thread2.isRunning()); - r1.notify(); - thread1.join(); - assert (!thread1.isRunning()); - assert (r1.ran()); - assert (r1.threadName() == "Thread1"); - assert (r2.ran()); - assert (r2.threadName() == "Thread2"); - assert (r3.ran()); - assert (r3.threadName() == "Thread3"); - assert (r4.ran()); - assert (r4.threadName() == "Thread4"); -} - - -void ThreadTest::setUp() -{ -} - - -void ThreadTest::tearDown() -{ -} - - -CppUnit::Test* ThreadTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("ThreadTest"); - - CppUnit_addTest(pSuite, ThreadTest, testThread); - CppUnit_addTest(pSuite, ThreadTest, testNamedThread); - CppUnit_addTest(pSuite, ThreadTest, testCurrent); - CppUnit_addTest(pSuite, ThreadTest, testThreads); - - return pSuite; -} +// +// ThreadTest.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/ThreadTest.cpp#1 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "ThreadTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/Thread.h" +#include "Poco/Runnable.h" +#include "Poco/Event.h" + + +using Poco::Thread; +using Poco::Runnable; +using Poco::Event; + + +class MyRunnable: public Runnable +{ +public: + MyRunnable(): _ran(false) + { + } + + void run() + { + Thread* pThread = Thread::current(); + if (pThread) + _threadName = pThread->name(); + _ran = true; + _event.wait(); + } + + bool ran() const + { + return _ran; + } + + const std::string& threadName() const + { + return _threadName; + } + + void notify() + { + _event.set(); + } + +private: + bool _ran; + std::string _threadName; + Event _event; +}; + + +ThreadTest::ThreadTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +ThreadTest::~ThreadTest() +{ +} + + +void ThreadTest::testThread() +{ + Thread thread; + MyRunnable r; + assert (!thread.isRunning()); + thread.start(r); + Thread::sleep(200); + assert (thread.isRunning()); + r.notify(); + thread.join(); + assert (!thread.isRunning()); + assert (r.ran()); + assert (!r.threadName().empty()); +} + + +void ThreadTest::testNamedThread() +{ + Thread thread("MyThread"); + MyRunnable r; + thread.start(r); + r.notify(); + thread.join(); + assert (r.ran()); + assert (r.threadName() == "MyThread"); +} + + +void ThreadTest::testCurrent() +{ + assertNullPtr (Thread::current()); +} + + +void ThreadTest::testThreads() +{ + Thread thread1("Thread1"); + Thread thread2("Thread2"); + Thread thread3("Thread3"); + Thread thread4("Thread4"); + + MyRunnable r1; + MyRunnable r2; + MyRunnable r3; + MyRunnable r4; + assert (!thread1.isRunning()); + assert (!thread2.isRunning()); + assert (!thread3.isRunning()); + assert (!thread4.isRunning()); + thread1.start(r1); + Thread::sleep(200); + assert (thread1.isRunning()); + assert (!thread2.isRunning()); + assert (!thread3.isRunning()); + assert (!thread4.isRunning()); + thread2.start(r2); + thread3.start(r3); + thread4.start(r4); + Thread::sleep(200); + assert (thread1.isRunning()); + assert (thread2.isRunning()); + assert (thread3.isRunning()); + assert (thread4.isRunning()); + r4.notify(); + thread4.join(); + assert (!thread4.isRunning()); + assert (thread1.isRunning()); + assert (thread2.isRunning()); + assert (thread3.isRunning()); + r3.notify(); + thread3.join(); + assert (!thread3.isRunning()); + r2.notify(); + thread2.join(); + assert (!thread2.isRunning()); + r1.notify(); + thread1.join(); + assert (!thread1.isRunning()); + assert (r1.ran()); + assert (r1.threadName() == "Thread1"); + assert (r2.ran()); + assert (r2.threadName() == "Thread2"); + assert (r3.ran()); + assert (r3.threadName() == "Thread3"); + assert (r4.ran()); + assert (r4.threadName() == "Thread4"); +} + + +void ThreadTest::setUp() +{ +} + + +void ThreadTest::tearDown() +{ +} + + +CppUnit::Test* ThreadTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("ThreadTest"); + + CppUnit_addTest(pSuite, ThreadTest, testThread); + CppUnit_addTest(pSuite, ThreadTest, testNamedThread); + CppUnit_addTest(pSuite, ThreadTest, testCurrent); + CppUnit_addTest(pSuite, ThreadTest, testThreads); + + return pSuite; +} diff --git a/Foundation/testsuite/src/ThreadTest.h b/Foundation/testsuite/src/ThreadTest.h index 6b8dc717b..08032c5ab 100644 --- a/Foundation/testsuite/src/ThreadTest.h +++ b/Foundation/testsuite/src/ThreadTest.h @@ -1,63 +1,63 @@ -// -// ThreadTest.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/ThreadTest.h#1 $ -// -// Definition of the ThreadTest class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 ThreadTest_INCLUDED -#define ThreadTest_INCLUDED - - -#include "Poco/Foundation.h" -#include "CppUnit/TestCase.h" - - -class ThreadTest: public CppUnit::TestCase -{ -public: - ThreadTest(const std::string& name); - ~ThreadTest(); - - void testThread(); - void testNamedThread(); - void testCurrent(); - void testThreads(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // ThreadTest_INCLUDED +// +// ThreadTest.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/ThreadTest.h#1 $ +// +// Definition of the ThreadTest class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 ThreadTest_INCLUDED +#define ThreadTest_INCLUDED + + +#include "Poco/Foundation.h" +#include "CppUnit/TestCase.h" + + +class ThreadTest: public CppUnit::TestCase +{ +public: + ThreadTest(const std::string& name); + ~ThreadTest(); + + void testThread(); + void testNamedThread(); + void testCurrent(); + void testThreads(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // ThreadTest_INCLUDED diff --git a/Foundation/testsuite/src/ThreadingTestSuite.cpp b/Foundation/testsuite/src/ThreadingTestSuite.cpp index 2c0530b67..f87d73719 100644 --- a/Foundation/testsuite/src/ThreadingTestSuite.cpp +++ b/Foundation/testsuite/src/ThreadingTestSuite.cpp @@ -1,60 +1,60 @@ -// -// ThreadingTestSuite.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/ThreadingTestSuite.cpp#1 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "ThreadingTestSuite.h" -#include "ThreadTest.h" -#include "SemaphoreTest.h" -#include "RWLockTest.h" -#include "ThreadPoolTest.h" -#include "TimerTest.h" -#include "ThreadLocalTest.h" -#include "ActivityTest.h" -#include "ActiveMethodTest.h" -#include "ActiveDispatcherTest.h" - - -CppUnit::Test* ThreadingTestSuite::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("ThreadingTestSuite"); - - pSuite->addTest(ThreadTest::suite()); - pSuite->addTest(SemaphoreTest::suite()); - pSuite->addTest(RWLockTest::suite()); - pSuite->addTest(ThreadPoolTest::suite()); - pSuite->addTest(TimerTest::suite()); - pSuite->addTest(ThreadLocalTest::suite()); - pSuite->addTest(ActivityTest::suite()); - pSuite->addTest(ActiveMethodTest::suite()); - pSuite->addTest(ActiveDispatcherTest::suite()); - - return pSuite; -} +// +// ThreadingTestSuite.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/ThreadingTestSuite.cpp#1 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "ThreadingTestSuite.h" +#include "ThreadTest.h" +#include "SemaphoreTest.h" +#include "RWLockTest.h" +#include "ThreadPoolTest.h" +#include "TimerTest.h" +#include "ThreadLocalTest.h" +#include "ActivityTest.h" +#include "ActiveMethodTest.h" +#include "ActiveDispatcherTest.h" + + +CppUnit::Test* ThreadingTestSuite::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("ThreadingTestSuite"); + + pSuite->addTest(ThreadTest::suite()); + pSuite->addTest(SemaphoreTest::suite()); + pSuite->addTest(RWLockTest::suite()); + pSuite->addTest(ThreadPoolTest::suite()); + pSuite->addTest(TimerTest::suite()); + pSuite->addTest(ThreadLocalTest::suite()); + pSuite->addTest(ActivityTest::suite()); + pSuite->addTest(ActiveMethodTest::suite()); + pSuite->addTest(ActiveDispatcherTest::suite()); + + return pSuite; +} diff --git a/Foundation/testsuite/src/ThreadingTestSuite.h b/Foundation/testsuite/src/ThreadingTestSuite.h index f34427ada..a15d8bc79 100644 --- a/Foundation/testsuite/src/ThreadingTestSuite.h +++ b/Foundation/testsuite/src/ThreadingTestSuite.h @@ -1,49 +1,49 @@ -// -// ThreadingTestSuite.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/ThreadingTestSuite.h#1 $ -// -// Definition of the ThreadingTestSuite class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 ThreadingTestSuite_INCLUDED -#define ThreadingTestSuite_INCLUDED - - -#include "CppUnit/TestSuite.h" - - -class ThreadingTestSuite -{ -public: - static CppUnit::Test* suite(); -}; - - -#endif // ThreadingTestSuite_INCLUDED +// +// ThreadingTestSuite.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/ThreadingTestSuite.h#1 $ +// +// Definition of the ThreadingTestSuite class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 ThreadingTestSuite_INCLUDED +#define ThreadingTestSuite_INCLUDED + + +#include "CppUnit/TestSuite.h" + + +class ThreadingTestSuite +{ +public: + static CppUnit::Test* suite(); +}; + + +#endif // ThreadingTestSuite_INCLUDED diff --git a/Foundation/testsuite/src/TimerTest.cpp b/Foundation/testsuite/src/TimerTest.cpp index b9fcc47bb..1cfa2f5fa 100644 --- a/Foundation/testsuite/src/TimerTest.cpp +++ b/Foundation/testsuite/src/TimerTest.cpp @@ -1,104 +1,104 @@ -// -// TimerTest.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/TimerTest.cpp#2 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "TimerTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/Thread.h" -#include "Poco/Stopwatch.h" - - -using Poco::Timer; -using Poco::TimerCallback; -using Poco::Thread; -using Poco::Stopwatch; - - -TimerTest::TimerTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -TimerTest::~TimerTest() -{ -} - - -void TimerTest::testTimer() -{ - Timer t(100, 200); - assert (t.getStartInterval() == 100); - assert (t.getPeriodicInterval() == 200); - - Stopwatch sw; - TimerCallback tc(*this, &TimerTest::onTimer); - sw.start(); - t.start(tc); - _event.wait(); - sw.stop(); - assert (sw.elapsed() >= 90000 && sw.elapsed() < 150000); - sw.restart(); - _event.wait(); - sw.stop(); - assert (sw.elapsed() >= 190000 && sw.elapsed() < 250000); - sw.restart(); - _event.wait(); - sw.stop(); - assert (sw.elapsed() >= 190000 && sw.elapsed() < 250000); - t.stop(); -} - - -void TimerTest::setUp() -{ -} - - -void TimerTest::tearDown() -{ -} - - -void TimerTest::onTimer(Timer& timer) -{ - _event.set(); -} - - -CppUnit::Test* TimerTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("TimerTest"); - - CppUnit_addTest(pSuite, TimerTest, testTimer); - - return pSuite; -} +// +// TimerTest.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/TimerTest.cpp#2 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "TimerTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/Thread.h" +#include "Poco/Stopwatch.h" + + +using Poco::Timer; +using Poco::TimerCallback; +using Poco::Thread; +using Poco::Stopwatch; + + +TimerTest::TimerTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +TimerTest::~TimerTest() +{ +} + + +void TimerTest::testTimer() +{ + Timer t(100, 200); + assert (t.getStartInterval() == 100); + assert (t.getPeriodicInterval() == 200); + + Stopwatch sw; + TimerCallback tc(*this, &TimerTest::onTimer); + sw.start(); + t.start(tc); + _event.wait(); + sw.stop(); + assert (sw.elapsed() >= 90000 && sw.elapsed() < 150000); + sw.restart(); + _event.wait(); + sw.stop(); + assert (sw.elapsed() >= 190000 && sw.elapsed() < 250000); + sw.restart(); + _event.wait(); + sw.stop(); + assert (sw.elapsed() >= 190000 && sw.elapsed() < 250000); + t.stop(); +} + + +void TimerTest::setUp() +{ +} + + +void TimerTest::tearDown() +{ +} + + +void TimerTest::onTimer(Timer& timer) +{ + _event.set(); +} + + +CppUnit::Test* TimerTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("TimerTest"); + + CppUnit_addTest(pSuite, TimerTest, testTimer); + + return pSuite; +} diff --git a/Foundation/testsuite/src/TimerTest.h b/Foundation/testsuite/src/TimerTest.h index 098660374..58745840b 100644 --- a/Foundation/testsuite/src/TimerTest.h +++ b/Foundation/testsuite/src/TimerTest.h @@ -1,66 +1,66 @@ -// -// TimerTest.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/TimerTest.h#1 $ -// -// Definition of the TimerTest class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 TimerTest_INCLUDED -#define TimerTest_INCLUDED - - -#include "Poco/Foundation.h" -#include "CppUnit/TestCase.h" -#include "Poco/Timer.h" -#include "Poco/Event.h" - - -class TimerTest: public CppUnit::TestCase -{ -public: - TimerTest(const std::string& name); - ~TimerTest(); - - void testTimer(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -protected: - void onTimer(Poco::Timer& t); - -private: - Poco::Event _event; -}; - - -#endif // TimerTest_INCLUDED +// +// TimerTest.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/TimerTest.h#1 $ +// +// Definition of the TimerTest class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 TimerTest_INCLUDED +#define TimerTest_INCLUDED + + +#include "Poco/Foundation.h" +#include "CppUnit/TestCase.h" +#include "Poco/Timer.h" +#include "Poco/Event.h" + + +class TimerTest: public CppUnit::TestCase +{ +public: + TimerTest(const std::string& name); + ~TimerTest(); + + void testTimer(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +protected: + void onTimer(Poco::Timer& t); + +private: + Poco::Event _event; +}; + + +#endif // TimerTest_INCLUDED diff --git a/Foundation/testsuite/src/TimespanTest.cpp b/Foundation/testsuite/src/TimespanTest.cpp index 9ba4d7713..6d1a7f84f 100644 --- a/Foundation/testsuite/src/TimespanTest.cpp +++ b/Foundation/testsuite/src/TimespanTest.cpp @@ -1,180 +1,180 @@ -// -// TimespanTest.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/TimespanTest.cpp#1 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "TimespanTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/Timespan.h" - - -using Poco::Timespan; - - -TimespanTest::TimespanTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -TimespanTest::~TimespanTest() -{ -} - - -void TimespanTest::testConversions() -{ - Timespan ts; - assert (ts.totalMicroseconds() == 0); - ts = Timespan::DAYS; - assert (ts.totalMicroseconds() == Timespan::DAYS); - assert (ts.totalMilliseconds() == 86400000); - assert (ts.totalSeconds() == 86400); - assert (ts.totalMinutes() == 60*24); - assert (ts.totalHours() == 24); - assert (ts.days() == 1); - - assert (ts.microseconds() == 0); - assert (ts.milliseconds() == 0); - assert (ts.seconds() == 0); - assert (ts.minutes() == 0); - assert (ts.hours() == 0); - - ts.assign(2, 12, 30, 10, 123456); - assert (ts.microseconds() == 456); - assert (ts.milliseconds() == 123); - assert (ts.seconds() == 10); - assert (ts.minutes() == 30); - assert (ts.hours() == 12); - assert (ts.days() == 2); - - ts.assign(0, 36, 30, 10, 123456); - assert (ts.microseconds() == 456); - assert (ts.milliseconds() == 123); - assert (ts.useconds() == 123456); - assert (ts.seconds() == 10); - assert (ts.minutes() == 30); - assert (ts.hours() == 12); - assert (ts.days() == 1); - - ts.assign(0, 0, 2190, 10, 123456); - assert (ts.microseconds() == 456); - assert (ts.milliseconds() == 123); - assert (ts.useconds() == 123456); - assert (ts.seconds() == 10); - assert (ts.minutes() == 30); - assert (ts.hours() == 12); - assert (ts.days() == 1); -} - - -void TimespanTest::testComparisons() -{ - Timespan ts1(10000000); - Timespan ts2(20000000); - Timespan ts3(20000000); - - assert (ts1 != ts2); - assert (!(ts1 == ts2)); - assert (ts1 <= ts2); - assert (ts1 < ts2); - assert (ts2 > ts1); - assert (ts2 >= ts1); - - assert (ts2 == ts3); - assert (!(ts2 != ts3)); - assert (ts2 >= ts3); - assert (ts2 <= ts3); - assert (!(ts2 > ts3)); - assert (!(ts2 < ts3)); - - assert (ts1 == 10000000); - assert (ts1 != 20000000); - assert (ts1 <= 10000000); - assert (ts1 <= 20000000); - assert (ts1 >= 10000000); - assert (ts1 >= 5000000); - assert (ts1 < 20000000); - assert (ts1 > 5000000); -} - - -void TimespanTest::testArithmetics() -{ - Timespan ts1(100000000); - Timespan ts2(50000000); - Timespan ts3; - ts3 = ts1 + ts2; - assert (ts3 == 150000000); - ts3 = ts1 + 30000000; - assert (ts3 == 130000000); - ts3 = ts1 - ts2; - assert (ts3 == 50000000); - ts3 = ts1 - 20000000; - assert (ts3 == 80000000); - ts3 += 20000000; - assert (ts3 == ts1); - ts3 -= ts2; - assert (ts3 == ts2); -} - - -void TimespanTest::testSwap() -{ - Timespan ts1(10000000); - Timespan ts2(50000000); - - assert (ts1 < ts2); - ts1.swap(ts2); - assert (ts2 < ts1); -} - - -void TimespanTest::setUp() -{ -} - - -void TimespanTest::tearDown() -{ -} - - -CppUnit::Test* TimespanTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("TimespanTest"); - - CppUnit_addTest(pSuite, TimespanTest, testConversions); - CppUnit_addTest(pSuite, TimespanTest, testComparisons); - CppUnit_addTest(pSuite, TimespanTest, testArithmetics); - CppUnit_addTest(pSuite, TimespanTest, testSwap); - - return pSuite; -} +// +// TimespanTest.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/TimespanTest.cpp#1 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "TimespanTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/Timespan.h" + + +using Poco::Timespan; + + +TimespanTest::TimespanTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +TimespanTest::~TimespanTest() +{ +} + + +void TimespanTest::testConversions() +{ + Timespan ts; + assert (ts.totalMicroseconds() == 0); + ts = Timespan::DAYS; + assert (ts.totalMicroseconds() == Timespan::DAYS); + assert (ts.totalMilliseconds() == 86400000); + assert (ts.totalSeconds() == 86400); + assert (ts.totalMinutes() == 60*24); + assert (ts.totalHours() == 24); + assert (ts.days() == 1); + + assert (ts.microseconds() == 0); + assert (ts.milliseconds() == 0); + assert (ts.seconds() == 0); + assert (ts.minutes() == 0); + assert (ts.hours() == 0); + + ts.assign(2, 12, 30, 10, 123456); + assert (ts.microseconds() == 456); + assert (ts.milliseconds() == 123); + assert (ts.seconds() == 10); + assert (ts.minutes() == 30); + assert (ts.hours() == 12); + assert (ts.days() == 2); + + ts.assign(0, 36, 30, 10, 123456); + assert (ts.microseconds() == 456); + assert (ts.milliseconds() == 123); + assert (ts.useconds() == 123456); + assert (ts.seconds() == 10); + assert (ts.minutes() == 30); + assert (ts.hours() == 12); + assert (ts.days() == 1); + + ts.assign(0, 0, 2190, 10, 123456); + assert (ts.microseconds() == 456); + assert (ts.milliseconds() == 123); + assert (ts.useconds() == 123456); + assert (ts.seconds() == 10); + assert (ts.minutes() == 30); + assert (ts.hours() == 12); + assert (ts.days() == 1); +} + + +void TimespanTest::testComparisons() +{ + Timespan ts1(10000000); + Timespan ts2(20000000); + Timespan ts3(20000000); + + assert (ts1 != ts2); + assert (!(ts1 == ts2)); + assert (ts1 <= ts2); + assert (ts1 < ts2); + assert (ts2 > ts1); + assert (ts2 >= ts1); + + assert (ts2 == ts3); + assert (!(ts2 != ts3)); + assert (ts2 >= ts3); + assert (ts2 <= ts3); + assert (!(ts2 > ts3)); + assert (!(ts2 < ts3)); + + assert (ts1 == 10000000); + assert (ts1 != 20000000); + assert (ts1 <= 10000000); + assert (ts1 <= 20000000); + assert (ts1 >= 10000000); + assert (ts1 >= 5000000); + assert (ts1 < 20000000); + assert (ts1 > 5000000); +} + + +void TimespanTest::testArithmetics() +{ + Timespan ts1(100000000); + Timespan ts2(50000000); + Timespan ts3; + ts3 = ts1 + ts2; + assert (ts3 == 150000000); + ts3 = ts1 + 30000000; + assert (ts3 == 130000000); + ts3 = ts1 - ts2; + assert (ts3 == 50000000); + ts3 = ts1 - 20000000; + assert (ts3 == 80000000); + ts3 += 20000000; + assert (ts3 == ts1); + ts3 -= ts2; + assert (ts3 == ts2); +} + + +void TimespanTest::testSwap() +{ + Timespan ts1(10000000); + Timespan ts2(50000000); + + assert (ts1 < ts2); + ts1.swap(ts2); + assert (ts2 < ts1); +} + + +void TimespanTest::setUp() +{ +} + + +void TimespanTest::tearDown() +{ +} + + +CppUnit::Test* TimespanTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("TimespanTest"); + + CppUnit_addTest(pSuite, TimespanTest, testConversions); + CppUnit_addTest(pSuite, TimespanTest, testComparisons); + CppUnit_addTest(pSuite, TimespanTest, testArithmetics); + CppUnit_addTest(pSuite, TimespanTest, testSwap); + + return pSuite; +} diff --git a/Foundation/testsuite/src/TimespanTest.h b/Foundation/testsuite/src/TimespanTest.h index df504a102..30038e5ef 100644 --- a/Foundation/testsuite/src/TimespanTest.h +++ b/Foundation/testsuite/src/TimespanTest.h @@ -1,63 +1,63 @@ -// -// TimespanTest.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/TimespanTest.h#1 $ -// -// Definition of the TimespanTest class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 TimespanTest_INCLUDED -#define TimespanTest_INCLUDED - - -#include "Poco/Foundation.h" -#include "CppUnit/TestCase.h" - - -class TimespanTest: public CppUnit::TestCase -{ -public: - TimespanTest(const std::string& name); - ~TimespanTest(); - - void testConversions(); - void testComparisons(); - void testArithmetics(); - void testSwap(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // TimespanTest_INCLUDED +// +// TimespanTest.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/TimespanTest.h#1 $ +// +// Definition of the TimespanTest class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 TimespanTest_INCLUDED +#define TimespanTest_INCLUDED + + +#include "Poco/Foundation.h" +#include "CppUnit/TestCase.h" + + +class TimespanTest: public CppUnit::TestCase +{ +public: + TimespanTest(const std::string& name); + ~TimespanTest(); + + void testConversions(); + void testComparisons(); + void testArithmetics(); + void testSwap(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // TimespanTest_INCLUDED diff --git a/Foundation/testsuite/src/TimestampTest.cpp b/Foundation/testsuite/src/TimestampTest.cpp index f610aa469..95feb6862 100644 --- a/Foundation/testsuite/src/TimestampTest.cpp +++ b/Foundation/testsuite/src/TimestampTest.cpp @@ -1,122 +1,122 @@ -// -// TimestampTest.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/TimestampTest.cpp#1 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "TimestampTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/Timestamp.h" -#include "Poco/Thread.h" - - -using Poco::Timestamp; -using Poco::Thread; - - -TimestampTest::TimestampTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -TimestampTest::~TimestampTest() -{ -} - - -void TimestampTest::testTimestamp() -{ - Timestamp t1; - Thread::sleep(200); - Timestamp t2; - Timestamp t3 = t2; - assert (t1 != t2); - assert (!(t1 == t2)); - assert (t2 > t1); - assert (t2 >= t1); - assert (!(t1 > t2)); - assert (!(t1 >= t2)); - assert (t2 == t3); - assert (!(t2 != t3)); - assert (t2 >= t3); - assert (t2 <= t3); - Timestamp::TimeDiff d = (t2 - t1); - assert (d >= 180000 && d <= 300000); - - t1.swap(t2); - assert (t1 > t2); - t2.swap(t1); - - Timestamp::UtcTimeVal tv = t1.utcTime(); - Timestamp t4 = Timestamp::fromUtcTime(tv); - assert (t1 == t4); - - Timestamp epoch(0); - tv = epoch.utcTime(); - assert (tv >> 32 == 0x01B21DD2); - assert ((tv & 0xFFFFFFFF) == 0x13814000); - - Timestamp now; - Thread::sleep(201); - assert (now.elapsed() >= 200000); - assert (now.isElapsed(200000)); - assert (!now.isElapsed(2000000)); - -#if defined(_WIN32) - { - Timestamp now; - Poco::UInt32 low; - Poco::UInt32 high; - now.toFileTimeNP(low, high); - Timestamp ts = Timestamp::fromFileTimeNP(low, high); - assert (now == ts); - } -#endif -} - - -void TimestampTest::setUp() -{ -} - - -void TimestampTest::tearDown() -{ -} - - -CppUnit::Test* TimestampTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("TimestampTest"); - - CppUnit_addTest(pSuite, TimestampTest, testTimestamp); - - return pSuite; -} +// +// TimestampTest.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/TimestampTest.cpp#1 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "TimestampTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/Timestamp.h" +#include "Poco/Thread.h" + + +using Poco::Timestamp; +using Poco::Thread; + + +TimestampTest::TimestampTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +TimestampTest::~TimestampTest() +{ +} + + +void TimestampTest::testTimestamp() +{ + Timestamp t1; + Thread::sleep(200); + Timestamp t2; + Timestamp t3 = t2; + assert (t1 != t2); + assert (!(t1 == t2)); + assert (t2 > t1); + assert (t2 >= t1); + assert (!(t1 > t2)); + assert (!(t1 >= t2)); + assert (t2 == t3); + assert (!(t2 != t3)); + assert (t2 >= t3); + assert (t2 <= t3); + Timestamp::TimeDiff d = (t2 - t1); + assert (d >= 180000 && d <= 300000); + + t1.swap(t2); + assert (t1 > t2); + t2.swap(t1); + + Timestamp::UtcTimeVal tv = t1.utcTime(); + Timestamp t4 = Timestamp::fromUtcTime(tv); + assert (t1 == t4); + + Timestamp epoch(0); + tv = epoch.utcTime(); + assert (tv >> 32 == 0x01B21DD2); + assert ((tv & 0xFFFFFFFF) == 0x13814000); + + Timestamp now; + Thread::sleep(201); + assert (now.elapsed() >= 200000); + assert (now.isElapsed(200000)); + assert (!now.isElapsed(2000000)); + +#if defined(_WIN32) + { + Timestamp now; + Poco::UInt32 low; + Poco::UInt32 high; + now.toFileTimeNP(low, high); + Timestamp ts = Timestamp::fromFileTimeNP(low, high); + assert (now == ts); + } +#endif +} + + +void TimestampTest::setUp() +{ +} + + +void TimestampTest::tearDown() +{ +} + + +CppUnit::Test* TimestampTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("TimestampTest"); + + CppUnit_addTest(pSuite, TimestampTest, testTimestamp); + + return pSuite; +} diff --git a/Foundation/testsuite/src/TimestampTest.h b/Foundation/testsuite/src/TimestampTest.h index 4e4e23365..e7538d0f1 100644 --- a/Foundation/testsuite/src/TimestampTest.h +++ b/Foundation/testsuite/src/TimestampTest.h @@ -1,60 +1,60 @@ -// -// TimestampTest.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/TimestampTest.h#1 $ -// -// Definition of the TimestampTest class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 TimestampTest_INCLUDED -#define TimestampTest_INCLUDED - - -#include "Poco/Foundation.h" -#include "CppUnit/TestCase.h" - - -class TimestampTest: public CppUnit::TestCase -{ -public: - TimestampTest(const std::string& name); - ~TimestampTest(); - - void testTimestamp(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // TimestampTest_INCLUDED +// +// TimestampTest.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/TimestampTest.h#1 $ +// +// Definition of the TimestampTest class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 TimestampTest_INCLUDED +#define TimestampTest_INCLUDED + + +#include "Poco/Foundation.h" +#include "CppUnit/TestCase.h" + + +class TimestampTest: public CppUnit::TestCase +{ +public: + TimestampTest(const std::string& name); + ~TimestampTest(); + + void testTimestamp(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // TimestampTest_INCLUDED diff --git a/Foundation/testsuite/src/TimezoneTest.cpp b/Foundation/testsuite/src/TimezoneTest.cpp index 471727ac7..7f52ca3ec 100644 --- a/Foundation/testsuite/src/TimezoneTest.cpp +++ b/Foundation/testsuite/src/TimezoneTest.cpp @@ -1,83 +1,83 @@ -// -// TimezoneTest.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/TimezoneTest.cpp#1 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "TimezoneTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/Timezone.h" -#include - - -using Poco::Timezone; - - -TimezoneTest::TimezoneTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -TimezoneTest::~TimezoneTest() -{ -} - - -void TimezoneTest::testTimezone() -{ - std::string name = Timezone::name(); - std::string stdName = Timezone::standardName(); - std::string dstName = Timezone::dstName(); - std::cout << "Timezone Names: " << name << ", " << stdName << ", " << dstName << std::endl; - int utcOffset = Timezone::utcOffset(); - std::cout << "UTC Offset: " << utcOffset << std::endl; - int dst = Timezone::dst(); - std::cout << "DST Offset: " << dst << std::endl; -} - - -void TimezoneTest::setUp() -{ -} - - -void TimezoneTest::tearDown() -{ -} - - -CppUnit::Test* TimezoneTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("TimezoneTest"); - - CppUnit_addTest(pSuite, TimezoneTest, testTimezone); - - return pSuite; -} +// +// TimezoneTest.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/TimezoneTest.cpp#1 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "TimezoneTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/Timezone.h" +#include + + +using Poco::Timezone; + + +TimezoneTest::TimezoneTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +TimezoneTest::~TimezoneTest() +{ +} + + +void TimezoneTest::testTimezone() +{ + std::string name = Timezone::name(); + std::string stdName = Timezone::standardName(); + std::string dstName = Timezone::dstName(); + std::cout << "Timezone Names: " << name << ", " << stdName << ", " << dstName << std::endl; + int utcOffset = Timezone::utcOffset(); + std::cout << "UTC Offset: " << utcOffset << std::endl; + int dst = Timezone::dst(); + std::cout << "DST Offset: " << dst << std::endl; +} + + +void TimezoneTest::setUp() +{ +} + + +void TimezoneTest::tearDown() +{ +} + + +CppUnit::Test* TimezoneTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("TimezoneTest"); + + CppUnit_addTest(pSuite, TimezoneTest, testTimezone); + + return pSuite; +} diff --git a/Foundation/testsuite/src/TimezoneTest.h b/Foundation/testsuite/src/TimezoneTest.h index b9efde270..4ae3c2b5e 100644 --- a/Foundation/testsuite/src/TimezoneTest.h +++ b/Foundation/testsuite/src/TimezoneTest.h @@ -1,60 +1,60 @@ -// -// TimezoneTest.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/TimezoneTest.h#1 $ -// -// Definition of the TimezoneTest class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 TimezoneTest_INCLUDED -#define TimezoneTest_INCLUDED - - -#include "Poco/Foundation.h" -#include "CppUnit/TestCase.h" - - -class TimezoneTest: public CppUnit::TestCase -{ -public: - TimezoneTest(const std::string& name); - ~TimezoneTest(); - - void testTimezone(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // TimezoneTest_INCLUDED +// +// TimezoneTest.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/TimezoneTest.h#1 $ +// +// Definition of the TimezoneTest class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 TimezoneTest_INCLUDED +#define TimezoneTest_INCLUDED + + +#include "Poco/Foundation.h" +#include "CppUnit/TestCase.h" + + +class TimezoneTest: public CppUnit::TestCase +{ +public: + TimezoneTest(const std::string& name); + ~TimezoneTest(); + + void testTimezone(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // TimezoneTest_INCLUDED diff --git a/Foundation/testsuite/src/URIStreamOpenerTest.cpp b/Foundation/testsuite/src/URIStreamOpenerTest.cpp index 801f8e270..21bfd9d73 100644 --- a/Foundation/testsuite/src/URIStreamOpenerTest.cpp +++ b/Foundation/testsuite/src/URIStreamOpenerTest.cpp @@ -1,246 +1,246 @@ -// -// URIStreamOpenerTest.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/URIStreamOpenerTest.cpp#1 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "URIStreamOpenerTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/URIStreamOpener.h" -#include "Poco/URIStreamFactory.h" -#include "Poco/URI.h" -#include "Poco/TemporaryFile.h" -#include "Poco/Path.h" -#include -#include - - -using Poco::URIStreamOpener; -using Poco::URIStreamFactory; -using Poco::URI; -using Poco::TemporaryFile; -using Poco::Path; - - -namespace -{ - class StringStreamFactory: public URIStreamFactory - { - public: - StringStreamFactory() - { - } - - std::istream* open(const URI& uri) - { - return new std::istringstream(uri.toString()); - } - }; -} - - -URIStreamOpenerTest::URIStreamOpenerTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -URIStreamOpenerTest::~URIStreamOpenerTest() -{ -} - - -void URIStreamOpenerTest::testStreamOpenerFile() -{ - TemporaryFile tempFile; - std::string path = tempFile.path(); - std::ofstream ostr(path.c_str()); - assert (ostr.good()); - ostr << "Hello, world!" << std::endl; - ostr.close(); - - URI uri; - uri.setScheme("file"); - uri.setPath(Path(path).toString(Path::PATH_UNIX)); - std::string uriString = uri.toString(); - - URIStreamOpener opener; - std::istream* istr = opener.open(uri); - assert (istr != 0); - assert (istr->good()); - delete istr; -} - - -void URIStreamOpenerTest::testStreamOpenerRelative() -{ - TemporaryFile tempFile; - std::string path = tempFile.path(); - std::ofstream ostr(path.c_str()); - assert (ostr.good()); - ostr << "Hello, world!" << std::endl; - ostr.close(); - - URI uri(Path(path).toString(Path::PATH_UNIX)); - std::string uriString = uri.toString(); - - URIStreamOpener opener; - std::istream* istr = opener.open(uri); - assert (istr != 0); - assert (istr->good()); - delete istr; -} - - -void URIStreamOpenerTest::testStreamOpenerURI() -{ - TemporaryFile tempFile; - std::string path = tempFile.path(); - std::ofstream ostr(path.c_str()); - assert (ostr.good()); - ostr << "Hello, world!" << std::endl; - ostr.close(); - - URI uri; - uri.setScheme("file"); - uri.setPath(Path(path).toString(Path::PATH_UNIX)); - std::string uriString = uri.toString(); - - URIStreamOpener opener; - std::istream* istr = opener.open(uriString); - assert (istr != 0); - assert (istr->good()); - delete istr; -} - - -void URIStreamOpenerTest::testStreamOpenerURIResolve() -{ - TemporaryFile tempFile; - std::string path = tempFile.path(); - std::ofstream ostr(path.c_str()); - assert (ostr.good()); - ostr << "Hello, world!" << std::endl; - ostr.close(); - - Path p(path); - p.makeAbsolute(); - Path parent(p.parent()); - - URI uri; - uri.setScheme("file"); - uri.setPath(parent.toString(Path::PATH_UNIX)); - std::string uriString = uri.toString(); - - URIStreamOpener opener; - std::istream* istr = opener.open(uriString, p.getFileName()); - assert (istr != 0); - assert (istr->good()); - delete istr; -} - - -void URIStreamOpenerTest::testStreamOpenerPath() -{ - TemporaryFile tempFile; - std::string path = tempFile.path(); - std::ofstream ostr(path.c_str()); - assert (ostr.good()); - ostr << "Hello, world!" << std::endl; - ostr.close(); - - URIStreamOpener opener; - std::istream* istr = opener.open(path); - assert (istr != 0); - assert (istr->good()); - delete istr; -} - - -void URIStreamOpenerTest::testStreamOpenerPathResolve() -{ - TemporaryFile tempFile; - std::string path = tempFile.path(); - std::ofstream ostr(path.c_str()); - assert (ostr.good()); - ostr << "Hello, world!" << std::endl; - ostr.close(); - - Path p(path); - Path parent(p.parent()); - std::string base = parent.toString(); - - URIStreamOpener opener; - std::istream* istr = opener.open(base, p.getFileName()); - assert (istr != 0); - assert (istr->good()); - delete istr; -} - - -void URIStreamOpenerTest::testRegisterUnregister() -{ - URIStreamOpener opener; - assert (!opener.supportsScheme("string")); - opener.registerStreamFactory("string", new StringStreamFactory); - assert (opener.supportsScheme("string")); - URI uri("string:foobar"); - std::istream* istr = opener.open(uri); - assert (istr != 0); - assert (istr->good()); - delete istr; - opener.unregisterStreamFactory("string"); - assert (!opener.supportsScheme("string")); -} - - -void URIStreamOpenerTest::setUp() -{ -} - - -void URIStreamOpenerTest::tearDown() -{ -} - - -CppUnit::Test* URIStreamOpenerTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("URIStreamOpenerTest"); - - CppUnit_addTest(pSuite, URIStreamOpenerTest, testStreamOpenerFile); - CppUnit_addTest(pSuite, URIStreamOpenerTest, testStreamOpenerRelative); - CppUnit_addTest(pSuite, URIStreamOpenerTest, testStreamOpenerURI); - CppUnit_addTest(pSuite, URIStreamOpenerTest, testStreamOpenerURIResolve); - CppUnit_addTest(pSuite, URIStreamOpenerTest, testStreamOpenerPath); - CppUnit_addTest(pSuite, URIStreamOpenerTest, testStreamOpenerPathResolve); - CppUnit_addTest(pSuite, URIStreamOpenerTest, testRegisterUnregister); - - return pSuite; -} +// +// URIStreamOpenerTest.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/URIStreamOpenerTest.cpp#1 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "URIStreamOpenerTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/URIStreamOpener.h" +#include "Poco/URIStreamFactory.h" +#include "Poco/URI.h" +#include "Poco/TemporaryFile.h" +#include "Poco/Path.h" +#include +#include + + +using Poco::URIStreamOpener; +using Poco::URIStreamFactory; +using Poco::URI; +using Poco::TemporaryFile; +using Poco::Path; + + +namespace +{ + class StringStreamFactory: public URIStreamFactory + { + public: + StringStreamFactory() + { + } + + std::istream* open(const URI& uri) + { + return new std::istringstream(uri.toString()); + } + }; +} + + +URIStreamOpenerTest::URIStreamOpenerTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +URIStreamOpenerTest::~URIStreamOpenerTest() +{ +} + + +void URIStreamOpenerTest::testStreamOpenerFile() +{ + TemporaryFile tempFile; + std::string path = tempFile.path(); + std::ofstream ostr(path.c_str()); + assert (ostr.good()); + ostr << "Hello, world!" << std::endl; + ostr.close(); + + URI uri; + uri.setScheme("file"); + uri.setPath(Path(path).toString(Path::PATH_UNIX)); + std::string uriString = uri.toString(); + + URIStreamOpener opener; + std::istream* istr = opener.open(uri); + assert (istr != 0); + assert (istr->good()); + delete istr; +} + + +void URIStreamOpenerTest::testStreamOpenerRelative() +{ + TemporaryFile tempFile; + std::string path = tempFile.path(); + std::ofstream ostr(path.c_str()); + assert (ostr.good()); + ostr << "Hello, world!" << std::endl; + ostr.close(); + + URI uri(Path(path).toString(Path::PATH_UNIX)); + std::string uriString = uri.toString(); + + URIStreamOpener opener; + std::istream* istr = opener.open(uri); + assert (istr != 0); + assert (istr->good()); + delete istr; +} + + +void URIStreamOpenerTest::testStreamOpenerURI() +{ + TemporaryFile tempFile; + std::string path = tempFile.path(); + std::ofstream ostr(path.c_str()); + assert (ostr.good()); + ostr << "Hello, world!" << std::endl; + ostr.close(); + + URI uri; + uri.setScheme("file"); + uri.setPath(Path(path).toString(Path::PATH_UNIX)); + std::string uriString = uri.toString(); + + URIStreamOpener opener; + std::istream* istr = opener.open(uriString); + assert (istr != 0); + assert (istr->good()); + delete istr; +} + + +void URIStreamOpenerTest::testStreamOpenerURIResolve() +{ + TemporaryFile tempFile; + std::string path = tempFile.path(); + std::ofstream ostr(path.c_str()); + assert (ostr.good()); + ostr << "Hello, world!" << std::endl; + ostr.close(); + + Path p(path); + p.makeAbsolute(); + Path parent(p.parent()); + + URI uri; + uri.setScheme("file"); + uri.setPath(parent.toString(Path::PATH_UNIX)); + std::string uriString = uri.toString(); + + URIStreamOpener opener; + std::istream* istr = opener.open(uriString, p.getFileName()); + assert (istr != 0); + assert (istr->good()); + delete istr; +} + + +void URIStreamOpenerTest::testStreamOpenerPath() +{ + TemporaryFile tempFile; + std::string path = tempFile.path(); + std::ofstream ostr(path.c_str()); + assert (ostr.good()); + ostr << "Hello, world!" << std::endl; + ostr.close(); + + URIStreamOpener opener; + std::istream* istr = opener.open(path); + assert (istr != 0); + assert (istr->good()); + delete istr; +} + + +void URIStreamOpenerTest::testStreamOpenerPathResolve() +{ + TemporaryFile tempFile; + std::string path = tempFile.path(); + std::ofstream ostr(path.c_str()); + assert (ostr.good()); + ostr << "Hello, world!" << std::endl; + ostr.close(); + + Path p(path); + Path parent(p.parent()); + std::string base = parent.toString(); + + URIStreamOpener opener; + std::istream* istr = opener.open(base, p.getFileName()); + assert (istr != 0); + assert (istr->good()); + delete istr; +} + + +void URIStreamOpenerTest::testRegisterUnregister() +{ + URIStreamOpener opener; + assert (!opener.supportsScheme("string")); + opener.registerStreamFactory("string", new StringStreamFactory); + assert (opener.supportsScheme("string")); + URI uri("string:foobar"); + std::istream* istr = opener.open(uri); + assert (istr != 0); + assert (istr->good()); + delete istr; + opener.unregisterStreamFactory("string"); + assert (!opener.supportsScheme("string")); +} + + +void URIStreamOpenerTest::setUp() +{ +} + + +void URIStreamOpenerTest::tearDown() +{ +} + + +CppUnit::Test* URIStreamOpenerTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("URIStreamOpenerTest"); + + CppUnit_addTest(pSuite, URIStreamOpenerTest, testStreamOpenerFile); + CppUnit_addTest(pSuite, URIStreamOpenerTest, testStreamOpenerRelative); + CppUnit_addTest(pSuite, URIStreamOpenerTest, testStreamOpenerURI); + CppUnit_addTest(pSuite, URIStreamOpenerTest, testStreamOpenerURIResolve); + CppUnit_addTest(pSuite, URIStreamOpenerTest, testStreamOpenerPath); + CppUnit_addTest(pSuite, URIStreamOpenerTest, testStreamOpenerPathResolve); + CppUnit_addTest(pSuite, URIStreamOpenerTest, testRegisterUnregister); + + return pSuite; +} diff --git a/Foundation/testsuite/src/URIStreamOpenerTest.h b/Foundation/testsuite/src/URIStreamOpenerTest.h index acdf1b5ef..eb8baf099 100644 --- a/Foundation/testsuite/src/URIStreamOpenerTest.h +++ b/Foundation/testsuite/src/URIStreamOpenerTest.h @@ -1,66 +1,66 @@ -// -// URIStreamOpenerTest.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/URIStreamOpenerTest.h#1 $ -// -// Definition of the URIStreamOpenerTest class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 URIStreamOpenerTest_INCLUDED -#define URIStreamOpenerTest_INCLUDED - - -#include "Poco/Foundation.h" -#include "CppUnit/TestCase.h" - - -class URIStreamOpenerTest: public CppUnit::TestCase -{ -public: - URIStreamOpenerTest(const std::string& name); - ~URIStreamOpenerTest(); - - void testStreamOpenerFile(); - void testStreamOpenerRelative(); - void testStreamOpenerURI(); - void testStreamOpenerURIResolve(); - void testStreamOpenerPath(); - void testStreamOpenerPathResolve(); - void testRegisterUnregister(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // URIStreamOpenerTest_INCLUDED +// +// URIStreamOpenerTest.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/URIStreamOpenerTest.h#1 $ +// +// Definition of the URIStreamOpenerTest class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 URIStreamOpenerTest_INCLUDED +#define URIStreamOpenerTest_INCLUDED + + +#include "Poco/Foundation.h" +#include "CppUnit/TestCase.h" + + +class URIStreamOpenerTest: public CppUnit::TestCase +{ +public: + URIStreamOpenerTest(const std::string& name); + ~URIStreamOpenerTest(); + + void testStreamOpenerFile(); + void testStreamOpenerRelative(); + void testStreamOpenerURI(); + void testStreamOpenerURIResolve(); + void testStreamOpenerPath(); + void testStreamOpenerPathResolve(); + void testRegisterUnregister(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // URIStreamOpenerTest_INCLUDED diff --git a/Foundation/testsuite/src/URITest.cpp b/Foundation/testsuite/src/URITest.cpp index 08145b80b..ceffb9af1 100644 --- a/Foundation/testsuite/src/URITest.cpp +++ b/Foundation/testsuite/src/URITest.cpp @@ -1,762 +1,762 @@ -// -// URITest.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/URITest.cpp#1 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "URITest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/URI.h" - - -using Poco::URI; - - -URITest::URITest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -URITest::~URITest() -{ -} - - -void URITest::testConstruction() -{ - URI uri; - assert (uri.getScheme().empty()); - assert (uri.getAuthority().empty()); - assert (uri.getUserInfo().empty()); - assert (uri.getHost().empty()); - assert (uri.getPort() == 0); - assert (uri.getPath().empty()); - assert (uri.getQuery().empty()); - assert (uri.getFragment().empty()); - - uri.setScheme("ftp"); - assert (uri.getScheme() == "ftp"); - assert (uri.getPort() == 21); - - uri.setScheme("HTTP"); - assert (uri.getScheme() == "http"); - - uri.setAuthority("www.appinf.com"); - assert (uri.getAuthority() == "www.appinf.com"); - assert (uri.getPort() == 80); - - uri.setAuthority("user@services.appinf.com:8000"); - assert (uri.getUserInfo() == "user"); - assert (uri.getHost() == "services.appinf.com"); - assert (uri.getPort() == 8000); - - uri.setPath("/index.html"); - assert (uri.getPath() == "/index.html"); - - uri.setPath("/file%20with%20spaces.html"); - assert (uri.getPath() == "/file with spaces.html"); - - uri.setPathEtc("/query.cgi?query=foo"); - assert (uri.getPath() == "/query.cgi"); - assert (uri.getQuery() == "query=foo"); - assert (uri.getFragment().empty()); - assert (uri.getPathEtc() == "/query.cgi?query=foo"); - assert (uri.getPathAndQuery() == "/query.cgi?query=foo"); - - uri.setPathEtc("/query.cgi?query=bar#frag"); - assert (uri.getPath() == "/query.cgi"); - assert (uri.getQuery() == "query=bar"); - assert (uri.getFragment() == "frag"); - assert (uri.getPathEtc() == "/query.cgi?query=bar#frag"); - assert (uri.getPathAndQuery() == "/query.cgi?query=bar"); - - uri.setQuery("query=test"); - assert (uri.getQuery() == "query=test"); - - uri.setFragment("result"); - assert (uri.getFragment() == "result"); - - URI uri2("file", "/home/guenter/foo.bar"); - assert (uri2.getScheme() == "file"); - assert (uri2.getPath() == "/home/guenter/foo.bar"); - - URI uri3("http", "www.appinf.com", "/index.html"); - assert (uri3.getScheme() == "http"); - assert (uri3.getAuthority() == "www.appinf.com"); - assert (uri3.getPath() == "/index.html"); - - URI uri4("http", "www.appinf.com:8000", "/index.html"); - assert (uri4.getScheme() == "http"); - assert (uri4.getAuthority() == "www.appinf.com:8000"); - assert (uri4.getPath() == "/index.html"); - - URI uri5("http", "user@www.appinf.com:8000", "/index.html"); - assert (uri5.getScheme() == "http"); - assert (uri5.getUserInfo() == "user"); - assert (uri5.getHost() == "www.appinf.com"); - assert (uri5.getPort() == 8000); - assert (uri5.getAuthority() == "user@www.appinf.com:8000"); - assert (uri5.getPath() == "/index.html"); - - URI uri6("http", "user@www.appinf.com:80", "/index.html"); - assert (uri6.getScheme() == "http"); - assert (uri6.getUserInfo() == "user"); - assert (uri6.getHost() == "www.appinf.com"); - assert (uri6.getPort() == 80); - assert (uri6.getAuthority() == "user@www.appinf.com"); - assert (uri6.getPath() == "/index.html"); - - URI uri7("http", "user@www.appinf.com:", "/index.html"); - assert (uri7.getScheme() == "http"); - assert (uri7.getUserInfo() == "user"); - assert (uri7.getHost() == "www.appinf.com"); - assert (uri7.getPort() == 80); - assert (uri7.getAuthority() == "user@www.appinf.com"); - assert (uri7.getPath() == "/index.html"); - - URI uri8("http", "www.appinf.com", "/index.html", "query=test"); - assert (uri8.getScheme() == "http"); - assert (uri8.getAuthority() == "www.appinf.com"); - assert (uri8.getPath() == "/index.html"); - assert (uri8.getQuery() == "query=test"); - - URI uri9("http", "www.appinf.com", "/index.html", "query=test", "fragment"); - assert (uri9.getScheme() == "http"); - assert (uri9.getAuthority() == "www.appinf.com"); - assert (uri9.getPath() == "/index.html"); - assert (uri9.getPathEtc() == "/index.html?query=test#fragment"); - assert (uri9.getQuery() == "query=test"); - assert (uri9.getFragment() == "fragment"); - - uri9.clear(); - assert (uri9.getScheme().empty()); - assert (uri9.getAuthority().empty()); - assert (uri9.getUserInfo().empty()); - assert (uri9.getHost().empty()); - assert (uri9.getPort() == 0); - assert (uri9.getPath().empty()); - assert (uri9.getQuery().empty()); - assert (uri9.getFragment().empty()); - - URI uri10("ldap", "[2001:db8::7]", "/c=GB?objectClass?one"); - assert (uri10.getScheme() == "ldap"); - assert (uri10.getUserInfo().empty()); - assert (uri10.getHost() == "[2001:db8::7]"); - assert (uri10.getPort() == 389); - assert (uri10.getAuthority() == "[2001:db8::7]"); - assert (uri10.getPathEtc() == "/c=GB?objectClass?one"); - - URI uri11("http", "www.appinf.com", "/index.html?query=test#fragment"); - assert (uri11.getScheme() == "http"); - assert (uri11.getAuthority() == "www.appinf.com"); - assert (uri11.getPath() == "/index.html"); - assert (uri11.getPathEtc() == "/index.html?query=test#fragment"); - assert (uri11.getQuery() == "query=test"); - assert (uri11.getFragment() == "fragment"); - -} - - -void URITest::testParse() -{ - URI uri("http://www.appinf.com"); - assert (uri.getScheme() == "http"); - assert (uri.getAuthority() == "www.appinf.com"); - assert (uri.getPath().empty()); - assert (uri.getQuery().empty()); - assert (uri.getFragment().empty()); - assert (!uri.isRelative()); - - uri = "http://www.appinf.com/"; - assert (uri.getScheme() == "http"); - assert (uri.getAuthority() == "www.appinf.com"); - assert (uri.getPath() == "/"); - assert (uri.getQuery().empty()); - assert (uri.getFragment().empty()); - assert (!uri.isRelative()); - - uri = "ftp://anonymous@ftp.appinf.com/pub/"; - assert (uri.getScheme() == "ftp"); - assert (uri.getUserInfo() == "anonymous"); - assert (uri.getHost() == "ftp.appinf.com"); - assert (uri.getPort() == 21); - assert (uri.getAuthority() == "anonymous@ftp.appinf.com"); - assert (uri.getPath() == "/pub/"); - assert (uri.getQuery().empty()); - assert (uri.getFragment().empty()); - assert (!uri.isRelative()); - assert (!uri.isRelative()); - - uri = "https://www.appinf.com/index.html#top"; - assert (uri.getScheme() == "https"); - assert (uri.getHost() == "www.appinf.com"); - assert (uri.getPort() == 443); - assert (uri.getPath() == "/index.html"); - assert (uri.getQuery().empty()); - assert (uri.getFragment() == "top"); - assert (!uri.isRelative()); - - uri = "http://www.appinf.com/search.cgi?keyword=test&scope=all"; - assert (uri.getScheme() == "http"); - assert (uri.getHost() == "www.appinf.com"); - assert (uri.getPort() == 80); - assert (uri.getPath() == "/search.cgi"); - assert (uri.getQuery() == "keyword=test&scope=all"); - assert (uri.getFragment().empty()); - assert (!uri.isRelative()); - - uri = "http://www.appinf.com/search.cgi?keyword=test&scope=all#result"; - assert (uri.getScheme() == "http"); - assert (uri.getHost() == "www.appinf.com"); - assert (uri.getPort() == 80); - assert (uri.getPath() == "/search.cgi"); - assert (uri.getQuery() == "keyword=test&scope=all"); - assert (uri.getFragment() == "result"); - assert (!uri.isRelative()); - - uri = "http://www.appinf.com/search.cgi?keyword=test%20encoded&scope=all#result"; - assert (uri.getScheme() == "http"); - assert (uri.getHost() == "www.appinf.com"); - assert (uri.getPort() == 80); - assert (uri.getPath() == "/search.cgi"); - assert (uri.getQuery() == "keyword=test encoded&scope=all"); - assert (uri.getFragment() == "result"); - assert (!uri.isRelative()); - - uri = "ldap://[2001:db8::7]/c=GB?objectClass?one"; - assert (uri.getScheme() == "ldap"); - assert (uri.getUserInfo().empty()); - assert (uri.getHost() == "[2001:db8::7]"); - assert (uri.getPort() == 389); - assert (uri.getAuthority() == "[2001:db8::7]"); - assert (uri.getPath() == "/c=GB"); - assert (uri.getQuery() == "objectClass?one"); - assert (uri.getFragment().empty()); - - uri = "mailto:John.Doe@example.com"; - assert (uri.getScheme() == "mailto"); - assert (uri.getUserInfo().empty()); - assert (uri.getHost().empty()); - assert (uri.getPort() == 0); - assert (uri.getAuthority().empty()); - assert (uri.getPath() == "John.Doe@example.com"); - assert (uri.getQuery().empty()); - assert (uri.getFragment().empty()); - - uri = "tel:+1-816-555-1212"; - assert (uri.getScheme() == "tel"); - assert (uri.getUserInfo().empty()); - assert (uri.getHost().empty()); - assert (uri.getPort() == 0); - assert (uri.getAuthority().empty()); - assert (uri.getPath() == "+1-816-555-1212"); - assert (uri.getQuery().empty()); - assert (uri.getFragment().empty()); - - uri = "telnet://192.0.2.16:80"; - assert (uri.getScheme() == "telnet"); - assert (uri.getUserInfo().empty()); - assert (uri.getHost() == "192.0.2.16"); - assert (uri.getPort() == 80); - assert (uri.getAuthority() == "192.0.2.16:80"); - assert (uri.getPath().empty()); - assert (uri.getQuery().empty()); - assert (uri.getFragment().empty()); - - uri = "urn:oasis:names:specification:docbook:dtd:xml:4.1.2"; - assert (uri.getScheme() == "urn"); - assert (uri.getUserInfo().empty()); - assert (uri.getHost().empty()); - assert (uri.getPort() == 0); - assert (uri.getAuthority().empty()); - assert (uri.getPath() == "oasis:names:specification:docbook:dtd:xml:4.1.2"); - assert (uri.getQuery().empty()); - assert (uri.getFragment().empty()); - - uri = ""; - assert (uri.getScheme().empty()); - assert (uri.getAuthority().empty()); - assert (uri.getUserInfo().empty()); - assert (uri.getHost().empty()); - assert (uri.getPort() == 0); - assert (uri.getPath().empty()); - assert (uri.getQuery().empty()); - assert (uri.getFragment().empty()); - assert (uri.empty()); - - // relative references - - uri = "/foo/bar"; - assert (uri.getScheme().empty()); - assert (uri.getAuthority().empty()); - assert (uri.getUserInfo().empty()); - assert (uri.getHost().empty()); - assert (uri.getPort() == 0); - assert (uri.getPath() == "/foo/bar"); - assert (uri.getQuery().empty()); - assert (uri.getFragment().empty()); - assert (uri.isRelative()); - - uri = "./foo/bar"; - assert (uri.getScheme().empty()); - assert (uri.getAuthority().empty()); - assert (uri.getUserInfo().empty()); - assert (uri.getHost().empty()); - assert (uri.getPort() == 0); - assert (uri.getPath() == "./foo/bar"); - assert (uri.getQuery().empty()); - assert (uri.getFragment().empty()); - assert (uri.isRelative()); - - uri = "../foo/bar"; - assert (uri.getScheme().empty()); - assert (uri.getAuthority().empty()); - assert (uri.getUserInfo().empty()); - assert (uri.getHost().empty()); - assert (uri.getPort() == 0); - assert (uri.getPath() == "../foo/bar"); - assert (uri.getQuery().empty()); - assert (uri.getFragment().empty()); - assert (uri.isRelative()); - - uri = "index.html"; - assert (uri.getScheme().empty()); - assert (uri.getAuthority().empty()); - assert (uri.getUserInfo().empty()); - assert (uri.getHost().empty()); - assert (uri.getPort() == 0); - assert (uri.getPath() == "index.html"); - assert (uri.getQuery().empty()); - assert (uri.getFragment().empty()); - assert (uri.isRelative()); - - uri = "index.html#frag"; - assert (uri.getScheme().empty()); - assert (uri.getAuthority().empty()); - assert (uri.getUserInfo().empty()); - assert (uri.getHost().empty()); - assert (uri.getPort() == 0); - assert (uri.getPath() == "index.html"); - assert (uri.getQuery().empty()); - assert (uri.getFragment() == "frag"); - assert (uri.isRelative()); - - uri = "?query=test"; - assert (uri.getScheme().empty()); - assert (uri.getAuthority().empty()); - assert (uri.getUserInfo().empty()); - assert (uri.getHost().empty()); - assert (uri.getPort() == 0); - assert (uri.getPath().empty()); - assert (uri.getQuery() == "query=test"); - assert (uri.getFragment().empty()); - assert (uri.isRelative()); - - uri = "?query=test#frag"; - assert (uri.getScheme().empty()); - assert (uri.getAuthority().empty()); - assert (uri.getUserInfo().empty()); - assert (uri.getHost().empty()); - assert (uri.getPort() == 0); - assert (uri.getPath().empty()); - assert (uri.getQuery() == "query=test"); - assert (uri.getFragment() == "frag"); - assert (uri.isRelative()); - - uri = "#frag"; - assert (uri.getScheme().empty()); - assert (uri.getAuthority().empty()); - assert (uri.getUserInfo().empty()); - assert (uri.getHost().empty()); - assert (uri.getPort() == 0); - assert (uri.getPath().empty()); - assert (uri.getQuery().empty()); - assert (uri.getFragment() == "frag"); - assert (uri.isRelative()); - - uri = "#"; - assert (uri.getScheme().empty()); - assert (uri.getAuthority().empty()); - assert (uri.getUserInfo().empty()); - assert (uri.getHost().empty()); - assert (uri.getPort() == 0); - assert (uri.getPath().empty()); - assert (uri.getQuery().empty()); - assert (uri.getFragment().empty()); - assert (uri.isRelative()); - - uri = "file:///a/b/c"; - assert (uri.getScheme() == "file"); - assert (uri.getAuthority().empty()); - assert (uri.getUserInfo().empty()); - assert (uri.getHost().empty()); - assert (uri.getPort() == 0); - assert (uri.getPath() == "/a/b/c"); - assert (uri.getQuery().empty()); - assert (uri.getFragment().empty()); - assert (!uri.isRelative()); - - uri = "file://localhost/a/b/c"; - assert (uri.getScheme() == "file"); - assert (uri.getAuthority() == "localhost"); - assert (uri.getUserInfo().empty()); - assert (uri.getHost() == "localhost"); - assert (uri.getPort() == 0); - assert (uri.getPath() == "/a/b/c"); - assert (uri.getQuery().empty()); - assert (uri.getFragment().empty()); - assert (!uri.isRelative()); - - uri = "file:///c:/Windows/system32/"; - assert (uri.getScheme() == "file"); - assert (uri.getAuthority().empty()); - assert (uri.getUserInfo().empty()); - assert (uri.getHost().empty()); - assert (uri.getPort() == 0); - assert (uri.getPath() == "/c:/Windows/system32/"); - assert (uri.getQuery().empty()); - assert (uri.getFragment().empty()); - assert (!uri.isRelative()); - - uri = "./c:/Windows/system32/"; - assert (uri.getScheme().empty()); - assert (uri.getAuthority().empty()); - assert (uri.getUserInfo().empty()); - assert (uri.getHost().empty()); - assert (uri.getPort() == 0); - assert (uri.getPath() == "./c:/Windows/system32/"); - assert (uri.getQuery().empty()); - assert (uri.getFragment().empty()); - assert (uri.isRelative()); - -} - - -void URITest::testToString() -{ - URI uri("http://www.appinf.com"); - assert (uri.toString() == "http://www.appinf.com"); - - uri = "http://www.appinf.com/"; - assert (uri.toString() == "http://www.appinf.com/"); - - uri = "ftp://anonymous@ftp.appinf.com/pub/"; - assert (uri.toString() == "ftp://anonymous@ftp.appinf.com/pub/"); - - uri = "https://www.appinf.com/index.html#top"; - assert (uri.toString() == "https://www.appinf.com/index.html#top"); - - uri = "http://www.appinf.com/search.cgi?keyword=test&scope=all"; - assert (uri.toString() == "http://www.appinf.com/search.cgi?keyword=test&scope=all"); - - uri = "http://www.appinf.com/search.cgi?keyword=test&scope=all#result"; - assert (uri.toString() == "http://www.appinf.com/search.cgi?keyword=test&scope=all#result"); - - uri = "http://www.appinf.com/search.cgi?keyword=test%20encoded&scope=all#result"; - assert (uri.toString() == "http://www.appinf.com/search.cgi?keyword=test%20encoded&scope=all#result"); - - uri = "ldap://[2001:db8::7]/c=GB?objectClass?one"; - assert (uri.toString() == "ldap://[2001:db8::7]/c=GB?objectClass?one"); - - uri = "mailto:John.Doe@example.com"; - assert (uri.toString() == "mailto:John.Doe@example.com"); - - uri = "tel:+1-816-555-1212"; - assert (uri.toString() == "tel:+1-816-555-1212"); - - uri = "telnet://192.0.2.16:80"; - assert (uri.toString() == "telnet://192.0.2.16:80"); - - uri = "urn:oasis:names:specification:docbook:dtd:xml:4.1.2"; - assert (uri.toString() == "urn:oasis:names:specification:docbook:dtd:xml:4.1.2"); - - uri = ""; - assert (uri.toString() == ""); - - // relative references - - uri = "/foo/bar"; - assert (uri.toString() == "/foo/bar"); - - uri = "./foo/bar"; - assert (uri.toString() == "./foo/bar"); - - uri = "../foo/bar"; - assert (uri.toString() == "../foo/bar"); - - uri = "//foo/bar"; - assert (uri.toString() == "//foo/bar"); - - uri = "index.html"; - assert (uri.toString() == "index.html"); - - uri = "index.html#frag"; - assert (uri.toString() == "index.html#frag"); - - uri = "?query=test"; - assert (uri.toString() == "?query=test"); - - uri = "?query=test#frag"; - assert (uri.toString() == "?query=test#frag"); - - uri = "#frag"; - assert (uri.toString() == "#frag"); - - uri = "#"; - assert (uri.toString() == ""); - - uri = "file:///a/b/c"; - assert (uri.toString() == "file:///a/b/c"); - - uri = "file://localhost/a/b/c"; - assert (uri.toString() == "file://localhost/a/b/c"); - - uri = "file:///c:/Windows/system32/"; - assert (uri.toString() == "file:///c:/Windows/system32/"); - - uri = "./c:/Windows/system32/"; - assert (uri.toString() == "./c:/Windows/system32/"); -} - - -void URITest::testCompare() -{ - URI uri1("http://www.appinf.com"); - URI uri2("HTTP://www.appinf.com:80"); - assert (uri1 == uri2); - assert (uri1 == "http://www.appinf.com:"); - assert (uri1 != "http://www.google.com"); - - uri1 = "/foo/bar"; - assert (uri1 == "/foo/bar"); - assert (uri1 != "/foo/baz"); - - uri1 = "?query"; - assert (uri1 == "?query"); - assert (uri1 != "?query2"); - - uri1 = "#frag"; - assert (uri1 == "#frag"); - assert (uri1 != "#frag2"); - - uri1 = "/index.html#frag"; - assert (uri1 == "/index.html#frag"); - assert (uri1 != "/index.html"); -} - - -void URITest::testNormalize() -{ - URI uri("http://www.appinf.com"); - uri.normalize(); - assert (uri.toString() == "http://www.appinf.com"); - - uri = "http://www.appinf.com/"; - uri.normalize(); - assert (uri.toString() == "http://www.appinf.com/"); - - uri = "http://www.appinf.com/foo/bar/./index.html"; - uri.normalize(); - assert (uri.toString() == "http://www.appinf.com/foo/bar/index.html"); - - uri = "http://www.appinf.com/foo/bar/../index.html"; - uri.normalize(); - assert (uri.toString() == "http://www.appinf.com/foo/index.html"); - - uri = "http://www.appinf.com/foo/./bar/../index.html"; - uri.normalize(); - assert (uri.toString() == "http://www.appinf.com/foo/index.html"); - - uri = "http://www.appinf.com/foo/./bar/../index.html"; - uri.normalize(); - assert (uri.toString() == "http://www.appinf.com/foo/index.html"); - - uri = "http://www.appinf.com/foo/bar/../../index.html"; - uri.normalize(); - assert (uri.toString() == "http://www.appinf.com/index.html"); - - uri = "http://www.appinf.com/foo/bar/../../../index.html"; - uri.normalize(); - assert (uri.toString() == "http://www.appinf.com/index.html"); - - uri = "http://www.appinf.com/foo/bar/.././../index.html"; - uri.normalize(); - assert (uri.toString() == "http://www.appinf.com/index.html"); - - uri = "http://www.appinf.com/./foo/bar/index.html"; - uri.normalize(); - assert (uri.toString() == "http://www.appinf.com/foo/bar/index.html"); - - uri = "http://www.appinf.com/../foo/bar/index.html"; - uri.normalize(); - assert (uri.toString() == "http://www.appinf.com/foo/bar/index.html"); - - uri = "http://www.appinf.com/../foo/bar/"; - uri.normalize(); - assert (uri.toString() == "http://www.appinf.com/foo/bar/"); - - uri = "http://www.appinf.com/../foo/../"; - uri.normalize(); - assert (uri.toString() == "http://www.appinf.com/"); - - uri = "file:///c:/Windows/system32/"; - uri.normalize(); - assert (uri.toString() == "file:///c:/Windows/system32/"); - - uri.clear(); - uri.setPath("c:/windows/system32/"); - uri.normalize(); - assert (uri.toString() == "./c:/windows/system32/"); -} - - -void URITest::testResolve() -{ - URI uri("http://www.appinf.com"); - - uri.resolve("/index.html"); - assert (uri.toString() == "http://www.appinf.com/index.html"); - - uri.resolve("#frag"); - assert (uri.toString() == "http://www.appinf.com/index.html#frag"); - - uri = "http://www.appinf.com/html"; - uri.resolve("../images/foo.gif"); - assert (uri.toString() == "http://www.appinf.com/images/foo.gif"); - - uri = "http://www.appinf.com/html/"; - uri.resolve("."); - assert (uri.toString() == "http://www.appinf.com/html/"); - - uri = "http://www.appinf.com/html/"; - uri.resolve("."); - assert (uri.toString() == "http://www.appinf.com/html/"); - - uri = "http://www.appinf.com/html/"; - uri.resolve(".."); - assert (uri.toString() == "http://www.appinf.com/"); - - uri = "http://www.appinf.com/html/"; - uri.resolve("index.html"); - assert (uri.toString() == "http://www.appinf.com/html/index.html"); - - uri = "http://www.appinf.com/html/"; - uri.resolve("/index.html"); - assert (uri.toString() == "http://www.appinf.com/index.html"); - - uri = "/a/b/c/d/e"; - uri.resolve("./../../f/./g"); - assert (uri.toString() == "/a/b/f/g"); - - uri = "/a/b/../c/"; - uri.resolve("../d"); - assert (uri.toString() == "/a/d"); - - uri = "/a/b/../c/"; - uri.resolve("../d/"); - assert (uri.toString() == "/a/d/"); - - uri = "/a/b/c/"; - uri.resolve("../../../../d/"); - assert (uri.toString() == "/d/"); - - uri = "/a/b/c/"; - uri.resolve("%2e%2e/%2e%2e/%2e%2e/../d/"); - assert (uri.toString() == "/d/"); - - uri = "/a/b/c/"; - uri.resolve(""); - assert (uri.toString() == "/a/b/c/"); - - uri = "/a/b/c/"; - uri.resolve("/d/"); - assert (uri.toString() == "/d/"); - - uri = "/a/b/c"; - uri.resolve(""); - assert (uri.toString() == "/a/b/c"); - - uri = "/a/b/c"; - uri.resolve("?query=test"); - assert (uri.toString() == "/a/b/c?query=test"); - - uri = "/a/b/c"; - uri.resolve("#frag"); - assert (uri.toString() == "/a/b/c#frag"); - - uri = "http://www.appinf.com/html/"; - uri.resolve("http://www.google.com/"); - assert (uri.toString() == "http://www.google.com/"); - - uri = "http://www.appinf.com/"; - URI uri2(uri, "index.html"); - assert (uri2.toString() == "http://www.appinf.com/index.html"); - - uri = "index.html"; - URI uri3(uri, "search.html"); - assert (uri3.toString() == "search.html"); -} - - -void URITest::testSwap() -{ - URI uri1("http://www.appinf.com/search.cgi?keyword=test%20encoded&scope=all#result"); - URI uri2("mailto:John.Doe@example.com"); - - uri1.swap(uri2); - assert (uri1.toString() == "mailto:John.Doe@example.com"); - assert (uri2.toString() == "http://www.appinf.com/search.cgi?keyword=test%20encoded&scope=all#result"); -} - - -void URITest::setUp() -{ -} - - -void URITest::tearDown() -{ -} - - -CppUnit::Test* URITest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("URITest"); - - CppUnit_addTest(pSuite, URITest, testConstruction); - CppUnit_addTest(pSuite, URITest, testParse); - CppUnit_addTest(pSuite, URITest, testToString); - CppUnit_addTest(pSuite, URITest, testCompare); - CppUnit_addTest(pSuite, URITest, testNormalize); - CppUnit_addTest(pSuite, URITest, testResolve); - CppUnit_addTest(pSuite, URITest, testSwap); - - return pSuite; -} +// +// URITest.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/URITest.cpp#1 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "URITest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/URI.h" + + +using Poco::URI; + + +URITest::URITest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +URITest::~URITest() +{ +} + + +void URITest::testConstruction() +{ + URI uri; + assert (uri.getScheme().empty()); + assert (uri.getAuthority().empty()); + assert (uri.getUserInfo().empty()); + assert (uri.getHost().empty()); + assert (uri.getPort() == 0); + assert (uri.getPath().empty()); + assert (uri.getQuery().empty()); + assert (uri.getFragment().empty()); + + uri.setScheme("ftp"); + assert (uri.getScheme() == "ftp"); + assert (uri.getPort() == 21); + + uri.setScheme("HTTP"); + assert (uri.getScheme() == "http"); + + uri.setAuthority("www.appinf.com"); + assert (uri.getAuthority() == "www.appinf.com"); + assert (uri.getPort() == 80); + + uri.setAuthority("user@services.appinf.com:8000"); + assert (uri.getUserInfo() == "user"); + assert (uri.getHost() == "services.appinf.com"); + assert (uri.getPort() == 8000); + + uri.setPath("/index.html"); + assert (uri.getPath() == "/index.html"); + + uri.setPath("/file%20with%20spaces.html"); + assert (uri.getPath() == "/file with spaces.html"); + + uri.setPathEtc("/query.cgi?query=foo"); + assert (uri.getPath() == "/query.cgi"); + assert (uri.getQuery() == "query=foo"); + assert (uri.getFragment().empty()); + assert (uri.getPathEtc() == "/query.cgi?query=foo"); + assert (uri.getPathAndQuery() == "/query.cgi?query=foo"); + + uri.setPathEtc("/query.cgi?query=bar#frag"); + assert (uri.getPath() == "/query.cgi"); + assert (uri.getQuery() == "query=bar"); + assert (uri.getFragment() == "frag"); + assert (uri.getPathEtc() == "/query.cgi?query=bar#frag"); + assert (uri.getPathAndQuery() == "/query.cgi?query=bar"); + + uri.setQuery("query=test"); + assert (uri.getQuery() == "query=test"); + + uri.setFragment("result"); + assert (uri.getFragment() == "result"); + + URI uri2("file", "/home/guenter/foo.bar"); + assert (uri2.getScheme() == "file"); + assert (uri2.getPath() == "/home/guenter/foo.bar"); + + URI uri3("http", "www.appinf.com", "/index.html"); + assert (uri3.getScheme() == "http"); + assert (uri3.getAuthority() == "www.appinf.com"); + assert (uri3.getPath() == "/index.html"); + + URI uri4("http", "www.appinf.com:8000", "/index.html"); + assert (uri4.getScheme() == "http"); + assert (uri4.getAuthority() == "www.appinf.com:8000"); + assert (uri4.getPath() == "/index.html"); + + URI uri5("http", "user@www.appinf.com:8000", "/index.html"); + assert (uri5.getScheme() == "http"); + assert (uri5.getUserInfo() == "user"); + assert (uri5.getHost() == "www.appinf.com"); + assert (uri5.getPort() == 8000); + assert (uri5.getAuthority() == "user@www.appinf.com:8000"); + assert (uri5.getPath() == "/index.html"); + + URI uri6("http", "user@www.appinf.com:80", "/index.html"); + assert (uri6.getScheme() == "http"); + assert (uri6.getUserInfo() == "user"); + assert (uri6.getHost() == "www.appinf.com"); + assert (uri6.getPort() == 80); + assert (uri6.getAuthority() == "user@www.appinf.com"); + assert (uri6.getPath() == "/index.html"); + + URI uri7("http", "user@www.appinf.com:", "/index.html"); + assert (uri7.getScheme() == "http"); + assert (uri7.getUserInfo() == "user"); + assert (uri7.getHost() == "www.appinf.com"); + assert (uri7.getPort() == 80); + assert (uri7.getAuthority() == "user@www.appinf.com"); + assert (uri7.getPath() == "/index.html"); + + URI uri8("http", "www.appinf.com", "/index.html", "query=test"); + assert (uri8.getScheme() == "http"); + assert (uri8.getAuthority() == "www.appinf.com"); + assert (uri8.getPath() == "/index.html"); + assert (uri8.getQuery() == "query=test"); + + URI uri9("http", "www.appinf.com", "/index.html", "query=test", "fragment"); + assert (uri9.getScheme() == "http"); + assert (uri9.getAuthority() == "www.appinf.com"); + assert (uri9.getPath() == "/index.html"); + assert (uri9.getPathEtc() == "/index.html?query=test#fragment"); + assert (uri9.getQuery() == "query=test"); + assert (uri9.getFragment() == "fragment"); + + uri9.clear(); + assert (uri9.getScheme().empty()); + assert (uri9.getAuthority().empty()); + assert (uri9.getUserInfo().empty()); + assert (uri9.getHost().empty()); + assert (uri9.getPort() == 0); + assert (uri9.getPath().empty()); + assert (uri9.getQuery().empty()); + assert (uri9.getFragment().empty()); + + URI uri10("ldap", "[2001:db8::7]", "/c=GB?objectClass?one"); + assert (uri10.getScheme() == "ldap"); + assert (uri10.getUserInfo().empty()); + assert (uri10.getHost() == "[2001:db8::7]"); + assert (uri10.getPort() == 389); + assert (uri10.getAuthority() == "[2001:db8::7]"); + assert (uri10.getPathEtc() == "/c=GB?objectClass?one"); + + URI uri11("http", "www.appinf.com", "/index.html?query=test#fragment"); + assert (uri11.getScheme() == "http"); + assert (uri11.getAuthority() == "www.appinf.com"); + assert (uri11.getPath() == "/index.html"); + assert (uri11.getPathEtc() == "/index.html?query=test#fragment"); + assert (uri11.getQuery() == "query=test"); + assert (uri11.getFragment() == "fragment"); + +} + + +void URITest::testParse() +{ + URI uri("http://www.appinf.com"); + assert (uri.getScheme() == "http"); + assert (uri.getAuthority() == "www.appinf.com"); + assert (uri.getPath().empty()); + assert (uri.getQuery().empty()); + assert (uri.getFragment().empty()); + assert (!uri.isRelative()); + + uri = "http://www.appinf.com/"; + assert (uri.getScheme() == "http"); + assert (uri.getAuthority() == "www.appinf.com"); + assert (uri.getPath() == "/"); + assert (uri.getQuery().empty()); + assert (uri.getFragment().empty()); + assert (!uri.isRelative()); + + uri = "ftp://anonymous@ftp.appinf.com/pub/"; + assert (uri.getScheme() == "ftp"); + assert (uri.getUserInfo() == "anonymous"); + assert (uri.getHost() == "ftp.appinf.com"); + assert (uri.getPort() == 21); + assert (uri.getAuthority() == "anonymous@ftp.appinf.com"); + assert (uri.getPath() == "/pub/"); + assert (uri.getQuery().empty()); + assert (uri.getFragment().empty()); + assert (!uri.isRelative()); + assert (!uri.isRelative()); + + uri = "https://www.appinf.com/index.html#top"; + assert (uri.getScheme() == "https"); + assert (uri.getHost() == "www.appinf.com"); + assert (uri.getPort() == 443); + assert (uri.getPath() == "/index.html"); + assert (uri.getQuery().empty()); + assert (uri.getFragment() == "top"); + assert (!uri.isRelative()); + + uri = "http://www.appinf.com/search.cgi?keyword=test&scope=all"; + assert (uri.getScheme() == "http"); + assert (uri.getHost() == "www.appinf.com"); + assert (uri.getPort() == 80); + assert (uri.getPath() == "/search.cgi"); + assert (uri.getQuery() == "keyword=test&scope=all"); + assert (uri.getFragment().empty()); + assert (!uri.isRelative()); + + uri = "http://www.appinf.com/search.cgi?keyword=test&scope=all#result"; + assert (uri.getScheme() == "http"); + assert (uri.getHost() == "www.appinf.com"); + assert (uri.getPort() == 80); + assert (uri.getPath() == "/search.cgi"); + assert (uri.getQuery() == "keyword=test&scope=all"); + assert (uri.getFragment() == "result"); + assert (!uri.isRelative()); + + uri = "http://www.appinf.com/search.cgi?keyword=test%20encoded&scope=all#result"; + assert (uri.getScheme() == "http"); + assert (uri.getHost() == "www.appinf.com"); + assert (uri.getPort() == 80); + assert (uri.getPath() == "/search.cgi"); + assert (uri.getQuery() == "keyword=test encoded&scope=all"); + assert (uri.getFragment() == "result"); + assert (!uri.isRelative()); + + uri = "ldap://[2001:db8::7]/c=GB?objectClass?one"; + assert (uri.getScheme() == "ldap"); + assert (uri.getUserInfo().empty()); + assert (uri.getHost() == "[2001:db8::7]"); + assert (uri.getPort() == 389); + assert (uri.getAuthority() == "[2001:db8::7]"); + assert (uri.getPath() == "/c=GB"); + assert (uri.getQuery() == "objectClass?one"); + assert (uri.getFragment().empty()); + + uri = "mailto:John.Doe@example.com"; + assert (uri.getScheme() == "mailto"); + assert (uri.getUserInfo().empty()); + assert (uri.getHost().empty()); + assert (uri.getPort() == 0); + assert (uri.getAuthority().empty()); + assert (uri.getPath() == "John.Doe@example.com"); + assert (uri.getQuery().empty()); + assert (uri.getFragment().empty()); + + uri = "tel:+1-816-555-1212"; + assert (uri.getScheme() == "tel"); + assert (uri.getUserInfo().empty()); + assert (uri.getHost().empty()); + assert (uri.getPort() == 0); + assert (uri.getAuthority().empty()); + assert (uri.getPath() == "+1-816-555-1212"); + assert (uri.getQuery().empty()); + assert (uri.getFragment().empty()); + + uri = "telnet://192.0.2.16:80"; + assert (uri.getScheme() == "telnet"); + assert (uri.getUserInfo().empty()); + assert (uri.getHost() == "192.0.2.16"); + assert (uri.getPort() == 80); + assert (uri.getAuthority() == "192.0.2.16:80"); + assert (uri.getPath().empty()); + assert (uri.getQuery().empty()); + assert (uri.getFragment().empty()); + + uri = "urn:oasis:names:specification:docbook:dtd:xml:4.1.2"; + assert (uri.getScheme() == "urn"); + assert (uri.getUserInfo().empty()); + assert (uri.getHost().empty()); + assert (uri.getPort() == 0); + assert (uri.getAuthority().empty()); + assert (uri.getPath() == "oasis:names:specification:docbook:dtd:xml:4.1.2"); + assert (uri.getQuery().empty()); + assert (uri.getFragment().empty()); + + uri = ""; + assert (uri.getScheme().empty()); + assert (uri.getAuthority().empty()); + assert (uri.getUserInfo().empty()); + assert (uri.getHost().empty()); + assert (uri.getPort() == 0); + assert (uri.getPath().empty()); + assert (uri.getQuery().empty()); + assert (uri.getFragment().empty()); + assert (uri.empty()); + + // relative references + + uri = "/foo/bar"; + assert (uri.getScheme().empty()); + assert (uri.getAuthority().empty()); + assert (uri.getUserInfo().empty()); + assert (uri.getHost().empty()); + assert (uri.getPort() == 0); + assert (uri.getPath() == "/foo/bar"); + assert (uri.getQuery().empty()); + assert (uri.getFragment().empty()); + assert (uri.isRelative()); + + uri = "./foo/bar"; + assert (uri.getScheme().empty()); + assert (uri.getAuthority().empty()); + assert (uri.getUserInfo().empty()); + assert (uri.getHost().empty()); + assert (uri.getPort() == 0); + assert (uri.getPath() == "./foo/bar"); + assert (uri.getQuery().empty()); + assert (uri.getFragment().empty()); + assert (uri.isRelative()); + + uri = "../foo/bar"; + assert (uri.getScheme().empty()); + assert (uri.getAuthority().empty()); + assert (uri.getUserInfo().empty()); + assert (uri.getHost().empty()); + assert (uri.getPort() == 0); + assert (uri.getPath() == "../foo/bar"); + assert (uri.getQuery().empty()); + assert (uri.getFragment().empty()); + assert (uri.isRelative()); + + uri = "index.html"; + assert (uri.getScheme().empty()); + assert (uri.getAuthority().empty()); + assert (uri.getUserInfo().empty()); + assert (uri.getHost().empty()); + assert (uri.getPort() == 0); + assert (uri.getPath() == "index.html"); + assert (uri.getQuery().empty()); + assert (uri.getFragment().empty()); + assert (uri.isRelative()); + + uri = "index.html#frag"; + assert (uri.getScheme().empty()); + assert (uri.getAuthority().empty()); + assert (uri.getUserInfo().empty()); + assert (uri.getHost().empty()); + assert (uri.getPort() == 0); + assert (uri.getPath() == "index.html"); + assert (uri.getQuery().empty()); + assert (uri.getFragment() == "frag"); + assert (uri.isRelative()); + + uri = "?query=test"; + assert (uri.getScheme().empty()); + assert (uri.getAuthority().empty()); + assert (uri.getUserInfo().empty()); + assert (uri.getHost().empty()); + assert (uri.getPort() == 0); + assert (uri.getPath().empty()); + assert (uri.getQuery() == "query=test"); + assert (uri.getFragment().empty()); + assert (uri.isRelative()); + + uri = "?query=test#frag"; + assert (uri.getScheme().empty()); + assert (uri.getAuthority().empty()); + assert (uri.getUserInfo().empty()); + assert (uri.getHost().empty()); + assert (uri.getPort() == 0); + assert (uri.getPath().empty()); + assert (uri.getQuery() == "query=test"); + assert (uri.getFragment() == "frag"); + assert (uri.isRelative()); + + uri = "#frag"; + assert (uri.getScheme().empty()); + assert (uri.getAuthority().empty()); + assert (uri.getUserInfo().empty()); + assert (uri.getHost().empty()); + assert (uri.getPort() == 0); + assert (uri.getPath().empty()); + assert (uri.getQuery().empty()); + assert (uri.getFragment() == "frag"); + assert (uri.isRelative()); + + uri = "#"; + assert (uri.getScheme().empty()); + assert (uri.getAuthority().empty()); + assert (uri.getUserInfo().empty()); + assert (uri.getHost().empty()); + assert (uri.getPort() == 0); + assert (uri.getPath().empty()); + assert (uri.getQuery().empty()); + assert (uri.getFragment().empty()); + assert (uri.isRelative()); + + uri = "file:///a/b/c"; + assert (uri.getScheme() == "file"); + assert (uri.getAuthority().empty()); + assert (uri.getUserInfo().empty()); + assert (uri.getHost().empty()); + assert (uri.getPort() == 0); + assert (uri.getPath() == "/a/b/c"); + assert (uri.getQuery().empty()); + assert (uri.getFragment().empty()); + assert (!uri.isRelative()); + + uri = "file://localhost/a/b/c"; + assert (uri.getScheme() == "file"); + assert (uri.getAuthority() == "localhost"); + assert (uri.getUserInfo().empty()); + assert (uri.getHost() == "localhost"); + assert (uri.getPort() == 0); + assert (uri.getPath() == "/a/b/c"); + assert (uri.getQuery().empty()); + assert (uri.getFragment().empty()); + assert (!uri.isRelative()); + + uri = "file:///c:/Windows/system32/"; + assert (uri.getScheme() == "file"); + assert (uri.getAuthority().empty()); + assert (uri.getUserInfo().empty()); + assert (uri.getHost().empty()); + assert (uri.getPort() == 0); + assert (uri.getPath() == "/c:/Windows/system32/"); + assert (uri.getQuery().empty()); + assert (uri.getFragment().empty()); + assert (!uri.isRelative()); + + uri = "./c:/Windows/system32/"; + assert (uri.getScheme().empty()); + assert (uri.getAuthority().empty()); + assert (uri.getUserInfo().empty()); + assert (uri.getHost().empty()); + assert (uri.getPort() == 0); + assert (uri.getPath() == "./c:/Windows/system32/"); + assert (uri.getQuery().empty()); + assert (uri.getFragment().empty()); + assert (uri.isRelative()); + +} + + +void URITest::testToString() +{ + URI uri("http://www.appinf.com"); + assert (uri.toString() == "http://www.appinf.com"); + + uri = "http://www.appinf.com/"; + assert (uri.toString() == "http://www.appinf.com/"); + + uri = "ftp://anonymous@ftp.appinf.com/pub/"; + assert (uri.toString() == "ftp://anonymous@ftp.appinf.com/pub/"); + + uri = "https://www.appinf.com/index.html#top"; + assert (uri.toString() == "https://www.appinf.com/index.html#top"); + + uri = "http://www.appinf.com/search.cgi?keyword=test&scope=all"; + assert (uri.toString() == "http://www.appinf.com/search.cgi?keyword=test&scope=all"); + + uri = "http://www.appinf.com/search.cgi?keyword=test&scope=all#result"; + assert (uri.toString() == "http://www.appinf.com/search.cgi?keyword=test&scope=all#result"); + + uri = "http://www.appinf.com/search.cgi?keyword=test%20encoded&scope=all#result"; + assert (uri.toString() == "http://www.appinf.com/search.cgi?keyword=test%20encoded&scope=all#result"); + + uri = "ldap://[2001:db8::7]/c=GB?objectClass?one"; + assert (uri.toString() == "ldap://[2001:db8::7]/c=GB?objectClass?one"); + + uri = "mailto:John.Doe@example.com"; + assert (uri.toString() == "mailto:John.Doe@example.com"); + + uri = "tel:+1-816-555-1212"; + assert (uri.toString() == "tel:+1-816-555-1212"); + + uri = "telnet://192.0.2.16:80"; + assert (uri.toString() == "telnet://192.0.2.16:80"); + + uri = "urn:oasis:names:specification:docbook:dtd:xml:4.1.2"; + assert (uri.toString() == "urn:oasis:names:specification:docbook:dtd:xml:4.1.2"); + + uri = ""; + assert (uri.toString() == ""); + + // relative references + + uri = "/foo/bar"; + assert (uri.toString() == "/foo/bar"); + + uri = "./foo/bar"; + assert (uri.toString() == "./foo/bar"); + + uri = "../foo/bar"; + assert (uri.toString() == "../foo/bar"); + + uri = "//foo/bar"; + assert (uri.toString() == "//foo/bar"); + + uri = "index.html"; + assert (uri.toString() == "index.html"); + + uri = "index.html#frag"; + assert (uri.toString() == "index.html#frag"); + + uri = "?query=test"; + assert (uri.toString() == "?query=test"); + + uri = "?query=test#frag"; + assert (uri.toString() == "?query=test#frag"); + + uri = "#frag"; + assert (uri.toString() == "#frag"); + + uri = "#"; + assert (uri.toString() == ""); + + uri = "file:///a/b/c"; + assert (uri.toString() == "file:///a/b/c"); + + uri = "file://localhost/a/b/c"; + assert (uri.toString() == "file://localhost/a/b/c"); + + uri = "file:///c:/Windows/system32/"; + assert (uri.toString() == "file:///c:/Windows/system32/"); + + uri = "./c:/Windows/system32/"; + assert (uri.toString() == "./c:/Windows/system32/"); +} + + +void URITest::testCompare() +{ + URI uri1("http://www.appinf.com"); + URI uri2("HTTP://www.appinf.com:80"); + assert (uri1 == uri2); + assert (uri1 == "http://www.appinf.com:"); + assert (uri1 != "http://www.google.com"); + + uri1 = "/foo/bar"; + assert (uri1 == "/foo/bar"); + assert (uri1 != "/foo/baz"); + + uri1 = "?query"; + assert (uri1 == "?query"); + assert (uri1 != "?query2"); + + uri1 = "#frag"; + assert (uri1 == "#frag"); + assert (uri1 != "#frag2"); + + uri1 = "/index.html#frag"; + assert (uri1 == "/index.html#frag"); + assert (uri1 != "/index.html"); +} + + +void URITest::testNormalize() +{ + URI uri("http://www.appinf.com"); + uri.normalize(); + assert (uri.toString() == "http://www.appinf.com"); + + uri = "http://www.appinf.com/"; + uri.normalize(); + assert (uri.toString() == "http://www.appinf.com/"); + + uri = "http://www.appinf.com/foo/bar/./index.html"; + uri.normalize(); + assert (uri.toString() == "http://www.appinf.com/foo/bar/index.html"); + + uri = "http://www.appinf.com/foo/bar/../index.html"; + uri.normalize(); + assert (uri.toString() == "http://www.appinf.com/foo/index.html"); + + uri = "http://www.appinf.com/foo/./bar/../index.html"; + uri.normalize(); + assert (uri.toString() == "http://www.appinf.com/foo/index.html"); + + uri = "http://www.appinf.com/foo/./bar/../index.html"; + uri.normalize(); + assert (uri.toString() == "http://www.appinf.com/foo/index.html"); + + uri = "http://www.appinf.com/foo/bar/../../index.html"; + uri.normalize(); + assert (uri.toString() == "http://www.appinf.com/index.html"); + + uri = "http://www.appinf.com/foo/bar/../../../index.html"; + uri.normalize(); + assert (uri.toString() == "http://www.appinf.com/index.html"); + + uri = "http://www.appinf.com/foo/bar/.././../index.html"; + uri.normalize(); + assert (uri.toString() == "http://www.appinf.com/index.html"); + + uri = "http://www.appinf.com/./foo/bar/index.html"; + uri.normalize(); + assert (uri.toString() == "http://www.appinf.com/foo/bar/index.html"); + + uri = "http://www.appinf.com/../foo/bar/index.html"; + uri.normalize(); + assert (uri.toString() == "http://www.appinf.com/foo/bar/index.html"); + + uri = "http://www.appinf.com/../foo/bar/"; + uri.normalize(); + assert (uri.toString() == "http://www.appinf.com/foo/bar/"); + + uri = "http://www.appinf.com/../foo/../"; + uri.normalize(); + assert (uri.toString() == "http://www.appinf.com/"); + + uri = "file:///c:/Windows/system32/"; + uri.normalize(); + assert (uri.toString() == "file:///c:/Windows/system32/"); + + uri.clear(); + uri.setPath("c:/windows/system32/"); + uri.normalize(); + assert (uri.toString() == "./c:/windows/system32/"); +} + + +void URITest::testResolve() +{ + URI uri("http://www.appinf.com"); + + uri.resolve("/index.html"); + assert (uri.toString() == "http://www.appinf.com/index.html"); + + uri.resolve("#frag"); + assert (uri.toString() == "http://www.appinf.com/index.html#frag"); + + uri = "http://www.appinf.com/html"; + uri.resolve("../images/foo.gif"); + assert (uri.toString() == "http://www.appinf.com/images/foo.gif"); + + uri = "http://www.appinf.com/html/"; + uri.resolve("."); + assert (uri.toString() == "http://www.appinf.com/html/"); + + uri = "http://www.appinf.com/html/"; + uri.resolve("."); + assert (uri.toString() == "http://www.appinf.com/html/"); + + uri = "http://www.appinf.com/html/"; + uri.resolve(".."); + assert (uri.toString() == "http://www.appinf.com/"); + + uri = "http://www.appinf.com/html/"; + uri.resolve("index.html"); + assert (uri.toString() == "http://www.appinf.com/html/index.html"); + + uri = "http://www.appinf.com/html/"; + uri.resolve("/index.html"); + assert (uri.toString() == "http://www.appinf.com/index.html"); + + uri = "/a/b/c/d/e"; + uri.resolve("./../../f/./g"); + assert (uri.toString() == "/a/b/f/g"); + + uri = "/a/b/../c/"; + uri.resolve("../d"); + assert (uri.toString() == "/a/d"); + + uri = "/a/b/../c/"; + uri.resolve("../d/"); + assert (uri.toString() == "/a/d/"); + + uri = "/a/b/c/"; + uri.resolve("../../../../d/"); + assert (uri.toString() == "/d/"); + + uri = "/a/b/c/"; + uri.resolve("%2e%2e/%2e%2e/%2e%2e/../d/"); + assert (uri.toString() == "/d/"); + + uri = "/a/b/c/"; + uri.resolve(""); + assert (uri.toString() == "/a/b/c/"); + + uri = "/a/b/c/"; + uri.resolve("/d/"); + assert (uri.toString() == "/d/"); + + uri = "/a/b/c"; + uri.resolve(""); + assert (uri.toString() == "/a/b/c"); + + uri = "/a/b/c"; + uri.resolve("?query=test"); + assert (uri.toString() == "/a/b/c?query=test"); + + uri = "/a/b/c"; + uri.resolve("#frag"); + assert (uri.toString() == "/a/b/c#frag"); + + uri = "http://www.appinf.com/html/"; + uri.resolve("http://www.google.com/"); + assert (uri.toString() == "http://www.google.com/"); + + uri = "http://www.appinf.com/"; + URI uri2(uri, "index.html"); + assert (uri2.toString() == "http://www.appinf.com/index.html"); + + uri = "index.html"; + URI uri3(uri, "search.html"); + assert (uri3.toString() == "search.html"); +} + + +void URITest::testSwap() +{ + URI uri1("http://www.appinf.com/search.cgi?keyword=test%20encoded&scope=all#result"); + URI uri2("mailto:John.Doe@example.com"); + + uri1.swap(uri2); + assert (uri1.toString() == "mailto:John.Doe@example.com"); + assert (uri2.toString() == "http://www.appinf.com/search.cgi?keyword=test%20encoded&scope=all#result"); +} + + +void URITest::setUp() +{ +} + + +void URITest::tearDown() +{ +} + + +CppUnit::Test* URITest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("URITest"); + + CppUnit_addTest(pSuite, URITest, testConstruction); + CppUnit_addTest(pSuite, URITest, testParse); + CppUnit_addTest(pSuite, URITest, testToString); + CppUnit_addTest(pSuite, URITest, testCompare); + CppUnit_addTest(pSuite, URITest, testNormalize); + CppUnit_addTest(pSuite, URITest, testResolve); + CppUnit_addTest(pSuite, URITest, testSwap); + + return pSuite; +} diff --git a/Foundation/testsuite/src/URITest.h b/Foundation/testsuite/src/URITest.h index 580c959f9..e182182a4 100644 --- a/Foundation/testsuite/src/URITest.h +++ b/Foundation/testsuite/src/URITest.h @@ -1,66 +1,66 @@ -// -// URITest.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/URITest.h#1 $ -// -// Definition of the URITest class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 URITest_INCLUDED -#define URITest_INCLUDED - - -#include "Poco/Foundation.h" -#include "CppUnit/TestCase.h" - - -class URITest: public CppUnit::TestCase -{ -public: - URITest(const std::string& name); - ~URITest(); - - void testConstruction(); - void testParse(); - void testToString(); - void testCompare(); - void testNormalize(); - void testResolve(); - void testSwap(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // URITest_INCLUDED +// +// URITest.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/URITest.h#1 $ +// +// Definition of the URITest class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 URITest_INCLUDED +#define URITest_INCLUDED + + +#include "Poco/Foundation.h" +#include "CppUnit/TestCase.h" + + +class URITest: public CppUnit::TestCase +{ +public: + URITest(const std::string& name); + ~URITest(); + + void testConstruction(); + void testParse(); + void testToString(); + void testCompare(); + void testNormalize(); + void testResolve(); + void testSwap(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // URITest_INCLUDED diff --git a/Foundation/testsuite/src/URITestSuite.cpp b/Foundation/testsuite/src/URITestSuite.cpp index 112abd2cc..70e1edbfd 100644 --- a/Foundation/testsuite/src/URITestSuite.cpp +++ b/Foundation/testsuite/src/URITestSuite.cpp @@ -1,46 +1,46 @@ -// -// URITestSuite.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/URITestSuite.cpp#1 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "URITestSuite.h" -#include "URITest.h" -#include "URIStreamOpenerTest.h" - - -CppUnit::Test* URITestSuite::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("URITestSuite"); - - pSuite->addTest(URITest::suite()); - pSuite->addTest(URIStreamOpenerTest::suite()); - - return pSuite; -} +// +// URITestSuite.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/URITestSuite.cpp#1 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "URITestSuite.h" +#include "URITest.h" +#include "URIStreamOpenerTest.h" + + +CppUnit::Test* URITestSuite::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("URITestSuite"); + + pSuite->addTest(URITest::suite()); + pSuite->addTest(URIStreamOpenerTest::suite()); + + return pSuite; +} diff --git a/Foundation/testsuite/src/URITestSuite.h b/Foundation/testsuite/src/URITestSuite.h index 84e49e962..4069d96bd 100644 --- a/Foundation/testsuite/src/URITestSuite.h +++ b/Foundation/testsuite/src/URITestSuite.h @@ -1,49 +1,49 @@ -// -// URITestSuite.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/URITestSuite.h#1 $ -// -// Definition of the URITestSuite class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 URITestSuite_INCLUDED -#define URITestSuite_INCLUDED - - -#include "CppUnit/TestSuite.h" - - -class URITestSuite -{ -public: - static CppUnit::Test* suite(); -}; - - -#endif // URITestSuite_INCLUDED +// +// URITestSuite.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/URITestSuite.h#1 $ +// +// Definition of the URITestSuite class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 URITestSuite_INCLUDED +#define URITestSuite_INCLUDED + + +#include "CppUnit/TestSuite.h" + + +class URITestSuite +{ +public: + static CppUnit::Test* suite(); +}; + + +#endif // URITestSuite_INCLUDED diff --git a/Foundation/testsuite/src/UUIDGeneratorTest.cpp b/Foundation/testsuite/src/UUIDGeneratorTest.cpp index b5d59db56..8fed34a34 100644 --- a/Foundation/testsuite/src/UUIDGeneratorTest.cpp +++ b/Foundation/testsuite/src/UUIDGeneratorTest.cpp @@ -1,129 +1,129 @@ -// -// UUIDGeneratorTest.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/UUIDGeneratorTest.cpp#1 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "UUIDGeneratorTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/UUIDGenerator.h" -#include "Poco/UUID.h" -#include - - -using Poco::UUIDGenerator; -using Poco::UUID; - - -UUIDGeneratorTest::UUIDGeneratorTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -UUIDGeneratorTest::~UUIDGeneratorTest() -{ -} - - -void UUIDGeneratorTest::testTimeBased() -{ - UUIDGenerator& gen = UUIDGenerator::defaultGenerator(); - - std::set uuids; - for (int i = 0; i < 1000; ++i) - { - UUID uuid = gen.create(); - assert (uuid.version() == UUID::UUID_TIME_BASED); - assert (uuids.find(uuid) == uuids.end()); - uuids.insert(uuid); - } -} - - -void UUIDGeneratorTest::testRandom() -{ - UUIDGenerator& gen = UUIDGenerator::defaultGenerator(); - - std::set uuids; - for (int i = 0; i < 1000; ++i) - { - UUID uuid = gen.createRandom(); - assert (uuid.version() == UUID::UUID_RANDOM); - assert (uuids.find(uuid) == uuids.end()); - uuids.insert(uuid); - } -} - - -void UUIDGeneratorTest::testNameBased() -{ - UUIDGenerator& gen = UUIDGenerator::defaultGenerator(); - - UUID uuid1 = gen.createFromName(UUID::uri(), "http://www.appinf.com/uuid"); - assert (uuid1.version() == UUID::UUID_NAME_BASED); - assert (uuid1.variant() == 2); - - UUID uuid2 = gen.createFromName(UUID::uri(), "http://www.appinf.com/uuid2"); - assert (uuid2 != uuid1); - - UUID uuid3 = gen.createFromName(UUID::dns(), "www.appinf.com"); - assert (uuid3 != uuid1); - - UUID uuid4 = gen.createFromName(UUID::oid(), "1.3.6.1.4.1"); - assert (uuid4 != uuid1); - - UUID uuid5 = gen.createFromName(UUID::x500(), "cn=Guenter Obiltschnig, ou=People, o=Applied Informatics, c=at"); - assert (uuid5 != uuid1); - - UUID uuid6 = gen.createFromName(UUID::uri(), "http://www.appinf.com/uuid"); - assert (uuid6 == uuid1); -} - - -void UUIDGeneratorTest::setUp() -{ -} - - -void UUIDGeneratorTest::tearDown() -{ -} - - -CppUnit::Test* UUIDGeneratorTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("UUIDGeneratorTest"); - - CppUnit_addTest(pSuite, UUIDGeneratorTest, testTimeBased); - CppUnit_addTest(pSuite, UUIDGeneratorTest, testRandom); - CppUnit_addTest(pSuite, UUIDGeneratorTest, testNameBased); - - return pSuite; -} +// +// UUIDGeneratorTest.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/UUIDGeneratorTest.cpp#1 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "UUIDGeneratorTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/UUIDGenerator.h" +#include "Poco/UUID.h" +#include + + +using Poco::UUIDGenerator; +using Poco::UUID; + + +UUIDGeneratorTest::UUIDGeneratorTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +UUIDGeneratorTest::~UUIDGeneratorTest() +{ +} + + +void UUIDGeneratorTest::testTimeBased() +{ + UUIDGenerator& gen = UUIDGenerator::defaultGenerator(); + + std::set uuids; + for (int i = 0; i < 1000; ++i) + { + UUID uuid = gen.create(); + assert (uuid.version() == UUID::UUID_TIME_BASED); + assert (uuids.find(uuid) == uuids.end()); + uuids.insert(uuid); + } +} + + +void UUIDGeneratorTest::testRandom() +{ + UUIDGenerator& gen = UUIDGenerator::defaultGenerator(); + + std::set uuids; + for (int i = 0; i < 1000; ++i) + { + UUID uuid = gen.createRandom(); + assert (uuid.version() == UUID::UUID_RANDOM); + assert (uuids.find(uuid) == uuids.end()); + uuids.insert(uuid); + } +} + + +void UUIDGeneratorTest::testNameBased() +{ + UUIDGenerator& gen = UUIDGenerator::defaultGenerator(); + + UUID uuid1 = gen.createFromName(UUID::uri(), "http://www.appinf.com/uuid"); + assert (uuid1.version() == UUID::UUID_NAME_BASED); + assert (uuid1.variant() == 2); + + UUID uuid2 = gen.createFromName(UUID::uri(), "http://www.appinf.com/uuid2"); + assert (uuid2 != uuid1); + + UUID uuid3 = gen.createFromName(UUID::dns(), "www.appinf.com"); + assert (uuid3 != uuid1); + + UUID uuid4 = gen.createFromName(UUID::oid(), "1.3.6.1.4.1"); + assert (uuid4 != uuid1); + + UUID uuid5 = gen.createFromName(UUID::x500(), "cn=Guenter Obiltschnig, ou=People, o=Applied Informatics, c=at"); + assert (uuid5 != uuid1); + + UUID uuid6 = gen.createFromName(UUID::uri(), "http://www.appinf.com/uuid"); + assert (uuid6 == uuid1); +} + + +void UUIDGeneratorTest::setUp() +{ +} + + +void UUIDGeneratorTest::tearDown() +{ +} + + +CppUnit::Test* UUIDGeneratorTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("UUIDGeneratorTest"); + + CppUnit_addTest(pSuite, UUIDGeneratorTest, testTimeBased); + CppUnit_addTest(pSuite, UUIDGeneratorTest, testRandom); + CppUnit_addTest(pSuite, UUIDGeneratorTest, testNameBased); + + return pSuite; +} diff --git a/Foundation/testsuite/src/UUIDGeneratorTest.h b/Foundation/testsuite/src/UUIDGeneratorTest.h index 965494fa6..eb3b54603 100644 --- a/Foundation/testsuite/src/UUIDGeneratorTest.h +++ b/Foundation/testsuite/src/UUIDGeneratorTest.h @@ -1,62 +1,62 @@ -// -// UUIDGeneratorTest.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/UUIDGeneratorTest.h#1 $ -// -// Definition of the UUIDGeneratorTest class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 UUIDGeneratorTest_INCLUDED -#define UUIDGeneratorTest_INCLUDED - - -#include "Poco/Foundation.h" -#include "CppUnit/TestCase.h" - - -class UUIDGeneratorTest: public CppUnit::TestCase -{ -public: - UUIDGeneratorTest(const std::string& name); - ~UUIDGeneratorTest(); - - void testTimeBased(); - void testRandom(); - void testNameBased(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // UUIDGeneratorTest_INCLUDED +// +// UUIDGeneratorTest.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/UUIDGeneratorTest.h#1 $ +// +// Definition of the UUIDGeneratorTest class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 UUIDGeneratorTest_INCLUDED +#define UUIDGeneratorTest_INCLUDED + + +#include "Poco/Foundation.h" +#include "CppUnit/TestCase.h" + + +class UUIDGeneratorTest: public CppUnit::TestCase +{ +public: + UUIDGeneratorTest(const std::string& name); + ~UUIDGeneratorTest(); + + void testTimeBased(); + void testRandom(); + void testNameBased(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // UUIDGeneratorTest_INCLUDED diff --git a/Foundation/testsuite/src/UUIDTest.cpp b/Foundation/testsuite/src/UUIDTest.cpp index 464890a0b..d9f443d65 100644 --- a/Foundation/testsuite/src/UUIDTest.cpp +++ b/Foundation/testsuite/src/UUIDTest.cpp @@ -1,189 +1,189 @@ -// -// UUIDTest.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/UUIDTest.cpp#1 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "UUIDTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/UUID.h" - - -using Poco::UUID; - - -UUIDTest::UUIDTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -UUIDTest::~UUIDTest() -{ -} - - -void UUIDTest::testParse() -{ - UUID uuid("6ba7b810-9dad-11d1-80b4-00c04fd430c8"); - assert (uuid.toString() == "6ba7b810-9dad-11d1-80b4-00c04fd430c8"); - - uuid.parse("6BA7B810-9DAD-11D1-80B4-00C04FD430C8"); - assert (uuid.toString() == "6ba7b810-9dad-11d1-80b4-00c04fd430c8"); -} - - -void UUIDTest::testBuffer() -{ - UUID uuid("6ba7b810-9dad-11d1-80b4-00c04fd430c8"); - char buffer[16]; - uuid.copyTo(buffer); - UUID uuid2; - uuid2.copyFrom(buffer); - assert (uuid2.toString() == "6ba7b810-9dad-11d1-80b4-00c04fd430c8"); -} - - -void UUIDTest::testCompare() -{ - UUID nil; - assert (nil.isNil()); - assert (UUID::nil().isNil()); - - UUID uuid1 = nil; - UUID uuid2; - assert (uuid1.isNil()); - assert (uuid1 == nil); - assert (!(uuid1 != nil)); - assert (uuid1 >= nil); - assert (uuid1 <= nil); - assert (!(uuid1 > nil)); - assert (!(uuid1 < nil)); - assert (uuid1.toString() == "00000000-0000-0000-0000-000000000000"); - - uuid1 = UUID::dns(); - assert (!uuid1.isNil()); - assert (uuid1 != nil); - assert (!(uuid1 == nil)); - assert (uuid1 >= nil); - assert (!(uuid1 <= nil)); - assert (uuid1 > nil); - assert (!(uuid1 < nil)); - assert (uuid1.toString() == "6ba7b810-9dad-11d1-80b4-00c04fd430c8"); - - assert (nil != uuid1); - assert (!(nil == uuid1)); - assert (!(nil >= uuid1)); - assert (nil <= uuid1); - assert (!(nil > uuid1)); - assert (nil < uuid1); - - uuid2 = uuid1; - assert (uuid2 == uuid1); - assert (!(uuid2 != uuid1)); - assert (uuid2 >= uuid1); - assert (uuid2 <= uuid1); - assert (!(uuid2 > uuid1)); - assert (!(uuid2 < uuid1)); -} - - -void UUIDTest::testVersion() -{ - UUID uuid("db4fa7e9-9e62-4597-99e0-b1ec0b59800e"); - UUID::Version v = uuid.version(); - assert (v == UUID::UUID_RANDOM); - - uuid.parse("6ba7b810-9dad-11d1-80b4-00c04fd430c8"); - v = uuid.version(); - assert (v == UUID::UUID_TIME_BASED); - - uuid.parse("d2ee4220-3625-11d9-9669-0800200c9a66"); - v = uuid.version(); - assert (v == UUID::UUID_TIME_BASED); - - uuid.parse("360d3652-4411-4786-bbe6-b9675b548559"); - v = uuid.version(); - assert (v == UUID::UUID_RANDOM); -} - - -void UUIDTest::testVariant() -{ - UUID uuid("db4fa7e9-9e62-4597-99e0-b1ec0b59800e"); - int v = uuid.variant(); - assert (v == 2); - - uuid.parse("6ba7b810-9dad-11d1-80b4-00c04fd430c8"); - v = uuid.variant(); - assert (v == 2); - - uuid.parse("d2ee4220-3625-11d9-9669-0800200c9a66"); - v = uuid.variant(); - assert (v == 2); - - uuid.parse("360d3652-4411-4786-bbe6-b9675b548559"); - v = uuid.variant(); - assert (v == 2); -} - - -void UUIDTest::testSwap() -{ - UUID uuid1("db4fa7e9-9e62-4597-99e0-b1ec0b59800e"); - UUID uuid2("d2ee4220-3625-11d9-9669-0800200c9a66"); - uuid1.swap(uuid2); - assert (uuid1.toString() == "d2ee4220-3625-11d9-9669-0800200c9a66"); - assert (uuid2.toString() == "db4fa7e9-9e62-4597-99e0-b1ec0b59800e"); -} - - -void UUIDTest::setUp() -{ -} - - -void UUIDTest::tearDown() -{ -} - - -CppUnit::Test* UUIDTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("UUIDTest"); - - CppUnit_addTest(pSuite, UUIDTest, testParse); - CppUnit_addTest(pSuite, UUIDTest, testBuffer); - CppUnit_addTest(pSuite, UUIDTest, testCompare); - CppUnit_addTest(pSuite, UUIDTest, testVersion); - CppUnit_addTest(pSuite, UUIDTest, testVariant); - CppUnit_addTest(pSuite, UUIDTest, testSwap); - - return pSuite; -} +// +// UUIDTest.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/UUIDTest.cpp#1 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "UUIDTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/UUID.h" + + +using Poco::UUID; + + +UUIDTest::UUIDTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +UUIDTest::~UUIDTest() +{ +} + + +void UUIDTest::testParse() +{ + UUID uuid("6ba7b810-9dad-11d1-80b4-00c04fd430c8"); + assert (uuid.toString() == "6ba7b810-9dad-11d1-80b4-00c04fd430c8"); + + uuid.parse("6BA7B810-9DAD-11D1-80B4-00C04FD430C8"); + assert (uuid.toString() == "6ba7b810-9dad-11d1-80b4-00c04fd430c8"); +} + + +void UUIDTest::testBuffer() +{ + UUID uuid("6ba7b810-9dad-11d1-80b4-00c04fd430c8"); + char buffer[16]; + uuid.copyTo(buffer); + UUID uuid2; + uuid2.copyFrom(buffer); + assert (uuid2.toString() == "6ba7b810-9dad-11d1-80b4-00c04fd430c8"); +} + + +void UUIDTest::testCompare() +{ + UUID nil; + assert (nil.isNil()); + assert (UUID::nil().isNil()); + + UUID uuid1 = nil; + UUID uuid2; + assert (uuid1.isNil()); + assert (uuid1 == nil); + assert (!(uuid1 != nil)); + assert (uuid1 >= nil); + assert (uuid1 <= nil); + assert (!(uuid1 > nil)); + assert (!(uuid1 < nil)); + assert (uuid1.toString() == "00000000-0000-0000-0000-000000000000"); + + uuid1 = UUID::dns(); + assert (!uuid1.isNil()); + assert (uuid1 != nil); + assert (!(uuid1 == nil)); + assert (uuid1 >= nil); + assert (!(uuid1 <= nil)); + assert (uuid1 > nil); + assert (!(uuid1 < nil)); + assert (uuid1.toString() == "6ba7b810-9dad-11d1-80b4-00c04fd430c8"); + + assert (nil != uuid1); + assert (!(nil == uuid1)); + assert (!(nil >= uuid1)); + assert (nil <= uuid1); + assert (!(nil > uuid1)); + assert (nil < uuid1); + + uuid2 = uuid1; + assert (uuid2 == uuid1); + assert (!(uuid2 != uuid1)); + assert (uuid2 >= uuid1); + assert (uuid2 <= uuid1); + assert (!(uuid2 > uuid1)); + assert (!(uuid2 < uuid1)); +} + + +void UUIDTest::testVersion() +{ + UUID uuid("db4fa7e9-9e62-4597-99e0-b1ec0b59800e"); + UUID::Version v = uuid.version(); + assert (v == UUID::UUID_RANDOM); + + uuid.parse("6ba7b810-9dad-11d1-80b4-00c04fd430c8"); + v = uuid.version(); + assert (v == UUID::UUID_TIME_BASED); + + uuid.parse("d2ee4220-3625-11d9-9669-0800200c9a66"); + v = uuid.version(); + assert (v == UUID::UUID_TIME_BASED); + + uuid.parse("360d3652-4411-4786-bbe6-b9675b548559"); + v = uuid.version(); + assert (v == UUID::UUID_RANDOM); +} + + +void UUIDTest::testVariant() +{ + UUID uuid("db4fa7e9-9e62-4597-99e0-b1ec0b59800e"); + int v = uuid.variant(); + assert (v == 2); + + uuid.parse("6ba7b810-9dad-11d1-80b4-00c04fd430c8"); + v = uuid.variant(); + assert (v == 2); + + uuid.parse("d2ee4220-3625-11d9-9669-0800200c9a66"); + v = uuid.variant(); + assert (v == 2); + + uuid.parse("360d3652-4411-4786-bbe6-b9675b548559"); + v = uuid.variant(); + assert (v == 2); +} + + +void UUIDTest::testSwap() +{ + UUID uuid1("db4fa7e9-9e62-4597-99e0-b1ec0b59800e"); + UUID uuid2("d2ee4220-3625-11d9-9669-0800200c9a66"); + uuid1.swap(uuid2); + assert (uuid1.toString() == "d2ee4220-3625-11d9-9669-0800200c9a66"); + assert (uuid2.toString() == "db4fa7e9-9e62-4597-99e0-b1ec0b59800e"); +} + + +void UUIDTest::setUp() +{ +} + + +void UUIDTest::tearDown() +{ +} + + +CppUnit::Test* UUIDTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("UUIDTest"); + + CppUnit_addTest(pSuite, UUIDTest, testParse); + CppUnit_addTest(pSuite, UUIDTest, testBuffer); + CppUnit_addTest(pSuite, UUIDTest, testCompare); + CppUnit_addTest(pSuite, UUIDTest, testVersion); + CppUnit_addTest(pSuite, UUIDTest, testVariant); + CppUnit_addTest(pSuite, UUIDTest, testSwap); + + return pSuite; +} diff --git a/Foundation/testsuite/src/UUIDTest.h b/Foundation/testsuite/src/UUIDTest.h index 3186d15ef..53cbe5aa4 100644 --- a/Foundation/testsuite/src/UUIDTest.h +++ b/Foundation/testsuite/src/UUIDTest.h @@ -1,65 +1,65 @@ -// -// UUIDTest.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/UUIDTest.h#1 $ -// -// Definition of the UUIDTest class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 UUIDTest_INCLUDED -#define UUIDTest_INCLUDED - - -#include "Poco/Foundation.h" -#include "CppUnit/TestCase.h" - - -class UUIDTest: public CppUnit::TestCase -{ -public: - UUIDTest(const std::string& name); - ~UUIDTest(); - - void testParse(); - void testBuffer(); - void testCompare(); - void testVersion(); - void testVariant(); - void testSwap(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // UUIDTest_INCLUDED +// +// UUIDTest.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/UUIDTest.h#1 $ +// +// Definition of the UUIDTest class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 UUIDTest_INCLUDED +#define UUIDTest_INCLUDED + + +#include "Poco/Foundation.h" +#include "CppUnit/TestCase.h" + + +class UUIDTest: public CppUnit::TestCase +{ +public: + UUIDTest(const std::string& name); + ~UUIDTest(); + + void testParse(); + void testBuffer(); + void testCompare(); + void testVersion(); + void testVariant(); + void testSwap(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // UUIDTest_INCLUDED diff --git a/Foundation/testsuite/src/UUIDTestSuite.cpp b/Foundation/testsuite/src/UUIDTestSuite.cpp index 58aed7931..a598cf5f4 100644 --- a/Foundation/testsuite/src/UUIDTestSuite.cpp +++ b/Foundation/testsuite/src/UUIDTestSuite.cpp @@ -1,46 +1,46 @@ -// -// UUIDTestSuite.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/UUIDTestSuite.cpp#1 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "UUIDTestSuite.h" -#include "UUIDTest.h" -#include "UUIDGeneratorTest.h" - - -CppUnit::Test* UUIDTestSuite::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("UUIDTestSuite"); - - pSuite->addTest(UUIDTest::suite()); - pSuite->addTest(UUIDGeneratorTest::suite()); - - return pSuite; -} +// +// UUIDTestSuite.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/UUIDTestSuite.cpp#1 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "UUIDTestSuite.h" +#include "UUIDTest.h" +#include "UUIDGeneratorTest.h" + + +CppUnit::Test* UUIDTestSuite::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("UUIDTestSuite"); + + pSuite->addTest(UUIDTest::suite()); + pSuite->addTest(UUIDGeneratorTest::suite()); + + return pSuite; +} diff --git a/Foundation/testsuite/src/UUIDTestSuite.h b/Foundation/testsuite/src/UUIDTestSuite.h index 9f36a1b73..6270b17ce 100644 --- a/Foundation/testsuite/src/UUIDTestSuite.h +++ b/Foundation/testsuite/src/UUIDTestSuite.h @@ -1,49 +1,49 @@ -// -// UUIDTestSuite.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/UUIDTestSuite.h#1 $ -// -// Definition of the UUIDTestSuite class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 UUIDTestSuite_INCLUDED -#define UUIDTestSuite_INCLUDED - - -#include "CppUnit/TestSuite.h" - - -class UUIDTestSuite -{ -public: - static CppUnit::Test* suite(); -}; - - -#endif // UUIDTestSuite_INCLUDED +// +// UUIDTestSuite.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/UUIDTestSuite.h#1 $ +// +// Definition of the UUIDTestSuite class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 UUIDTestSuite_INCLUDED +#define UUIDTestSuite_INCLUDED + + +#include "CppUnit/TestSuite.h" + + +class UUIDTestSuite +{ +public: + static CppUnit::Test* suite(); +}; + + +#endif // UUIDTestSuite_INCLUDED diff --git a/Foundation/testsuite/src/WinDriver.cpp b/Foundation/testsuite/src/WinDriver.cpp index a41c3d8ac..b386bf94b 100644 --- a/Foundation/testsuite/src/WinDriver.cpp +++ b/Foundation/testsuite/src/WinDriver.cpp @@ -1,50 +1,50 @@ -// -// WinDriver.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/WinDriver.cpp#1 $ -// -// Test driver for Windows. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "WinTestRunner/WinTestRunner.h" -#include "FoundationTestSuite.h" - - -class TestDriver: public CppUnit::WinTestRunnerApp -{ - void TestMain() - { - CppUnit::WinTestRunner runner; - runner.addTest(FoundationTestSuite::suite()); - runner.run(); - } -}; - - -TestDriver theDriver; +// +// WinDriver.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/WinDriver.cpp#1 $ +// +// Test driver for Windows. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "WinTestRunner/WinTestRunner.h" +#include "FoundationTestSuite.h" + + +class TestDriver: public CppUnit::WinTestRunnerApp +{ + void TestMain() + { + CppUnit::WinTestRunner runner; + runner.addTest(FoundationTestSuite::suite()); + runner.run(); + } +}; + + +TestDriver theDriver; diff --git a/Foundation/testsuite/src/ZLibTest.cpp b/Foundation/testsuite/src/ZLibTest.cpp index e1715d984..52c15758a 100644 --- a/Foundation/testsuite/src/ZLibTest.cpp +++ b/Foundation/testsuite/src/ZLibTest.cpp @@ -1,174 +1,174 @@ -// -// ZLibTest.cpp -// -// $Id: //poco/1.2/Foundation/testsuite/src/ZLibTest.cpp#1 $ -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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. -// - - -#include "ZLibTest.h" -#include "CppUnit/TestCaller.h" -#include "CppUnit/TestSuite.h" -#include "Poco/InflatingStream.h" -#include "Poco/DeflatingStream.h" -#include "Poco/StreamCopier.h" -#include - - -using Poco::InflatingInputStream; -using Poco::InflatingOutputStream; -using Poco::DeflatingOutputStream; -using Poco::DeflatingInputStream; -using Poco::InflatingStreamBuf; -using Poco::DeflatingStreamBuf; -using Poco::StreamCopier; - - -ZLibTest::ZLibTest(const std::string& name): CppUnit::TestCase(name) -{ -} - - -ZLibTest::~ZLibTest() -{ -} - - -void ZLibTest::testDeflate1() -{ - std::stringstream buffer; - DeflatingOutputStream deflater(buffer); - deflater << "abcdefabcdefabcdefabcdefabcdefabcdef" << std::endl; - deflater << "abcdefabcdefabcdefabcdefabcdefabcdef" << std::endl; - deflater.close(); - InflatingInputStream inflater(buffer); - std::string data; - inflater >> data; - assert (data == "abcdefabcdefabcdefabcdefabcdefabcdef"); - inflater >> data; - assert (data == "abcdefabcdefabcdefabcdefabcdefabcdef"); -} - - -void ZLibTest::testDeflate2() -{ - std::stringstream buffer; - DeflatingOutputStream deflater(buffer); - deflater << "abcdefabcdefabcdefabcdefabcdefabcdef" << std::endl; - deflater << "abcdefabcdefabcdefabcdefabcdefabcdef" << std::endl; - deflater.close(); - std::stringstream buffer2; - InflatingOutputStream inflater(buffer2); - StreamCopier::copyStream(buffer, inflater); - inflater.close(); - std::string data; - buffer2 >> data; - assert (data == "abcdefabcdefabcdefabcdefabcdefabcdef"); - buffer2 >> data; - assert (data == "abcdefabcdefabcdefabcdefabcdefabcdef"); -} - - -void ZLibTest::testDeflate3() -{ - std::stringstream buffer; - buffer << "abcdefabcdefabcdefabcdefabcdefabcdef" << std::endl; - buffer << "abcdefabcdefabcdefabcdefabcdefabcdef" << std::endl; - DeflatingInputStream deflater(buffer); - std::stringstream buffer2; - StreamCopier::copyStream(deflater, buffer2); - std::stringstream buffer3; - InflatingOutputStream inflater(buffer3); - StreamCopier::copyStream(buffer2, inflater); - inflater.close(); - std::string data; - buffer3 >> data; - assert (data == "abcdefabcdefabcdefabcdefabcdefabcdef"); - buffer3 >> data; - assert (data == "abcdefabcdefabcdefabcdefabcdefabcdef"); -} - - -void ZLibTest::testGzip1() -{ - std::stringstream buffer; - DeflatingOutputStream deflater(buffer, DeflatingStreamBuf::STREAM_GZIP); - deflater << "abcdefabcdefabcdefabcdefabcdefabcdef" << std::endl; - deflater << "abcdefabcdefabcdefabcdefabcdefabcdef" << std::endl; - deflater.close(); - InflatingInputStream inflater(buffer, InflatingStreamBuf::STREAM_GZIP); - std::string data; - inflater >> data; - assert (data == "abcdefabcdefabcdefabcdefabcdefabcdef"); - inflater >> data; - assert (data == "abcdefabcdefabcdefabcdefabcdefabcdef"); -} - - -void ZLibTest::testGzip2() -{ - // created with gzip ("Hello, world!"): - const unsigned char gzdata[] = - { - 0x1f, 0x8b, 0x08, 0x08, 0xb0, 0x73, 0xd0, 0x41, 0x00, 0x03, 0x68, 0x77, 0x00, 0xf3, 0x48, 0xcd, - 0xc9, 0xc9, 0xd7, 0x51, 0x28, 0xcf, 0x2f, 0xca, 0x49, 0x51, 0xe4, 0x02, 0x00, 0x18, 0xa7, 0x55, - 0x7b, 0x0e, 0x00, 0x00, 0x00, 0x00 - }; - - std::string gzstr((char*) gzdata, sizeof(gzdata)); - std::istringstream istr(gzstr); - InflatingInputStream inflater(istr, InflatingStreamBuf::STREAM_GZIP); - std::string data; - inflater >> data; - assert (data == "Hello,"); - inflater >> data; - assert (data == "world!"); -} - - -void ZLibTest::setUp() -{ -} - - -void ZLibTest::tearDown() -{ -} - - -CppUnit::Test* ZLibTest::suite() -{ - CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("ZLibTest"); - - CppUnit_addTest(pSuite, ZLibTest, testDeflate1); - CppUnit_addTest(pSuite, ZLibTest, testDeflate2); - CppUnit_addTest(pSuite, ZLibTest, testDeflate3); - CppUnit_addTest(pSuite, ZLibTest, testGzip1); - CppUnit_addTest(pSuite, ZLibTest, testGzip2); - - return pSuite; -} +// +// ZLibTest.cpp +// +// $Id: //poco/1.2/Foundation/testsuite/src/ZLibTest.cpp#1 $ +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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. +// + + +#include "ZLibTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/InflatingStream.h" +#include "Poco/DeflatingStream.h" +#include "Poco/StreamCopier.h" +#include + + +using Poco::InflatingInputStream; +using Poco::InflatingOutputStream; +using Poco::DeflatingOutputStream; +using Poco::DeflatingInputStream; +using Poco::InflatingStreamBuf; +using Poco::DeflatingStreamBuf; +using Poco::StreamCopier; + + +ZLibTest::ZLibTest(const std::string& name): CppUnit::TestCase(name) +{ +} + + +ZLibTest::~ZLibTest() +{ +} + + +void ZLibTest::testDeflate1() +{ + std::stringstream buffer; + DeflatingOutputStream deflater(buffer); + deflater << "abcdefabcdefabcdefabcdefabcdefabcdef" << std::endl; + deflater << "abcdefabcdefabcdefabcdefabcdefabcdef" << std::endl; + deflater.close(); + InflatingInputStream inflater(buffer); + std::string data; + inflater >> data; + assert (data == "abcdefabcdefabcdefabcdefabcdefabcdef"); + inflater >> data; + assert (data == "abcdefabcdefabcdefabcdefabcdefabcdef"); +} + + +void ZLibTest::testDeflate2() +{ + std::stringstream buffer; + DeflatingOutputStream deflater(buffer); + deflater << "abcdefabcdefabcdefabcdefabcdefabcdef" << std::endl; + deflater << "abcdefabcdefabcdefabcdefabcdefabcdef" << std::endl; + deflater.close(); + std::stringstream buffer2; + InflatingOutputStream inflater(buffer2); + StreamCopier::copyStream(buffer, inflater); + inflater.close(); + std::string data; + buffer2 >> data; + assert (data == "abcdefabcdefabcdefabcdefabcdefabcdef"); + buffer2 >> data; + assert (data == "abcdefabcdefabcdefabcdefabcdefabcdef"); +} + + +void ZLibTest::testDeflate3() +{ + std::stringstream buffer; + buffer << "abcdefabcdefabcdefabcdefabcdefabcdef" << std::endl; + buffer << "abcdefabcdefabcdefabcdefabcdefabcdef" << std::endl; + DeflatingInputStream deflater(buffer); + std::stringstream buffer2; + StreamCopier::copyStream(deflater, buffer2); + std::stringstream buffer3; + InflatingOutputStream inflater(buffer3); + StreamCopier::copyStream(buffer2, inflater); + inflater.close(); + std::string data; + buffer3 >> data; + assert (data == "abcdefabcdefabcdefabcdefabcdefabcdef"); + buffer3 >> data; + assert (data == "abcdefabcdefabcdefabcdefabcdefabcdef"); +} + + +void ZLibTest::testGzip1() +{ + std::stringstream buffer; + DeflatingOutputStream deflater(buffer, DeflatingStreamBuf::STREAM_GZIP); + deflater << "abcdefabcdefabcdefabcdefabcdefabcdef" << std::endl; + deflater << "abcdefabcdefabcdefabcdefabcdefabcdef" << std::endl; + deflater.close(); + InflatingInputStream inflater(buffer, InflatingStreamBuf::STREAM_GZIP); + std::string data; + inflater >> data; + assert (data == "abcdefabcdefabcdefabcdefabcdefabcdef"); + inflater >> data; + assert (data == "abcdefabcdefabcdefabcdefabcdefabcdef"); +} + + +void ZLibTest::testGzip2() +{ + // created with gzip ("Hello, world!"): + const unsigned char gzdata[] = + { + 0x1f, 0x8b, 0x08, 0x08, 0xb0, 0x73, 0xd0, 0x41, 0x00, 0x03, 0x68, 0x77, 0x00, 0xf3, 0x48, 0xcd, + 0xc9, 0xc9, 0xd7, 0x51, 0x28, 0xcf, 0x2f, 0xca, 0x49, 0x51, 0xe4, 0x02, 0x00, 0x18, 0xa7, 0x55, + 0x7b, 0x0e, 0x00, 0x00, 0x00, 0x00 + }; + + std::string gzstr((char*) gzdata, sizeof(gzdata)); + std::istringstream istr(gzstr); + InflatingInputStream inflater(istr, InflatingStreamBuf::STREAM_GZIP); + std::string data; + inflater >> data; + assert (data == "Hello,"); + inflater >> data; + assert (data == "world!"); +} + + +void ZLibTest::setUp() +{ +} + + +void ZLibTest::tearDown() +{ +} + + +CppUnit::Test* ZLibTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("ZLibTest"); + + CppUnit_addTest(pSuite, ZLibTest, testDeflate1); + CppUnit_addTest(pSuite, ZLibTest, testDeflate2); + CppUnit_addTest(pSuite, ZLibTest, testDeflate3); + CppUnit_addTest(pSuite, ZLibTest, testGzip1); + CppUnit_addTest(pSuite, ZLibTest, testGzip2); + + return pSuite; +} diff --git a/Foundation/testsuite/src/ZLibTest.h b/Foundation/testsuite/src/ZLibTest.h index 3b9374740..eb0e96a6d 100644 --- a/Foundation/testsuite/src/ZLibTest.h +++ b/Foundation/testsuite/src/ZLibTest.h @@ -1,64 +1,64 @@ -// -// ZLibTest.h -// -// $Id: //poco/1.2/Foundation/testsuite/src/ZLibTest.h#1 $ -// -// Definition of the ZLibTest class. -// -// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// 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 ZLibTest_INCLUDED -#define ZLibTest_INCLUDED - - -#include "Poco/Foundation.h" -#include "CppUnit/TestCase.h" - - -class ZLibTest: public CppUnit::TestCase -{ -public: - ZLibTest(const std::string& name); - ~ZLibTest(); - - void testDeflate1(); - void testDeflate2(); - void testDeflate3(); - void testGzip1(); - void testGzip2(); - - void setUp(); - void tearDown(); - - static CppUnit::Test* suite(); - -private: -}; - - -#endif // ZLibTest_INCLUDED +// +// ZLibTest.h +// +// $Id: //poco/1.2/Foundation/testsuite/src/ZLibTest.h#1 $ +// +// Definition of the ZLibTest class. +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// 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 ZLibTest_INCLUDED +#define ZLibTest_INCLUDED + + +#include "Poco/Foundation.h" +#include "CppUnit/TestCase.h" + + +class ZLibTest: public CppUnit::TestCase +{ +public: + ZLibTest(const std::string& name); + ~ZLibTest(); + + void testDeflate1(); + void testDeflate2(); + void testDeflate3(); + void testGzip1(); + void testGzip2(); + + void setUp(); + void tearDown(); + + static CppUnit::Test* suite(); + +private: +}; + + +#endif // ZLibTest_INCLUDED diff --git a/Foundation/testsuite/testapp.vmsbuild b/Foundation/testsuite/testapp.vmsbuild index 1d3a8427d..185aa76cc 100644 --- a/Foundation/testsuite/testapp.vmsbuild +++ b/Foundation/testsuite/testapp.vmsbuild @@ -1,7 +1,7 @@ -# -# sample.vmsbuild -# -# $Id: //poco/1.2/Foundation/testsuite/testapp.vmsbuild#1 $ -# -EXE=TestApp -TestApp +# +# sample.vmsbuild +# +# $Id: //poco/1.2/Foundation/testsuite/testapp.vmsbuild#1 $ +# +EXE=TestApp +TestApp diff --git a/Foundation/testsuite/testlibrary.opt b/Foundation/testsuite/testlibrary.opt index 9696352a6..3455edd73 100644 --- a/Foundation/testsuite/testlibrary.opt +++ b/Foundation/testsuite/testlibrary.opt @@ -1 +1 @@ -SYMBOL_VECTOR=(pocoInitializeLibrary=procedure,pocoUninitializeLibrary=procedure,pocoBuildManifest=procedure,gimmeFive=procedure) +SYMBOL_VECTOR=(pocoInitializeLibrary=procedure,pocoUninitializeLibrary=procedure,pocoBuildManifest=procedure,gimmeFive=procedure) diff --git a/Foundation/testsuite/testlibrary.vmsbuild b/Foundation/testsuite/testlibrary.vmsbuild index 71f4b9d28..282419bba 100644 --- a/Foundation/testsuite/testlibrary.vmsbuild +++ b/Foundation/testsuite/testlibrary.vmsbuild @@ -1,8 +1,8 @@ -# -# buildfiles.vms -# -# $Id: //poco/1.2/Foundation/testsuite/testlibrary.vmsbuild#1 $ -# -SHR=TestLibrary -TestPlugin -TestLibrary +# +# buildfiles.vms +# +# $Id: //poco/1.2/Foundation/testsuite/testlibrary.vmsbuild#1 $ +# +SHR=TestLibrary +TestPlugin +TestLibrary diff --git a/Foundation/testsuite/testsuite.vmsbuild b/Foundation/testsuite/testsuite.vmsbuild index 95fbba602..3b376c789 100644 --- a/Foundation/testsuite/testsuite.vmsbuild +++ b/Foundation/testsuite/testsuite.vmsbuild @@ -1,104 +1,104 @@ -# -# buildfiles.vms -# -# $Id: //poco/1.2/Foundation/testsuite/testsuite.vmsbuild#1 $ -# -EXE=TestRunner -ActiveMethodTest -ActivityTest -AutoPtrTest -SmartPtrTest -Base64Test -AutoReleasePoolTest -BinaryReaderWriterTest -ByteOrderTest -ChannelTest -ClassLoaderTest -CoreTest -CoreTestSuite -CountingStreamTest -CryptTestSuite -DateTimeFormatterTest -DateTimeParserTest -DateTimeTest -LocalDateTimeTest -DateTimeTestSuite -DigestStreamTest -Driver -DynamicFactoryTest -FPETest -FileChannelTest -FileTest -GlobTest -FilesystemTestSuite -FoundationTestSuite -HMACEngineTest -HashTest -HexBinaryTest -LoggerTest -LoggingFactoryTest -LoggingRegistryTest -LoggingTestSuite -NamedEventTest -NamedMutexTest -ProcessesTestSuite -MD2EngineTest -MD4EngineTest -MD5EngineTest -ManifestTest -NDCTest -NotificationCenterTest -NotificationQueueTest -NotificationsTestSuite -NullStreamTest -NumberFormatterTest -NumberParserTest -PathTest -PatternFormatterTest -RWLockTest -RandomStreamTest -RandomTest -RegularExpressionTest -SHA1EngineTest -SemaphoreTest -SharedLibraryTest -SharedLibraryTestSuite -StopwatchTest -StreamConverterTest -StreamCopierTest -StreamTokenizerTest -StreamsTestSuite -StringTest -StringTokenizerTest -TaskTestSuite -TaskTest -TaskManagerTest -TestChannel -TextConverterTest -TextIteratorTest -TextTestSuite -ThreadLocalTest -ThreadPoolTest -ThreadTest -ThreadingTestSuite -TimerTest -TimespanTest -TimestampTest -TimezoneTest -URIStreamOpenerTest -URITest -URITestSuite -UUIDGeneratorTest -UUIDTest -UUIDTestSuite -ZLibTest -TestPlugin -CacheTestSuite -EventTestSuite -ExpireCacheTest -ExpireLRUCacheTest -FIFOEventTest -LRUCacheTest -PriorityEventTest -AnyTest -TypesTestSuite +# +# buildfiles.vms +# +# $Id: //poco/1.2/Foundation/testsuite/testsuite.vmsbuild#1 $ +# +EXE=TestRunner +ActiveMethodTest +ActivityTest +AutoPtrTest +SmartPtrTest +Base64Test +AutoReleasePoolTest +BinaryReaderWriterTest +ByteOrderTest +ChannelTest +ClassLoaderTest +CoreTest +CoreTestSuite +CountingStreamTest +CryptTestSuite +DateTimeFormatterTest +DateTimeParserTest +DateTimeTest +LocalDateTimeTest +DateTimeTestSuite +DigestStreamTest +Driver +DynamicFactoryTest +FPETest +FileChannelTest +FileTest +GlobTest +FilesystemTestSuite +FoundationTestSuite +HMACEngineTest +HashTest +HexBinaryTest +LoggerTest +LoggingFactoryTest +LoggingRegistryTest +LoggingTestSuite +NamedEventTest +NamedMutexTest +ProcessesTestSuite +MD2EngineTest +MD4EngineTest +MD5EngineTest +ManifestTest +NDCTest +NotificationCenterTest +NotificationQueueTest +NotificationsTestSuite +NullStreamTest +NumberFormatterTest +NumberParserTest +PathTest +PatternFormatterTest +RWLockTest +RandomStreamTest +RandomTest +RegularExpressionTest +SHA1EngineTest +SemaphoreTest +SharedLibraryTest +SharedLibraryTestSuite +StopwatchTest +StreamConverterTest +StreamCopierTest +StreamTokenizerTest +StreamsTestSuite +StringTest +StringTokenizerTest +TaskTestSuite +TaskTest +TaskManagerTest +TestChannel +TextConverterTest +TextIteratorTest +TextTestSuite +ThreadLocalTest +ThreadPoolTest +ThreadTest +ThreadingTestSuite +TimerTest +TimespanTest +TimestampTest +TimezoneTest +URIStreamOpenerTest +URITest +URITestSuite +UUIDGeneratorTest +UUIDTest +UUIDTestSuite +ZLibTest +TestPlugin +CacheTestSuite +EventTestSuite +ExpireCacheTest +ExpireLRUCacheTest +FIFOEventTest +LRUCacheTest +PriorityEventTest +AnyTest +TypesTestSuite